@beeuni/sdk 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. package/README.md +53 -92
  2. package/dist/beeuni.esm.min.js +36 -34
  3. package/dist/beeuni.global.js +36 -34
  4. package/dist/browser/cache/idb-sync-cache.js +15 -5
  5. package/dist/browser/session-sync/server-transcript-mirror.d.ts +7 -1
  6. package/dist/browser/session-sync/server-transcript-mirror.js +30 -24
  7. package/dist/browser/session-sync/session-sync-registry.d.ts +3 -1
  8. package/dist/browser/session-sync/session-sync-registry.js +48 -3
  9. package/dist/browser/stores/sync-store/keep-unchanged.d.ts +4 -0
  10. package/dist/browser/stores/sync-store/keep-unchanged.js +34 -0
  11. package/dist/browser/stores/sync-store.d.ts +7 -0
  12. package/dist/browser/stores/sync-store.js +122 -35
  13. package/dist/core/attachments/prompt-attachments.d.ts +4 -0
  14. package/dist/core/attachments/prompt-attachments.js +34 -0
  15. package/dist/core/capture/rules.d.ts +17 -0
  16. package/dist/core/capture/rules.js +27 -0
  17. package/dist/core/client/beeuni.d.ts +99 -34
  18. package/dist/core/client/beeuni.js +5 -11
  19. package/dist/core/client/capture.d.ts +105 -0
  20. package/dist/core/client/capture.js +48 -0
  21. package/dist/core/client/facade-catalog.d.ts +0 -4
  22. package/dist/core/client/facade-catalog.js +1 -5
  23. package/dist/core/client/facade-identity.d.ts +1 -0
  24. package/dist/core/client/facade-identity.js +1 -0
  25. package/dist/core/client/project-access-resources.d.ts +3 -1
  26. package/dist/core/client/project-access-resources.js +1 -1
  27. package/dist/core/client/project-connections.d.ts +2 -2
  28. package/dist/core/client/project-connections.js +2 -2
  29. package/dist/core/client/project-operations-admin.d.ts +4 -4
  30. package/dist/core/client/project-operations-review.d.ts +2 -3
  31. package/dist/core/client/project-operations-review.js +1 -0
  32. package/dist/core/client/project-operations-workspace.d.ts +4 -4
  33. package/dist/core/client/project-operations-workspace.js +1 -1
  34. package/dist/core/client/project-operations.d.ts +9 -19
  35. package/dist/core/client/project-operations.js +2 -6
  36. package/dist/core/client/project-platform-security.d.ts +1 -1
  37. package/dist/core/client/project-platform-settings.d.ts +1 -1
  38. package/dist/core/client/session-context.d.ts +2 -0
  39. package/dist/core/client/session-handle.d.ts +13 -0
  40. package/dist/core/client/session-lifecycle-resources.d.ts +11 -0
  41. package/dist/core/client/session-lifecycle-resources.js +4 -0
  42. package/dist/core/client/session-lifecycle-security.d.ts +2 -0
  43. package/dist/core/client/session-lifecycle-security.js +1 -0
  44. package/dist/core/client/session-readiness.d.ts +2 -0
  45. package/dist/core/client/session-readiness.js +20 -1
  46. package/dist/core/http/api-client.d.ts +1 -7
  47. package/dist/core/http/api-client.js +2 -37
  48. package/dist/core/http/auth.d.ts +2 -4
  49. package/dist/core/http/auth.js +2 -8
  50. package/dist/core/http/config.d.ts +2 -0
  51. package/dist/core/http/response-error.js +26 -11
  52. package/dist/core/http/transport.js +6 -1
  53. package/dist/core/models/composer-model.d.ts +14 -0
  54. package/dist/core/models/composer-model.js +21 -1
  55. package/dist/core/rest/platform-client/capture.d.ts +363 -0
  56. package/dist/core/rest/platform-client/capture.js +116 -0
  57. package/dist/core/rest/platform-client/client-policy.d.ts +8 -0
  58. package/dist/core/rest/platform-client/client-policy.js +30 -0
  59. package/dist/core/rest/platform-client/index.d.ts +4 -4
  60. package/dist/core/rest/platform-client/index.js +4 -4
  61. package/dist/core/rest/platform-client/lifecycle.js +18 -12
  62. package/dist/core/rest/platform-client/shared.d.ts +5 -0
  63. package/dist/core/rest/platform-client/shared.js +18 -0
  64. package/dist/core/rest/platform-client/types.d.ts +1 -1
  65. package/dist/core/rest/projects-client/account-secret-resources.d.ts +2 -1
  66. package/dist/core/rest/projects-client/accounts.d.ts +34 -0
  67. package/dist/core/rest/projects-client/accounts.js +10 -0
  68. package/dist/core/rest/projects-client/admin-providers.d.ts +0 -61
  69. package/dist/core/rest/projects-client/admin-providers.js +0 -6
  70. package/dist/core/rest/projects-client/agent-config.d.ts +3 -0
  71. package/dist/core/rest/projects-client/apps-fleet.d.ts +5 -1
  72. package/dist/core/rest/projects-client/apps-fleet.js +2 -2
  73. package/dist/core/rest/projects-client/apps.d.ts +11 -1
  74. package/dist/core/rest/projects-client/change-requests.d.ts +2 -0
  75. package/dist/core/rest/projects-client/change-requests.js +2 -0
  76. package/dist/core/rest/projects-client/connectors.d.ts +13 -55
  77. package/dist/core/rest/projects-client/connectors.js +5 -29
  78. package/dist/core/rest/projects-client/files.d.ts +3 -0
  79. package/dist/core/rest/projects-client/files.js +4 -0
  80. package/dist/core/rest/projects-client/gateway.d.ts +5 -0
  81. package/dist/core/rest/projects-client/git-backend.d.ts +1 -10
  82. package/dist/core/rest/projects-client/git-backend.js +0 -10
  83. package/dist/core/rest/projects-client/iam-actions.d.ts +76 -0
  84. package/dist/core/rest/projects-client/iam-actions.js +101 -0
  85. package/dist/core/rest/projects-client/iam-sso.d.ts +0 -10
  86. package/dist/core/rest/projects-client/iam-sso.js +0 -3
  87. package/dist/core/rest/projects-client/iam.d.ts +1 -0
  88. package/dist/core/rest/projects-client/iam.js +1 -0
  89. package/dist/core/rest/projects-client/index.d.ts +1 -4
  90. package/dist/core/rest/projects-client/index.js +1 -4
  91. package/dist/core/rest/projects-client/notifications.d.ts +1 -1
  92. package/dist/core/rest/projects-client/notifications.js +4 -0
  93. package/dist/core/rest/projects-client/projects.d.ts +4 -2
  94. package/dist/core/rest/projects-client/projects.js +4 -2
  95. package/dist/core/rest/projects-client/review-items.d.ts +2 -0
  96. package/dist/core/rest/projects-client/review-items.js +4 -0
  97. package/dist/core/rest/projects-client/review.d.ts +17 -3
  98. package/dist/core/rest/projects-client/review.js +11 -0
  99. package/dist/core/rest/projects-client/sandbox.d.ts +8 -9
  100. package/dist/core/rest/projects-client/secrets.d.ts +3 -0
  101. package/dist/core/rest/projects-client/session-attachments.js +14 -1
  102. package/dist/core/rest/projects-client/session-sandbox.d.ts +1 -1
  103. package/dist/core/rest/projects-client/sessions.d.ts +31 -4
  104. package/dist/core/rest/projects-client/sessions.js +34 -4
  105. package/dist/core/runtime/runtime-rest-client.js +1 -1
  106. package/dist/core/runtime/runtime-types.d.ts +1 -0
  107. package/dist/core/session/control-stream.d.ts +1 -0
  108. package/dist/core/session/control-stream.js +18 -1
  109. package/dist/core/session/open-bundle.d.ts +4 -4
  110. package/dist/core/session/open-bundle.js +29 -46
  111. package/dist/core/session/turn-end-watch.d.ts +47 -0
  112. package/dist/core/session/turn-end-watch.js +141 -0
  113. package/dist/core/session-log/guard.d.ts +6 -0
  114. package/dist/core/session-log/guard.js +109 -0
  115. package/dist/core/session-log/index.d.ts +7 -0
  116. package/dist/core/session-log/index.js +5 -0
  117. package/dist/core/session-log/saved-log.d.ts +10 -0
  118. package/dist/core/session-log/saved-log.js +25 -0
  119. package/dist/core/session-log/source.d.ts +25 -0
  120. package/dist/core/session-log/source.js +30 -0
  121. package/dist/core/session-log/store.d.ts +21 -0
  122. package/dist/core/session-log/store.js +126 -0
  123. package/dist/core/session-log/tool-call.d.ts +11 -0
  124. package/dist/core/session-log/tool-call.js +65 -0
  125. package/dist/core/session-log/turns/blocks.d.ts +60 -0
  126. package/dist/core/session-log/turns/blocks.js +124 -0
  127. package/dist/core/session-log/turns/history.d.ts +32 -0
  128. package/dist/core/session-log/turns/history.js +99 -0
  129. package/dist/core/session-log/turns/index.d.ts +4 -0
  130. package/dist/core/session-log/turns/index.js +4 -0
  131. package/dist/core/session-log/turns/metrics.d.ts +21 -0
  132. package/dist/core/session-log/turns/metrics.js +29 -0
  133. package/dist/core/session-log/turns/turn.d.ts +55 -0
  134. package/dist/core/session-log/turns/turn.js +279 -0
  135. package/dist/core/session-log/turns/v1-parts.d.ts +8 -0
  136. package/dist/core/session-log/turns/v1-parts.js +43 -0
  137. package/dist/core/session-log/types.d.ts +264 -0
  138. package/dist/core/session-log/types.js +6 -0
  139. package/dist/core/session-log/v1-view.d.ts +13 -0
  140. package/dist/core/session-log/v1-view.js +215 -0
  141. package/dist/core/session-log/v1.d.ts +31 -0
  142. package/dist/core/session-log/v1.js +473 -0
  143. package/dist/core/session-sync/copy-store-types.d.ts +19 -0
  144. package/dist/core/session-sync/copy-store-types.js +1 -0
  145. package/dist/core/session-sync/saved-copy-store.js +25 -4
  146. package/dist/core/session-sync/saved-transcript.d.ts +15 -1
  147. package/dist/core/session-sync/saved-transcript.js +55 -0
  148. package/dist/core/session-sync/session-sync-controller.js +3 -0
  149. package/dist/core/stream/event-stream.js +2 -2
  150. package/dist/core/turns/classify.d.ts +2 -1
  151. package/dist/core/turns/classify.js +7 -3
  152. package/dist/core/turns/edit-blocks.d.ts +1 -0
  153. package/dist/core/turns/edit-blocks.js +15 -0
  154. package/dist/core/turns/parts.d.ts +3 -2
  155. package/dist/core/turns/parts.js +4 -2
  156. package/dist/core/turns/segments/burst-summary.d.ts +1 -0
  157. package/dist/core/turns/segments/burst-summary.js +24 -0
  158. package/dist/core/turns/segments/group-steps.d.ts +4 -3
  159. package/dist/core/turns/segments/group-steps.js +9 -6
  160. package/dist/core/turns/segments/index.d.ts +1 -0
  161. package/dist/core/turns/segments/index.js +1 -0
  162. package/dist/core/turns/segments/narration.d.ts +5 -4
  163. package/dist/core/turns/segments/narration.js +12 -3
  164. package/dist/core/turns/segments/session-activity-groups.d.ts +2 -1
  165. package/dist/core/turns/segments/session-activity-groups.js +3 -1
  166. package/dist/core/turns/segments/step-label.d.ts +2 -1
  167. package/dist/core/turns/segments/step-label.js +3 -1
  168. package/dist/core/turns/segments/work-split.d.ts +10 -0
  169. package/dist/core/turns/segments/work-split.js +40 -0
  170. package/dist/core/turns/segments/working-turn.d.ts +4 -2
  171. package/dist/core/turns/segments/working-turn.js +9 -8
  172. package/dist/core/turns/state.d.ts +2 -7
  173. package/dist/core/turns/state.js +28 -134
  174. package/dist/core/turns/tool-kind.d.ts +1 -1
  175. package/dist/core/turns/tool-kind.js +3 -2
  176. package/dist/core/turns/tool-registry.js +1 -0
  177. package/dist/core/turns/tools/tool-meta.d.ts +3 -2
  178. package/dist/core/turns/tools/tool-meta.js +5 -2
  179. package/dist/core/turns/tools/tool-outcome.d.ts +2 -1
  180. package/dist/core/turns/tools/tool-outcome.js +3 -1
  181. package/dist/core/turns/types.d.ts +1 -1
  182. package/dist/core/turns/view-model.js +1 -13
  183. package/dist/core/warm-session-pool.d.ts +29 -0
  184. package/dist/core/warm-session-pool.js +127 -0
  185. package/dist/genui/catalog.d.ts +28 -0
  186. package/dist/genui/catalog.js +396 -0
  187. package/dist/genui/expansion.d.ts +3 -0
  188. package/dist/genui/expansion.js +295 -0
  189. package/dist/genui/fence-entry.d.ts +2 -0
  190. package/dist/genui/fence-entry.js +1 -0
  191. package/dist/genui/fence.d.ts +21 -0
  192. package/dist/genui/fence.js +138 -0
  193. package/dist/genui/index.d.ts +6 -0
  194. package/dist/genui/index.js +6 -0
  195. package/dist/genui/markdown.d.ts +12 -0
  196. package/dist/genui/markdown.js +104 -0
  197. package/dist/genui/parse.d.ts +6 -0
  198. package/dist/genui/parse.js +75 -0
  199. package/dist/genui/prompt.d.ts +2 -0
  200. package/dist/genui/prompt.js +206 -0
  201. package/dist/genui/react/default-components.d.ts +2 -0
  202. package/dist/genui/react/default-components.js +72 -0
  203. package/dist/genui/react/default-components.test.d.ts +1 -0
  204. package/dist/genui/react/default-components.test.js +94 -0
  205. package/dist/genui/react/genui-block-disabled.test.d.ts +1 -0
  206. package/dist/genui/react/genui-block-disabled.test.js +50 -0
  207. package/dist/genui/react/genui-block.d.ts +28 -0
  208. package/dist/genui/react/genui-block.js +91 -0
  209. package/dist/genui/react/genui-block.test.d.ts +1 -0
  210. package/dist/genui/react/genui-block.test.js +205 -0
  211. package/dist/genui/react/index.d.ts +2 -0
  212. package/dist/genui/react/index.js +2 -0
  213. package/dist/genui/share.d.ts +5 -0
  214. package/dist/genui/share.js +30 -0
  215. package/dist/genui/test-fixtures.d.ts +2 -0
  216. package/dist/genui/test-fixtures.js +16 -0
  217. package/dist/genui/types.d.ts +29 -0
  218. package/dist/genui/types.js +1 -0
  219. package/dist/genui/urls.d.ts +1 -0
  220. package/dist/genui/urls.js +18 -0
  221. package/dist/genui/validate.d.ts +9 -0
  222. package/dist/genui/validate.js +116 -0
  223. package/dist/index.d.ts +4 -4
  224. package/dist/index.js +4 -4
  225. package/dist/internal/connector-catalog.d.ts +48 -0
  226. package/dist/internal/connector-catalog.js +27 -0
  227. package/dist/internal/host-configuration.d.ts +22 -0
  228. package/dist/internal/host-configuration.js +28 -0
  229. package/dist/internal/platform-admin-react.d.ts +12 -0
  230. package/dist/internal/platform-admin-react.js +13 -0
  231. package/dist/internal/platform-admin.d.ts +9 -0
  232. package/dist/internal/platform-admin.js +9 -0
  233. package/dist/platform/ui.d.ts +8 -2
  234. package/dist/platform/ui.js +19 -4
  235. package/dist/react/chat/use-chat-turns.d.ts +1 -1
  236. package/dist/react/human-presence.d.ts +9 -0
  237. package/dist/react/human-presence.js +12 -0
  238. package/dist/react/index.d.ts +4 -13
  239. package/dist/react/index.js +4 -13
  240. package/dist/react/opencode.d.ts +1 -0
  241. package/dist/react/opencode.js +1 -0
  242. package/dist/react/query-contracts.d.ts +6 -0
  243. package/dist/react/query-contracts.js +6 -0
  244. package/dist/react/query-keys.d.ts +17 -2
  245. package/dist/react/query-keys.js +24 -2
  246. package/dist/react/reset-identity-state.js +2 -0
  247. package/dist/react/session-cache-write.d.ts +1 -0
  248. package/dist/react/session-cache-write.js +20 -0
  249. package/dist/react/session-transcript-subscription.js +3 -1
  250. package/dist/react/sign-in-with-beeuni.d.ts +6 -6
  251. package/dist/react/turn-end-handoff.d.ts +13 -0
  252. package/dist/react/turn-end-handoff.js +101 -0
  253. package/dist/react/use-admin-providers.d.ts +3 -6
  254. package/dist/react/use-admin-providers.js +1 -11
  255. package/dist/react/use-capture.d.ts +47 -0
  256. package/dist/react/use-capture.js +173 -0
  257. package/dist/react/use-feature-flag.js +1 -0
  258. package/dist/react/use-opencode-events/handle-event.d.ts +1 -0
  259. package/dist/react/use-opencode-events/handle-event.js +5 -0
  260. package/dist/react/use-opencode-events/handle-interaction-event.js +8 -3
  261. package/dist/react/use-opencode-events/handle-session-event.js +13 -8
  262. package/dist/react/use-opencode-events/handler-context.d.ts +1 -0
  263. package/dist/react/use-opencode-events/helpers.d.ts +1 -0
  264. package/dist/react/use-opencode-events/helpers.js +11 -1
  265. package/dist/react/use-opencode-events/index.js +1 -0
  266. package/dist/react/use-opencode-local.d.ts +5 -1
  267. package/dist/react/use-opencode-local.js +15 -2
  268. package/dist/react/use-opencode-sessions/commands.d.ts +11 -1
  269. package/dist/react/use-opencode-sessions/commands.js +21 -1
  270. package/dist/react/use-opencode-sessions/permissions.js +28 -1
  271. package/dist/react/use-project-sessions.d.ts +1 -1
  272. package/dist/react/use-project-sessions.js +6 -5
  273. package/dist/react/use-prompt-attachments.js +1 -0
  274. package/dist/react/use-review-summary.d.ts +13 -0
  275. package/dist/react/use-review-summary.js +32 -0
  276. package/dist/react/use-runtime-reconnect.js +1 -1
  277. package/dist/react/use-session-list-state.d.ts +6 -0
  278. package/dist/react/use-session-list-state.js +33 -0
  279. package/dist/react/use-session-log.d.ts +16 -0
  280. package/dist/react/use-session-log.js +143 -0
  281. package/dist/react/use-session-messages.d.ts +2 -1
  282. package/dist/react/use-session-messages.js +15 -14
  283. package/dist/react/use-session-stream.js +12 -1
  284. package/dist/react/use-session-sync.d.ts +2 -2
  285. package/dist/react/use-session-sync.js +10 -8
  286. package/dist/react/use-session-transcript-history.js +2 -12
  287. package/dist/react/use-session-working.d.ts +2 -0
  288. package/dist/react/use-session-working.js +10 -0
  289. package/dist/react/use-session.d.ts +6 -0
  290. package/dist/react/use-session.js +88 -6
  291. package/package.json +62 -8
@@ -1,24 +1,24 @@
1
- "use strict";var Beeuni=(()=>{var ro=Object.defineProperty;var mP=Object.getOwnPropertyDescriptor;var fP=Object.getOwnPropertyNames;var yP=Object.prototype.hasOwnProperty;var hP=(e,t)=>{for(var n in t)ro(e,n,{get:t[n],enumerable:!0})},bP=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of fP(t))!yP.call(e,s)&&s!==n&&ro(e,s,{get:()=>t[s],enumerable:!(r=mP(t,s))||r.enumerable});return e};var _P=e=>bP(ro({},"__esModule",{value:!0}),e);var t$={};hP(t$,{ABORT_REASONS:()=>Kb,ABORT_REASONS_NOT_YET_EMITTED:()=>OM,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>fo,ACTIVE_INSTANCE_COOKIE:()=>sr,ANALYTICS_UNAVAILABLE_CODE:()=>mo,ATTACHMENT_PART_REF_PREFIX:()=>d_,ApiError:()=>b,AuthError:()=>Q,BEEUNI_TRANSCRIPT_SCHEMA:()=>LA,BeeuniMemberError:()=>Je,BillingError:()=>$e,CONNECTION_FAULT_GRACE_MS:()=>P_,CONNECTOR_POLL_FIRST_DELAY_MS:()=>a_,CONNECTOR_POLL_INTERVAL_MS:()=>c_,CONNECTOR_POLL_WINDOW_MS:()=>u_,CONTEXT_TOOLS:()=>Jh,COST_MARKUP:()=>rm,ConnectorApprovalPendingError:()=>Ur,ConnectorCallError:()=>pn,ConnectorPageLimitError:()=>Fr,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>Xh,DEFAULT_NOTIFICATION_PREFERENCES:()=>oA,DEFAULT_TRANSCRIPT_OPTIONS:()=>Ig,DESTRUCTIVE_PHASES:()=>t_,FEATURE_DISABLED_CODE:()=>br,FEATURE_FLAG_KEYS:()=>QP,FEATURE_NOT_SUPPORTED_CODE:()=>lo,FILE_VERBS:()=>Qe,FileExistsError:()=>$t,HeadlessAuthError:()=>Ct,HostBoundaryError:()=>ar,IMPERSONATION_HEADER:()=>$m,INBOX_NOTIFICATION_KINDS:()=>sA,INBOX_OBSERVATION_MAX_MS:()=>zs,INITIAL_SETTLED_CONNECTION:()=>$D,INSTANCE_SCOPED_ROUTES:()=>Hb,MAX_PROMPT_ATTACHMENTS_BYTES:()=>WS,MAX_PROMPT_ATTACHMENT_BYTES:()=>ic,MAX_PROMPT_ATTACHMENT_FILES:()=>Zm,MEMORY_VERBS:()=>KE,MODEL_NOT_SERVABLE_CODE:()=>po,NO_GROUP_ACTIVITY_TOOLS:()=>Df,OPTIMISTIC_ABORT_MAX_MS:()=>Ys,OPTIMISTIC_COMPACTION_MAX_MS:()=>YD,OPTIMISTIC_RECEIPT_MAX_MS:()=>Hs,PERSISTED_QUERY_CACHE_VERSION:()=>vW,PLUMBING_TOOLS:()=>mb,PREVIEW_PROBE_TIMEOUT_MS:()=>RD,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>bx,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>hx,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>cf,PROVISION_IN_FLIGHT_CODE:()=>go,PublicSessionShareError:()=>Yr,RUNTIME_NOT_READY_MARKERS:()=>KM,RUNTIME_PERMISSION_CAPABILITIES:()=>qA,RUNTIME_PERMISSION_REPLIES:()=>NA,RequestTooLargeError:()=>tt,RuntimeNotReadyError:()=>Dt,SANDBOX_FS_ROOTS:()=>ks,SANDBOX_PORTS:()=>Te,SERVER_COMPACTION_REVALIDATE_MS:()=>v_,SERVER_OBSERVATION_MAX_MS:()=>Vs,SESSION_LIST_STATUS:()=>uj,SESSION_NOTICE:()=>dj,STANDALONE_TOOLS:()=>jf,STREAM_OBSERVATION_MAX_MS:()=>Yt,SandboxNotReadyError:()=>or,SessionNotReadyError:()=>ut,SessionStartError:()=>Wr,TURN_END_LEDGER_LAG_MS:()=>qD,TURN_ERROR_CODES:()=>py,WAKE_ESCALATION_COOLDOWN_MS:()=>tj,WAKE_MAX_RESTARTS:()=>ej,WAKE_NO_PROGRESS_MS:()=>ZD,WIRE_ID_BACKDATE_MS:()=>bs,WIRE_ID_CLOCK_TOLERANCE:()=>We,WIRE_ID_TIME_MASK:()=>Ee,WIRE_ID_TIME_SCALE:()=>Et,WIRE_MESSAGE_ID:()=>oy,__getConfigResolver:()=>xP,__setConfigResolver:()=>SP,abortErrorReason:()=>DM,acceptAccountInvite:()=>Go,acceptInvite:()=>dO,actReviewItem:()=>rp,activateConnection:()=>fa,addComputerToProject:()=>ba,addGroupMembers:()=>El,addMarketplaceSource:()=>Bp,advanceWakeEscalation:()=>sj,allDescendantIds:()=>lb,appendPreviewToken:()=>mm,approveProjectAccessRequest:()=>Si,approveTask:()=>XA,archiveProject:()=>ln,assignTicket:()=>ik,attachGroupToProject:()=>Ei,authMfa:()=>fs,authUser:()=>ds,authenticatedFetch:()=>E,authenticatedRequest:()=>gn,authorizePreviewUrl:()=>kD,backendApi:()=>c,beeuniAppViewerToken:()=>$_,beeuniBinding:()=>U_,beeuniPty:()=>by,beeuniToken:()=>_m,bindSlackIdentity:()=>Vx,bindTeamsIdentity:()=>zx,brokerProjectSecretRequest:()=>Gi,browserKeyValueStorage:()=>bD,buildInstancePath:()=>zb,buildPresentationTemplateImageUrl:()=>ED,buildPresentationTemplatePdfUrl:()=>TD,buildPreviewAuthEndpoint:()=>gm,buildPublicTemplateUrl:()=>rD,buildRuntimePresentationConversionUrl:()=>__,buildSandboxTemplate:()=>Xa,buildScrapeFailureResults:()=>hb,buildStaticFileHealthPreviewUrl:()=>nC,buildStaticFileLocalUrl:()=>tC,buildStaticFilePreviewUrl:()=>eC,buildStaticFileServicePath:()=>Qy,buildTunnelEventStreamUrl:()=>vj,buildWebProxyUrl:()=>aC,bulkActReviewItems:()=>sp,bulkDeletePolicies:()=>yw,bulkImportPolicies:()=>hw,burstSummary:()=>lT,burstSummaryLabel:()=>pT,callConnector:()=>ot,cancelAccountDeletion:()=>nv,cancelAccountInvite:()=>Lo,cancelSandbox:()=>iO,cancelSandboxUpdate:()=>kO,cancelScheduledChange:()=>Uu,cancelSubscription:()=>Du,checkAccessEmail:()=>LO,childMapByParent:()=>JI,claimComputer:()=>EO,claimNext:()=>xh,claimPerSeatBilling:()=>qx,claimWarmProjectSession:()=>Lc,classifyPart:()=>Gg,classifyPreviewProbeStatus:()=>b_,classifyPtyClose:()=>fy,classifyTurn:()=>sb,cleanErrorMessage:()=>oT,cleanResultSnippet:()=>fT,cleanWorkerOutput:()=>LE,clearBeeuniAppViewerCache:()=>j_,clearImpersonationSession:()=>_o,clearModelDefault:()=>_u,clearSessionFresh:()=>sx,closeChangeRequest:()=>Pc,closeMilestone:()=>Dk,collectTurnParts:()=>VI,commentTicket:()=>ck,commitSessionChanges:()=>wc,compactionExpiryAtMs:()=>JD,compactionTurnInfo:()=>dT,compareMessagesForDisplay:()=>qI,completeInFlight:()=>wh,completeSlackInstall:()=>Yu,completeTeamsInstall:()=>Qu,composerSelectableAgents:()=>xm,computeStatusFromPart:()=>nm,configureAutoTopup:()=>Nu,configureBeeuni:()=>mr,confirmCheckoutSession:()=>Mu,connectEmail:()=>sl,connectSlack:()=>Vu,connectionFromHealth:()=>jD,connectionIsFaulted:()=>DD,connectionSharedWithEveryone:()=>PS,connectorConnect:()=>Qm,connectorFinalize:()=>Jm,connectorHeadline:()=>uD,contextLabelForTool:()=>vT,contextToolSummary:()=>KC,contextToolTrigger:()=>HC,convertPresentationToGoogleSlides:()=>fv,convertRuntimePresentation:()=>MD,copyFile:()=>qn,costExportUrl:()=>Gu,countLiveInboxPrompts:()=>WD,countReviewItemsBySegment:()=>hv,createAccount:()=>Co,createAccountAuditWebhook:()=>Ip,createAccountSecretResource:()=>Xi,createAccountToken:()=>hp,createApp:()=>Gp,createAppAccessSession:()=>Jp,createAppDeployment:()=>Zp,createAppToken:()=>Hp,createAppVolume:()=>yd,createAppVolumeSnapshot:()=>Pd,createArtifactKind:()=>HT,createAssignment:()=>Jl,createAuditWebhook:()=>Vw,createBackup:()=>fO,createBeeuni:()=>bh,createBeeuniPty:()=>pg,createBeeuniSession:()=>hs,createCheckoutSession:()=>Eu,createConnector:()=>Ma,createConnectorLinkInfoCache:()=>iD,createFile:()=>Nn,createGatewayKey:()=>xl,createGroup:()=>Rl,createHttpSessionSyncController:()=>E_,createInstance:()=>CO,createMarketplaceInstallSession:()=>jv,createMilestone:()=>Mk,createModelVisibility:()=>cP,createOAuthClient:()=>Hl,createPerSeatCheckout:()=>Nx,createPersistedQueryCache:()=>hD,createPolicy:()=>gw,createPortalSession:()=>Ou,createProject:()=>Zo,createProjectAgent:()=>bk,createProjectCliToken:()=>xp,createProjectRepo:()=>ei,createProjectResourceGrant:()=>ji,createProjectSession:()=>at,createProjectSkill:()=>ii,createProjectTrigger:()=>cu,createPromptAttachmentController:()=>Cg,createRole:()=>Fl,createSSEStream:()=>Aj,createSandbox:()=>ZM,createSandboxShare:()=>up,createSandboxTemplate:()=>Ya,createSavedCopyStore:()=>gx,createScimToken:()=>Sw,createServiceAccountApi:()=>Gw,createSessionPrompt:()=>_n,createSessionPublicShare:()=>$c,createSessionQueue:()=>Ph,createSessionReminder:()=>dp,createSsoGroupMapping:()=>Dw,createTask:()=>YA,createTicket:()=>rk,createTunnelEventStream:()=>kj,currentSavedCopyStore:()=>Cc,declineAccountInvite:()=>Wo,declineInvite:()=>gO,deleteAccountImmediately:()=>rv,deleteAccountSecretResource:()=>ta,deleteApp:()=>Kp,deleteAppDeployment:()=>od,deleteAuditWebhook:()=>Yw,deleteBackup:()=>hO,deleteBeeuniProject:()=>Rk,deleteConnector:()=>Da,deleteConnectorCredential:()=>Ba,deleteCredential:()=>Nk,deleteDriveFile:()=>Zv,deleteEnv:()=>cg,deleteFile:()=>gt,deleteGatewayBudget:()=>Pl,deleteGitHubInstallation:()=>hi,deleteGroup:()=>Il,deleteInstance:()=>IO,deleteMilestone:()=>$k,deleteOAuthClient:()=>Yl,deletePersonalProjectSecret:()=>Yi,deletePolicy:()=>fw,deleteProjectAgent:()=>Pk,deleteProjectProviderOAuth:()=>Ki,deleteProjectResourceGrant:()=>$i,deleteProjectSecret:()=>Vi,deleteProjectSession:()=>Jc,deleteProjectTrigger:()=>lu,deletePromptAttachment:()=>vt,deleteRole:()=>Nl,deleteSandboxTemplate:()=>Ja,deleteServiceAccountApi:()=>Kw,deleteSessionPrompt:()=>Kc,deleteSessionReminder:()=>Jr,deleteSessionReminders:()=>mp,deleteSsoGroupMapping:()=>jw,deleteSsoProvider:()=>Mw,deleteTask:()=>ZA,deleteTicket:()=>uk,deleteUserProviderConnection:()=>jd,describeAccountInvite:()=>qo,describeConnectorTool:()=>Mr,destroyAppMachine:()=>dd,destroyAppVolume:()=>bd,detachGroupFromProject:()=>Oi,detectLocalhostUrls:()=>Hy,directSubsessions:()=>mj,disableServiceAccountApi:()=>Ww,disconnectEmail:()=>ol,disconnectGitHubApp:()=>mD,disconnectSlack:()=>Xu,discoverConnectionOAuth2:()=>vS,discoverConnectionOAuth2Resource:()=>AS,discoverConnectorAuth:()=>Oa,discoverLocalSandbox:()=>rO,dismissDriveConflict:()=>Hv,downloadAccountAudit:()=>tD,downloadDriveFile:()=>zv,dropClientForUrl:()=>Jk,dropPublicClientForUrl:()=>eR,editQueued:()=>Rh,editSessionPrompt:()=>Hc,enqueue:()=>Sh,ensurePmSession:()=>yk,ensurePreviewSessionCookie:()=>h_,ensureProjectConnectorConnection:()=>SS,ensureSandbox:()=>e_,ensureWarmProjectSession:()=>Fc,env:()=>gy,exchangeCode:()=>us,execInApp:()=>md,exportAccountAudit:()=>Rp,extractGatewayErrorDetails:()=>ge,extractInstanceRoute:()=>Vt,extractSkillBaseDir:()=>Lb,extractSkillContent:()=>ZE,extractSkillFiles:()=>Fb,extractWorkerPreview:()=>NE,failInFlight:()=>vh,fallbackBusyRowAfterTurnId:()=>hE,familyForTool:()=>qs,featureDisabledKey:()=>ao,featureFlags:()=>Qd,fetchAccountStateWithToken:()=>Fx,fetchAccountsWithToken:()=>YP,fetchAttachmentPart:()=>_D,fetchBeeuniAppViewer:()=>bm,fetchCostExportCsv:()=>Hx,fetchProjectArchive:()=>sc,fetchProjectFileRaw:()=>GS,fetchProjectsForAccountWithToken:()=>oS,fetchSessionAttachment:()=>zd,fileDownloadRequest:()=>Iy,filePhase:()=>WE,fileVerb:()=>GE,files:()=>$y,finalizeAppArtifact:()=>es,finalizeConnectorSetupLink:()=>HO,findActiveTranscriptShare:()=>Px,findFiles:()=>Ln,findLastTextPart:()=>zI,findSessionAttachments:()=>SA,findText:()=>Bn,fireProjectTrigger:()=>du,fixSandboxWithAgent:()=>za,flattenModels:()=>oP,flattenThought:()=>eE,forkAppVolume:()=>xd,formatBillingErrorForUI:()=>uo,formatCost:()=>DE,formatDuration:()=>EE,formatJsonFailureOutput:()=>iT,formatMessageDay:()=>iE,formatMessageExact:()=>aE,formatOpenCodeRuntimeError:()=>YM,formatRawOutput:()=>mT,formatRuntimeError:()=>Zb,formatTokens:()=>jE,formatTranscript:()=>Ih,freshSendHint:()=>SE,generateSessionId:()=>_h,getAccount:()=>Io,getAccountBranding:()=>Eo,getAccountDeletionStatus:()=>ev,getAccountState:()=>vu,getAccountStateMinimal:()=>Au,getActiveInstanceIdFromCookie:()=>Qb,getAdminBootModes:()=>dv,getAdminProviderAnalytics:()=>cv,getAdminProviderDistribution:()=>ov,getAdminProviderFallback:()=>lv,getAdminRole:()=>sv,getAgentCardLabel:()=>nb,getAgentConfig:()=>Ox,getAgentPersona:()=>Sk,getAllVersions:()=>wO,getAnsweredQuestionParts:()=>QI,getApp:()=>Xr,getAppAccess:()=>zp,getAppAuthEnv:()=>Vp,getAppDeployment:()=>td,getAppDeploymentLogs:()=>nd,getApprovalLink:()=>Dv,getAuthToken:()=>xt,getAuthTokenWithRetry:()=>fS,getAutoTopupSettings:()=>Bu,getAutoTopupSetupStatus:()=>Bx,getBeeuniProject:()=>vk,getBeeuniProjectBySession:()=>Ak,getBeeuniPtyWebSocketUrl:()=>mg,getBillingCreditBreakdown:()=>Cu,getBillingTierConfigurations:()=>Tu,getBillingTransactionsSummary:()=>Ru,getBillingUsageHistory:()=>Iu,getChangeRequest:()=>fc,getChangeRequestDiff:()=>yc,getChangeRequestMergePreview:()=>hc,getChildSessionError:()=>iI,getChildSessionId:()=>Lg,getChildSessionToolParts:()=>aI,getClient:()=>He,getClientForUrl:()=>be,getConnectStatus:()=>Fa,getConnectionOAuth2Application:()=>wS,getConnectionOAuth2Status:()=>TS,getConnectionPolicies:()=>ES,getConnectorCatalog:()=>wt,getConnectorConfig:()=>Ia,getConnectorPolicies:()=>Ra,getConnectorSetupLink:()=>WO,getCostSummary:()=>Kx,getCurrentInstanceIdFromPathname:()=>Yb,getCurrentInstanceIdFromWindow:()=>UM,getCurrentProject:()=>_g,getDefaultAccountState:()=>wu,getDiagnostics:()=>pI,getDirectory:()=>tb,getDiscoverConnector:()=>$r,getDiscoverIntegration:()=>US,getDriveFileUrl:()=>wd,getEmailInstallation:()=>nl,getEmailMode:()=>rl,getEnterpriseDemo:()=>Jw,getFileStatus:()=>Fn,getFileWithDir:()=>Ug,getFilename:()=>eb,getFolderAccess:()=>Nv,getFullChangelog:()=>n_,getGatewayBreakdown:()=>fl,getGatewayBudgets:()=>bl,getGatewayErrors:()=>hl,getGatewayKeys:()=>Sl,getGatewayLog:()=>dl,getGatewayOverview:()=>gl,getGatewayRoutingPolicy:()=>al,getGatewaySeries:()=>ml,getGatewaySessions:()=>yl,getGitHubAppStatus:()=>lD,getGitHubInstallation:()=>ui,getGoogleAuthUrl:()=>mv,getGroup:()=>kl,getHiddenToolParts:()=>tI,getImpersonationSession:()=>Lm,getInvite:()=>pO,getJustavpsServerTypes:()=>RO,getLatestSandboxVersion:()=>xO,getMaintenanceConfig:()=>JO,getManagedGitBackend:()=>bi,getManagedGitStatus:()=>tS,getMarketplaceCatalogItem:()=>Up,getMarketplaceCatalogItemFile:()=>Fp,getMfaRequired:()=>ww,getMilestone:()=>Tk,getModelDefaults:()=>hu,getNotificationPreferences:()=>Cd,getOAuthClient:()=>Kl,getOAuthConsentRequest:()=>qO,getOpenCodeConfigInvalidError:()=>qM,getPartText:()=>XC,getPatPolicy:()=>Bw,getPermissionForTool:()=>dI,getProject:()=>sn,getProjectActivity:()=>xk,getProjectCommit:()=>lc,getProjectCommitDiff:()=>pc,getProjectDetail:()=>on,getProjectDrive:()=>Bv,getProjectFileHistory:()=>dc,getProjectGitToken:()=>Xo,getProjectLlmCatalog:()=>an,getProjectLlmCatalogProviders:()=>XP,getProjectModelAccess:()=>vn,getProjectModelPicker:()=>cn,getProjectSandboxHealth:()=>dn,getProjectSandboxProviderTransition:()=>nS,getProjectSession:()=>bn,getProjectSessionConfigState:()=>Xc,getProjectSessionScope:()=>tu,getProjectStarterSuggestions:()=>iA,getProrationPreview:()=>Fu,getProviders:()=>JM,getProxyBaseUrl:()=>rC,getPublicClientForUrl:()=>Zk,getPublicMarketplaceItem:()=>UO,getPublicMarketplaceItemFile:()=>FO,getPublicSessionShare:()=>Iv,getPublicSessionShareMessages:()=>Tv,getPublicShareByToken:()=>YO,getPublicTemplate:()=>sD,getQuestionForTool:()=>gI,getReferralCode:()=>nw,getReferralStats:()=>ow,getRetryInfo:()=>$E,getRetryMessage:()=>UE,getReviewItem:()=>tp,getRolePermissions:()=>$l,getRoleUsage:()=>Ul,getRuntimeConfigInvalidError:()=>Ks,getSSHConnection:()=>_O,getSandbox:()=>XM,getSandboxById:()=>eO,getSandboxPortUrl:()=>QM,getSandboxProvisionStatus:()=>MO,getSandboxProvisionStreamUrl:()=>OO,getSandboxUpdateStatus:()=>SO,getSandboxUrl:()=>um,getSandboxUrlForExternalId:()=>Fe,getSecretSetupLink:()=>VO,getServerHealth:()=>Rs,getServiceLogs:()=>Hk,getSessionAudit:()=>Bc,getSessionCost:()=>OE,getSessionCostRecord:()=>wn,getSessionDrives:()=>Ef,getSessionHealth:()=>wg,getSessionMessageAuthors:()=>ou,getSessionModelUsage:()=>iu,getSessionOpenBundle:()=>Sx,getSessionOversight:()=>kw,getSessionParticipants:()=>Ec,getSessionPolicy:()=>$w,getSessionPreviewCandidates:()=>Dc,getSessionProviderSecretPool:()=>oa,getSessionTranscript:()=>Nc,getSessionTranscriptSync:()=>qc,getSessionTurn:()=>Gc,getSessionWatch:()=>Mc,getShellModePart:()=>wE,getSlackChannelFile:()=>Zu,getSlackInstallation:()=>Hu,getSlackManifest:()=>Ju,getSlackMode:()=>zu,getSsoProvider:()=>Cw,getStaticFileHealthPath:()=>Jy,getSupabaseAccessToken:()=>Cr,getSupabaseAccessTokenWithRetry:()=>Ym,getTask:()=>HA,getTaskStatus:()=>zA,getTemplate:()=>$v,getTicket:()=>tk,getToolInfo:()=>cI,getToolPrimaryArg:()=>Os,getTranscriptFilename:()=>Th,getTurnCost:()=>ME,getTurnError:()=>RE,getTurnErrorDetails:()=>IE,getTurnErrorRawText:()=>CE,getTurnStatus:()=>TE,getUsageRollup:()=>qu,getUserRolesWithToken:()=>ZO,getVersionDiff:()=>gc,getWebPushPublicKey:()=>Td,getWorkingState:()=>AE,grantAccountSecretResource:()=>na,grantSandboxProjectAccess:()=>uO,grantSecretToAgent:()=>jx,groupMessagesIntoTurns:()=>WI,groupShowSegments:()=>lE,groupSteps:()=>em,hasDiffs:()=>FE,hasLocalhostUrls:()=>JR,hasPreviewTarget:()=>Yy,hasRetryingAssistantTurn:()=>ZI,heartbeatGapEvent:()=>Py,holdSessionPrompts:()=>Yc,humanizeReviewActionPath:()=>ap,humanizeSearchQuery:()=>Vn,humanizeToolName:()=>Ng,impersonationHeaders:()=>Po,importSsoProviderFromMetadata:()=>Tw,inboxObservationSupersedes:()=>GD,initialWakeEscalationState:()=>ym,inputPath:()=>De,installTemplate:()=>Uv,interruptSessionPrompt:()=>Vc,invalidateTokenCache:()=>Ir,inviteAccountMember:()=>Uo,inviteProjectMember:()=>ki,inviteRepoCollaborator:()=>Qo,isAbortError:()=>rr,isAdminBypassEnabled:()=>Gm,isAgentPart:()=>VC,isAppRouteUrl:()=>Ky,isAttachment:()=>ZC,isAttachmentPartRef:()=>g_,isAuthFailure:()=>_t,isBillingError:()=>co,isCompactionPart:()=>zC,isConfigured:()=>fr,isContextTool:()=>WC,isDestructivePhase:()=>PO,isEmptyConversation:()=>O_,isEmptyShowPart:()=>ts,isErrorOutput:()=>eT,isExternalUrl:()=>lC,isFeatureDisabledError:()=>io,isFilePart:()=>Fg,isImpersonationSessionLive:()=>Um,isInstanceDetailPath:()=>jM,isInstanceScopedAppPath:()=>Vb,isInternalLocalhostUrl:()=>iC,isInvisibleActivityPart:()=>qd,isInviteSent:()=>cS,isLastUserMessage:()=>vE,isLegacyMigratedSession:()=>A_,isManagedGithubProject:()=>JP,isNoGroupActivityTool:()=>Nd,isOfferedModel:()=>to,isOpenCodeConfigInvalidError:()=>GM,isPaintableSavedCopy:()=>kc,isPatchPart:()=>QC,isPersistableQueryKey:()=>yD,isPreviewUrl:()=>oC,isProxiableLocalhostUrl:()=>Xy,isQuestionTool:()=>lA,isReasoningPart:()=>Pe,isRetryableTurnError:()=>pb,isRuntimeConfigInvalidError:()=>Jb,isRuntimeNotReadyResponse:()=>Xb,isRuntimeReady:()=>xg,isRuntimeStartingError:()=>zM,isSandboxNotReadyError:()=>zt,isSelectableAgent:()=>rs,isServerReachable:()=>Pg,isSessionAttachmentRef:()=>fA,isSessionFresh:()=>Ac,isSessionStartError:()=>Cx,isShellActivityTool:()=>uA,isShellMode:()=>Eb,isShortOutput:()=>BE,isShowContentUnavailable:()=>aA,isShowPayloadEmpty:()=>Rn,isSnapshotPart:()=>YC,isStandaloneActivityTool:()=>Gd,isStepPart:()=>JC,isSubdomainPreviewUrl:()=>cr,isTextPart:()=>_e,isToolPart:()=>X,isToolPartHidden:()=>nI,isTurnErrorCode:()=>BA,isUnderSandboxRoot:()=>hg,isWebProxyUrl:()=>uC,isWireIdAheadOf:()=>ay,leaveAccount:()=>Vo,linkGitHubInstallation:()=>fi,linkRepository:()=>ai,listAccountAudit:()=>Ap,listAccountAuditWebhooks:()=>Cp,listAccountInvites:()=>Fo,listAccountMembers:()=>$o,listAccountResourceGrants:()=>pw,listAccountSecretResources:()=>Ji,listAccountSessions:()=>Fw,listAccountTokens:()=>yp,listAccounts:()=>Ro,listActions:()=>bw,listAdminSandboxes:()=>iv,listAgentIdentities:()=>Dl,listAllConnections:()=>la,listAppAgents:()=>Yp,listAppDeployments:()=>ed,listAppMachines:()=>ad,listAppVolumeSnapshots:()=>_d,listAppVolumes:()=>fd,listApps:()=>qp,listAssignments:()=>Ql,listAuditEvents:()=>Qw,listAuditWebhooks:()=>Hw,listBackups:()=>mO,listBeeuniProjectSessions:()=>kk,listBeeuniProjects:()=>wk,listBeeuniPty:()=>lg,listBillingTransactions:()=>ku,listChangeRequests:()=>mc,listChannelBindings:()=>Zx,listColumns:()=>lk,listConnectSections:()=>jS,listConnectToolkits:()=>DS,listConnections:()=>ua,listConnectorAccounts:()=>Or,listConnectorTools:()=>Er,listConnectors:()=>xa,listCostByProject:()=>Wx,listCredentialEvents:()=>Fk,listCredentials:()=>Uk,listDiscoverConnectors:()=>jr,listDiscoverIntegrations:()=>$S,listDiscoverSections:()=>Ua,listDriveConflicts:()=>Kv,listDriveFiles:()=>Vv,listDriveFolder:()=>Tf,listDriveVersions:()=>eA,listEnv:()=>ig,listFeaturedMarketplaces:()=>$p,listFields:()=>dk,listFiles:()=>Lt,listFolderPrincipals:()=>Wv,listGatewayLogs:()=>pl,listGitHubInstallations:()=>li,listGitHubRepositories:()=>di,listGitHubRepositoryBranches:()=>gi,listGroupMembers:()=>Tl,listGroupProjectGrants:()=>cw,listGroups:()=>Al,listLinkableGitHubInstallations:()=>pi,listManagedGitRepositories:()=>_i,listMarketplaceCatalogItems:()=>Dp,listMarketplaceSources:()=>Lp,listMarketplaces:()=>jp,listMemberGroups:()=>uw,listMemberProjectAccess:()=>lw,listMilestoneEvents:()=>Ek,listMilestones:()=>Ik,listMyAccountInvites:()=>No,listNotifications:()=>kd,listOAuthClients:()=>Wl,listOAuthGrants:()=>_p,listPendingApprovals:()=>Ui,listPendingProjectInvites:()=>Ri,listPermissions:()=>Zl,listPipedreamApps:()=>ja,listPipedreamSections:()=>$a,listPolicies:()=>dw,listProjectAccess:()=>wi,listProjectAccessRequests:()=>Pi,listProjectAgentIdentities:()=>jl,listProjectAgents:()=>hk,listProjectAudit:()=>kp,listProjectBranches:()=>cc,listProjectCliTokens:()=>Sp,listProjectCommits:()=>uc,listProjectDirectory:()=>tc,listProjectFiles:()=>ec,listProjectGroupGrants:()=>Ti,listProjectPersonalProviders:()=>Fd,listProjectPolicies:()=>Ga,listProjectProviderOAuth:()=>Wi,listProjectReminders:()=>fp,listProjectResourceGrants:()=>Di,listProjectSandboxTemplates:()=>Ka,listProjectSandboxes:()=>Za,listProjectSecrets:()=>Bi,listProjectSessions:()=>it,listProjectSessionsPage:()=>Ic,listProjectSnapshots:()=>Ha,listProjectTriggerEventApps:()=>mu,listProjectTriggerEventTypes:()=>gu,listProjectTriggers:()=>au,listProjects:()=>st,listProjectsForAccount:()=>Yo,listPublicMarketplaceItems:()=>jO,listPublicMarketplaces:()=>$O,listReferrals:()=>iw,listReviewItems:()=>ep,listRoles:()=>Ol,listSandboxProjectMembers:()=>cO,listSandboxShares:()=>cp,listSandboxes:()=>nO,listScimTokens:()=>Pw,listServiceAccountsApi:()=>qw,listServiceTemplates:()=>Kk,listServices:()=>Wk,listSessionConnectRequests:()=>OS,listSessionCosts:()=>Ku,listSessionDrives:()=>rA,listSessionPrompts:()=>Wc,listSessionProviderSecretPools:()=>ia,listSessionPublicShares:()=>jc,listSessionReminders:()=>pp,listSessionsNeedingInput:()=>Fi,listSignedInDevices:()=>Mv,listSsoGroupMappings:()=>Ow,listTaskEvents:()=>VA,listTasks:()=>KA,listTemplates:()=>mk,listTicketEvents:()=>nk,listTickets:()=>ek,listUserProviderConnections:()=>Od,loadHttpSessionHistory:()=>T_,loadPreviewUrlTemplate:()=>Ge,looksLikeError:()=>Hg,looksLikeHtml:()=>_T,looksLikeJsonPayload:()=>gT,makeDriveFolder:()=>Jv,mapApiReviewItem:()=>Cv,markInstanceError:()=>TO,markNotificationsRead:()=>Rd,markSessionFresh:()=>hn,maxWireIdClock:()=>ng,memoryRelPath:()=>HE,mergeBurstSteps:()=>JT,mergeChangeRequest:()=>_c,messageCreatedAt:()=>tE,messageTime:()=>Cb,migrateAdminSandboxProvider:()=>uv,mintWireMessageId:()=>_s,mintWireMessageIdAbove:()=>rg,mkdir:()=>Gt,modelInDefaultView:()=>uP,modelRefToKey:()=>H_,moveDriveFile:()=>Xv,narrateFailedStep:()=>Zg,narrateStep:()=>Xg,narrationToolName:()=>tr,narrowChatEvent:()=>Sy,newestWireIdClock:()=>cy,nextConnectorPollDelay:()=>cD,normalizeActivityToolName:()=>le,normalizeAppPathname:()=>BM,normalizeExternalInput:()=>pC,normalizeName:()=>V,normalizeToolName:()=>Bg,notifyHostSignal:()=>R_,openChangeRequest:()=>bc,openEventStream:()=>ws,openStressTestStream:()=>nD,paginateConnector:()=>qa,parseBillingError:()=>tn,parseEmbeddedFailure:()=>yT,parseFlagOverride:()=>wA,parseJsonFailure:()=>gb,parseLocalhostUrl:()=>Hn,parseMemoryView:()=>VE,parseOpenCodeErrorPayload:()=>NM,parsePresentationOutput:()=>QE,parseProxyHop:()=>Sg,parseQuestionAnswersFromOutput:()=>JE,parseReadOutput:()=>XE,parseRuntimeErrorPayload:()=>cm,parseScrapeInputUrls:()=>yb,parseScrapeOutput:()=>bb,parseSubdomainUrl:()=>Ag,parseTaskRows:()=>qE,parseWebProxyUrl:()=>cC,parseWebSearchOutput:()=>Qg,partOutcome:()=>Vg,patchBeeuniProject:()=>Ck,patchVerb:()=>YE,pickerProviderList:()=>sP,pipedreamConnect:()=>Ea,pipedreamConnectConnection:()=>Pa,pipedreamFinalize:()=>Na,pipedreamFinalizeConnection:()=>Sa,platformConfig:()=>k,pollConnectionOAuth2DeviceAuthorization:()=>IS,pollProjectProviderOAuth:()=>Rr,pollUserProviderOAuth:()=>Ud,previewGatewayRoute:()=>ll,previewMfaRequired:()=>vw,previewSlackIdentity:()=>Yx,previewTeamsIdentity:()=>Qx,probeEffectivePermission:()=>ql,probeEffectivePermissions:()=>Gl,probePreviewPort:()=>CD,projectArchiveRequest:()=>oc,projectCompacting:()=>QD,projectConfigAgentsToOpenCodeAgents:()=>W_,projectConfigAgentsToRuntimeAgents:()=>Sm,projectSessionConnection:()=>OD,projectSessionForRuntimeId:()=>fj,projectSessionStartSeed:()=>Rx,projectWorking:()=>KD,provisionProject:()=>ti,provisionProjectStream:()=>eS,provisionProjectWithToken:()=>iS,proxyLocalhostUrl:()=>vg,proxyUrlToInternal:()=>sC,purchaseCredits:()=>Lu,putConnectionOAuth2Application:()=>xS,rawErrorText:()=>Mg,reactivateSandbox:()=>aO,reactivateSubscription:()=>ju,readBeeuniMember:()=>Zs,readBlob:()=>Nt,readDriveFile:()=>Yv,readFile:()=>Bt,readProjectFile:()=>rc,reasoningIsRunning:()=>wb,rebuildProjectSnapshot:()=>Va,reconcileConnection:()=>pa,reconcileMemberConnection:()=>da,reconcileServices:()=>zk,recordPlatformLogout:()=>NO,recoverLinkResults:()=>Ls,refreshReferralCode:()=>rw,refreshSession:()=>It,registerAppArtifact:()=>Zr,registerConnectionOAuth2Client:()=>kS,registerDeviceToken:()=>vd,registerService:()=>Yk,registerWebPushSubscription:()=>Ed,rejectProjectAccessRequest:()=>xi,relativizePath:()=>lI,reloadProjectSessionConfig:()=>Zc,reloadProjectSessionConfigStream:()=>eu,removeAccountAuditWebhook:()=>Ep,removeAccountBrandingAsset:()=>Do,removeAccountMember:()=>Ko,removeBeeuniPty:()=>gg,removeGroupMember:()=>Ml,removeMarketplaceSource:()=>Np,removeQueued:()=>kh,renameConnection:()=>ha,renameFile:()=>Wn,renameSandbox:()=>tO,reopenChangeRequest:()=>Sc,reopenMilestone:()=>jk,reorderQueued:()=>Ch,replaceColumns:()=>pk,replaceFields:()=>gk,replaceProjectRepository:()=>ci,replaceTemplates:()=>fk,requestAccountDeletion:()=>tv,requestChangesOnChangeRequest:()=>xc,requestProjectAccess:()=>aS,requestProjectConnector:()=>Op,requestProjectSecret:()=>Mp,requestTopUp:()=>Lx,requireBeeuniMember:()=>B_,resendAccountInvite:()=>Bo,resendPendingProjectInvite:()=>Ii,resetAccountBranding:()=>jo,resetClient:()=>Xk,resetGatewayRoutingPolicy:()=>ul,resetPassword:()=>ls,resetPublicClient:()=>tR,resetSandboxUpdateStatus:()=>AO,resolveApproval:()=>Li,resolveComposerAgent:()=>G_,resolveComposerModel:()=>dP,resolveConnectorStart:()=>aD,resolveModelDefault:()=>pP,resolvePublicShareUrl:()=>_x,resolveScrapeResults:()=>PT,resolveWorkingTurn:()=>xE,resolvedPlan:()=>Ux,restartAppMachine:()=>pd,restartProjectSession:()=>Pn,restartSandbox:()=>sO,restoreAppVolume:()=>Sd,restoreBackup:()=>yO,restoreDriveVersion:()=>tA,retryAccountSecretResource:()=>ea,retryFailed:()=>Ah,retrySessionPrompt:()=>zc,revealCredential:()=>Bk,reviewItemTarget:()=>yv,reviewSegmentForStatus:()=>kf,reviewVerdictForStatus:()=>bv,revokeAccountSecretResourceGrant:()=>ra,revokeAccountSession:()=>Lw,revokeAccountToken:()=>bp,revokeAssignment:()=>Xl,revokeConnection:()=>ma,revokeGatewayKey:()=>wl,revokeOAuthGrant:()=>Pp,revokePendingProjectInvite:()=>Ci,revokeProjectAccess:()=>Ai,revokeProjectCliToken:()=>wp,revokeSandboxProjectAccess:()=>lO,revokeSandboxShare:()=>lp,revokeScimToken:()=>xw,revokeSessionPublicShare:()=>Uc,rewriteLocalhostUrl:()=>Ye,rollbackApp:()=>id,rootRuntimeSession:()=>k_,rotateAccountSecretResource:()=>Zi,rotateOAuthClientSecret:()=>zl,runConnector:()=>Lr,runGatewayPlayground:()=>vl,runProjectProviderOAuthFlow:()=>dS,runtimeSessionsOf:()=>Qs,runtimeSupports:()=>By,sanitizePtyChunk:()=>hy,saveGitHubInstallation:()=>mi,saveUserProviderApiKey:()=>Dd,savedCopyEmptyRoot:()=>M_,scaleApp:()=>gd,scheduleDowngrade:()=>$u,searchConnectorTools:()=>ca,searchProjectFiles:()=>nc,segmentTurn:()=>cE,selectableProjectAgents:()=>AA,sendMagicLink:()=>is,sendReferralEmails:()=>aw,serverCompactionRevalidateAtMs:()=>XD,serviceAction:()=>Vk,sessionConnectionLabel:()=>pj,sessionListStatus:()=>lj,sessionModelPin:()=>su,sessionParentId:()=>yx,sessionPromptActions:()=>vx,sessionStartKey:()=>Tx,setAccountSecretResourceAccess:()=>sa,setActiveInstanceCookie:()=>FM,setAdminBootModes:()=>gv,setAdminBypass:()=>qm,setAdminProviderDistribution:()=>av,setAdminProviderFallback:()=>pv,setAgentScope:()=>Pu,setBootstrapAuthToken:()=>mS,setCachedAuthToken:()=>gS,setConnectionPolicies:()=>MS,setConnectorAuthorizationStrategy:()=>Aa,setConnectorCredential:()=>La,setConnectorCredentialMode:()=>va,setConnectorName:()=>Ta,setConnectorPolicies:()=>Ca,setConnectorSecretBinding:()=>FS,setConnectorSensitive:()=>ka,setDefaultConnection:()=>ya,setEnterpriseDemo:()=>Xw,setEnv:()=>ag,setGatewayBudget:()=>_l,setGatewayRoutingPolicy:()=>cl,setGitHubAppFromExisting:()=>dD,setGitHubAppPat:()=>gD,setImpersonationSession:()=>OP,setMaintenanceConfig:()=>XO,setMemberSuperAdmin:()=>_w,setMfaRequired:()=>Aw,setModelDefault:()=>bu,setPersonalProjectSecret:()=>zi,setProjectModelAccess:()=>An,setProjectModelEnablement:()=>Ex,setProjectOnboardingComplete:()=>oi,setProjectOnboardingProfile:()=>sS,setProjectPersonalProvider:()=>Ld,setProjectPolicies:()=>Wa,setProjectSecretStrategy:()=>qi,setProjectSessionModel:()=>ru,setProjectSessionScope:()=>nu,setProjectSessionSharing:()=>Tc,setProjectTriggersActivation:()=>pu,setSavedCopyStore:()=>mx,setSessionOversight:()=>Rw,setSessionProviderSecretPool:()=>aa,setSessionWatch:()=>Oc,settleSessionConnection:()=>UD,setupSSH:()=>bO,shareConnection:()=>_a,shareFolder:()=>qv,shellActivityGroupLabel:()=>pA,shellExitCode:()=>im,shouldAttachImpersonation:()=>Bm,shouldHideResponsePart:()=>kE,shouldShowToolPart:()=>Zh,shouldSuppressWorkingTurnBusy:()=>fE,showGroupItems:()=>gE,showTurnBusyIndicator:()=>tm,signInWithPassword:()=>os,signInWithProvider:()=>cs,signInWithSso:()=>ms,signOut:()=>ys,signOutDevice:()=>Ov,signUp:()=>ss,skillDocumentPath:()=>oM,skillInputDir:()=>nM,sortSessions:()=>XI,splitUserParts:()=>eI,startApp:()=>rd,startAppMachine:()=>ud,startConnectionOAuth2Authorization:()=>RS,startConnectionOAuth2DeviceAuthorization:()=>CS,startConnectorSetupLink:()=>KO,startGitHubAppManifest:()=>pD,startProjectProviderOAuth:()=>kr,startProjectSession:()=>Le,startProjectSessionOrThrow:()=>yu,startSessionWithToken:()=>QO,startTask:()=>JA,startUserProviderOAuth:()=>$d,stepLabel:()=>zg,stopApp:()=>sd,stopAppMachine:()=>ld,stopProjectSession:()=>Sn,stopSandbox:()=>oO,storeGitHubUserToken:()=>yi,stripAnsi:()=>fI,stripInstancePrefix:()=>$M,stripTrailingSlashes:()=>ee,submitAccessRequest:()=>BO,submitDemoRequest:()=>eD,submitOAuthConsent:()=>GO,submitReviewItem:()=>np,submitSecretSetupLink:()=>zO,subscribeToImpersonation:()=>DP,supabaseClient:()=>VP,syncConnectors:()=>wa,syncSubscription:()=>Gx,systemReload:()=>rR,toDaemonPath:()=>ze,toInstanceAwarePath:()=>LM,toInternalUrl:()=>Zy,toSandboxAbsolutePath:()=>Ft,toToolView:()=>RI,toWorkspaceRelative:()=>bg,toolInfo:()=>Ds,toolKind:()=>te,toolViewModel:()=>Gb,triggerSandboxUpdate:()=>vO,triggersRequest:()=>my,turnEndCause:()=>w_,turnEndNotice:()=>zD,turnHasSteps:()=>YI,turnIsConfirmedActive:()=>bE,turnRendersQueued:()=>_E,turnRetryLabel:()=>gj,unassignTicket:()=>ak,unregisterDeviceToken:()=>Ad,unregisterWebPushSubscription:()=>Md,unshareFolder:()=>Gv,unwrapError:()=>pe,updateAccountAuditWebhook:()=>Tp,updateAccountBranding:()=>Mo,updateAccountMemberRole:()=>Ho,updateAccountName:()=>To,updateAgentConfig:()=>Dx,updateApp:()=>Wp,updateAppAccess:()=>Qp,updateAppVolume:()=>hd,updateAuditWebhook:()=>zw,updateBeeuniPty:()=>dg,updateChangeRequest:()=>vc,updateChannelBinding:()=>ew,updateConnectionCredential:()=>ga,updateEmailPolicy:()=>il,updateExperimentalFeature:()=>ri,updateFeatureFlag:()=>ni,updateGroup:()=>Cl,updateMilestone:()=>Ok,updateNotificationPreferences:()=>Id,updateOAuthClient:()=>Vl,updatePassword:()=>ps,updatePatPolicy:()=>Nw,updatePolicy:()=>mw,updateProject:()=>un,updateProjectAccess:()=>vi,updateProjectAgent:()=>_k,updateProjectDefaultAgent:()=>xu,updateProjectGroupGrant:()=>Mi,updateProjectSandboxProvider:()=>si,updateProjectSession:()=>Qc,updateProjectTrigger:()=>uu,updateRole:()=>Ll,updateRolePermissions:()=>Bl,updateSandboxTemplate:()=>Qa,updateSessionPolicy:()=>Uw,updateSessionReminder:()=>Qr,updateSessionReminders:()=>gp,updateTask:()=>QA,updateTemplateWarmPool:()=>rS,updateTicket:()=>sk,updateTicketStatus:()=>ok,updateUserMetadata:()=>gs,uploadAccountBrandingAsset:()=>Oo,uploadAppArtifactArchive:()=>Xp,uploadConnectorAttachment:()=>Dr,uploadDriveFile:()=>Qv,uploadFile:()=>qt,uploadNativeFile:()=>Ey,uploadPromptAttachment:()=>yn,uploadSessionAttachment:()=>Vd,uploadSlackChannelFile:()=>el,uploadTimeoutMsForBytes:()=>jt,upsertCredential:()=>Lk,upsertProjectGitCredential:()=>Hi,upsertProjectSecret:()=>Ni,upsertSsoProvider:()=>Iw,validateProjectManifest:()=>Jo,validateReferralCode:()=>sw,validateToken:()=>zo,verifyBeeuniToken:()=>q_,verifyGatewayProvider:()=>tw,verifyOtp:()=>as,verifySsoDomain:()=>Ew,wakeEscalationAttemptSummary:()=>cj,wakeEscalationNote:()=>ij,wakeProgressFingerprint:()=>nj,wireIdClock:()=>pt,wireIdClockAt:()=>Mt,wireIdClockDelta:()=>dt,workingExpiryAtMs:()=>HD,workingTurnDrawsBusyRow:()=>PE,writeActivityGroupLabel:()=>dA,writeFile:()=>Gn,wsDomain:()=>Ns,wsFavicon:()=>bT,wsRootDomain:()=>hT});var PP={backendUrl:"",getToken:async()=>null},so=null,gr=null;function SP(e){gr=e}function xP(){return gr}function mr(e,t){t?.global!==!1&&(so=e)}function k(){return gr?.()??so??PP}function fr(){return so!==null||gr?.()!==void 0}function wP(e){return new Promise(t=>setTimeout(t,e))}async function yr(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(o&&n?.(),s>0&&await wP(s)),i=await e(),i)return i;return i}var oo=12e4;function vP(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Em(e,t,n=oo){let r=e instanceof Request?e.signal:t?.signal;if(vP(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function hr(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var b=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},Q=class extends b{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},$e=class extends b{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},tt=class extends b{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},AP="ENDPOINT_RETIRED";function F(e,t){let n=t?` ${t}`:"";return new b(`${e}() is retired: the Beeuni API no longer serves this endpoint.${n}`,{code:AP})}var br="feature_disabled";function Mm(e){if(!(e instanceof b)||e.status!==403||e.code!==br)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function io(e){let t=Mm(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function ao(e){let t=Mm(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function tn(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new $e(t,{message:r?.message||e.message||"Billing error",...r},void 0,{code:e.code,details:e.details,data:e.data,response:e.response,url:e.url,endpoint:e.endpoint})}function co(e){return e instanceof $e}function _t(e){if(e instanceof Q)return!0;let t=e?.status;return t===401||t===403}function uo(e){if(!(e instanceof $e))return null;let t=e.detail?.message?.toLowerCase()||"";return t.includes("credit")||t.includes("balance")||t.includes("insufficient")?{alertTitle:"You ran out of credits",alertSubtitle:"Upgrade your plan to get more credits and continue using the AI assistant."}:{alertTitle:"Billing check failed",alertSubtitle:e.detail?.message||"Please upgrade to continue."}}function me(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function fe(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(me())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function _r(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(me())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var Om="request_deadline",kP=/^Request exceeded the \d+s server processing deadline$/,Dm=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Om||kP.test(n),RP="git_mirror_unavailable",CP=/^git mirror is temporarily unavailable$/,IP=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===RP||CP.test(n);async function TP(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await fe(e.json(),t),typeof r.message=="string"?n=r.message:r.error&&typeof r.error=="string"?n=r.error:typeof r.detail=="string"?n=r.detail:typeof r.detail?.message=="string"?n=r.detail.message:typeof r.reason=="string"&&(n=r.reason)}catch{}if(t.aborted)throw me();return{message:n,data:r}}function EP(e,t,n){return Dm(e,t,n)||IP(e,t,n)||e===501&&t?.code===lo||e===409&&(t?.code===po||t?.code===go)||e===503&&(t?.code===mo||t?.code===fo)}async function jm(e,t,n,r){let{message:s,data:o}=await TP(e,t),i=new b(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Dm(e.status,o,s)?Om:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=tn(i));let a=e.status!==403?null:o?.code==="account_mfa_required"?"beeuni:mfa-required":o?.code==="sso_required"?"beeuni:sso-required":null;if(a&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a))}catch{}return e.status===431&&(i=new tt(431,{message:"Request is too large to process",suggestion:"Try uploading files one at a time, or reduce the number of files attached to your message."})),n&&!EP(e.status,o,s)&&k().onError?.(i,r),{error:i,success:!1}}var $m="X-Beeuni-Impersonate",ho="beeuni.impersonation",nt=null,Pr=!1,yo=new Set;function bo(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function Um(e,t=Date.now()){if(!e||!e.grantId||!e.accountId)return!1;let n=Date.parse(e.expiresAt);return Number.isFinite(n)&&n>t}function MP(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.grantId!="string"||typeof t?.accountId!="string"?null:{grantId:t.grantId,accountId:t.accountId,accountName:typeof t.accountName=="string"?t.accountName:null,expiresAt:typeof t.expiresAt=="string"?t.expiresAt:""}}catch{return null}}function Fm(){for(let e of yo)try{e()}catch{}}function Lm(){return Pr||(Pr=!0,nt=MP(bo()?.getItem(ho)??null)),nt&&!Um(nt)?(_o(),null):nt}function OP(e){if(Pr=!0,!e){_o();return}nt=e;try{bo()?.setItem(ho,JSON.stringify(e))}catch{}Fm()}function _o(){Pr=!0;let e=nt!==null;nt=null;try{bo()?.removeItem(ho)}catch{}e&&Fm()}function DP(e){return yo.add(e),()=>{yo.delete(e)}}var jP=/(^|\/)admin\/(api|analytics)(\/|$)/;function Bm(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!jP.test(t)}function Po(e){if(e!==void 0&&!Bm(e))return{};let t=Lm();return t?{[$m]:t.grantId}:{}}var vo=!1;function qm(e){vo=e}function Gm(){return vo}function $P(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function xo(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function nn(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function Sr(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap($P))nn(n,s,o);return n}function wo(e,t,n){let r={...t},s=k().clientVersion?.trim();s&&!xo(r,"x-beeuni-client-version")&&nn(r,"X-Beeuni-Client-Version",s),vo&&nn(r,"x-beeuni-admin-bypass","1");for(let[o,i]of Object.entries(Po(e)))nn(r,o,i);return xo(r,"authorization")||nn(r,"Authorization",`Bearer ${n}`),r}async function wr(e,t){let n=await xr();if(!n)throw new Q;return{headers:new Headers(wo(e,Sr(e,{headers:t}),n)),rejected:()=>rn(n)}}function UP(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function Nm(e,t,n,r,s){if(t instanceof Request){let u=new Headers(wo(t.url,Sr(t,n),r));return e(new Request(t,{headers:u,...s?{signal:s}:{}}))}let o=String(t),i=wo(o,Sr(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var Wm=null;async function Ao(e){let t=await yr(()=>k().getToken(),e);return t&&(Wm=t),t}var xr=Ao;function rn(e=Wm){e&&k().getToken.invalidate?.(e)}var So=new Map;function FP(e){let t=So.get(e);if(t)return t;let n=(async()=>(rn(e),xr({attempts:2,baseDelayMs:200})))().finally(()=>So.delete(e));return So.set(e,n),n}async function rt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=oo}=n,o=n.fetch??k().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:Em(e,t,s);if(i?.aborted)throw me();let a=await(i?fe(xr(),i):xr());if(!a)throw new Q;let u=r&&!UP(t)&&!xo(Sr(e,t),"authorization"),p=u&&e instanceof Request?e.clone():e,d=await Nm(o,e,t,a,i);if(d.status!==401||!u)return d;let g=await FP(a);return!g||g===a?d:Nm(o,p,t,g,i)}async function ke(e,t,n,r){let s=await rt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new b(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var Km=()=>k().backendUrl||"",LP=new Set([502,503,504]),BP=e=>LP.has(e),Hm=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},NP=e=>Hm(e)||(e??"GET").toUpperCase()==="DELETE",qP=2,vr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function Re(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...i}=t,a=new AbortController,u={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>u.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await GP(e,i,n,r,s,o,a,u)}finally{i.signal?.removeEventListener("abort",p)}}async function GP(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw me();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},s);let u={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await KP(e,t,u,s,o,i,a);if(p instanceof Q)return{error:p,success:!1};if(!p.ok)return await jm(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await fe(p.json(),a.activeController.signal):g?.includes("text/")?d=await fe(p.text(),a.activeController.signal):d=await fe(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(u){return HP(u,e,t.method,n,r,s,a)}finally{Ar(a)}}function Ar(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function WP(e,t,n){try{await fe(e.arrayBuffer(),t)}catch(r){if(vr(r))throw r}finally{Ar(n)}}async function KP(e,t,n,r,s,o,i){let a=Hm(t.method),u=NP(t.method),p=u?qP+1:1,d;for(let g=0;g<p;g++){g>0&&await _r(250*2**(g-1),t.signal??void 0);let m=g===0?o:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await fe(rt(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(f){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),f instanceof Q)return new Q;if(i.didTimeout&&vr(f)&&!t.signal?.aborted&&u&&g<p-1){i.didTimeout=!1;continue}if(vr(f)||g===p-1)throw f;continue}if(!a||!BP(d.status)||g===p-1)return s||Ar(i),d;await WP(d,m.signal,i)}return d}function HP(e,t,n,r,s,o,i){Ar(i);let a=vr(e);a&&(i.isAborted=!0);let u;if(a){if(!i.didTimeout)return{error:new b("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(Km(),"")||t;u=new b(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(u=new b(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(Km(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&k().onError?.(u,s)):(u=new b(String(e)),r&&k().onError?.(u,s));return{error:u,success:!1}}var Ce=()=>k().backendUrl||"",lo="feature_not_supported",po="model_not_servable",go="provision_in_flight",mo="analytics_unavailable",fo="accounts_list_unavailable",VP={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new b(r.message||"Database error",{code:r.code,details:r});return k().onError?.(s,t),{error:s,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new b(n.message,{name:n.name||"ApiError",stack:n.stack}):new b(String(n));return k().onError?.(r,t),{error:r,success:!1}}}};async function zP(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await rt(`${Ce()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof Q)return hr();throw a}finally{clearTimeout(i)}}var c={putRaw:(e,t,n)=>Re(`${Ce()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>Re(`${Ce()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>Re(`${Ce()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>Re(`${Ce()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>Re(`${Ce()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>Re(`${Ce()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Re(`${Ce()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Re(`${Ce()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:zP};function l(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function ko(e){return e.replace(/\/v1\/?$/,"")}async function Pt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=ko(e.backendUrl);try{let r=await fetch(`${n}${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(e.timeoutMs??8e3)});return r.ok?await r.json():null}catch{return null}}async function Ro(){return l(await c.get("/accounts"))}async function Co(e){return l(await c.post("/accounts",e))}async function Io(e){return l(await c.get(`/accounts/${e}`))}async function To(e,t){return l(await c.patch(`/accounts/${e}`,{name:t}))}async function Eo(e){return l(await c.get(`/accounts/${e}/branding`))}async function Mo(e,t){return l(await c.put(`/accounts/${e}/branding`,t))}async function Oo(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),l(await c.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function Do(e,t){return l(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function jo(e){return l(await c.delete(`/accounts/${e}/branding`))}async function $o(e){return l(await c.get(`/accounts/${e}/members`))}async function Uo(e,t){return l(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Fo(e){return l(await c.get(`/accounts/${e}/invites`))}async function Lo(e,t){return l(await c.delete(`/accounts/${e}/invites/${t}`))}async function Bo(e,t){return l(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function No(){return l(await c.get("/account-invites",{showErrors:!1})).invites}async function qo(e){return l(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function Go(e){return l(await c.post(`/account-invites/${e}/accept`,{}))}async function Wo(e){return l(await c.post(`/account-invites/${e}/decline`,{}))}async function Ko(e,t){return l(await c.delete(`/accounts/${e}/members/${t}`))}async function Ho(e,t,n){return l(await c.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Vo(e){return l(await c.post(`/accounts/${e}/leave`,{}))}async function YP(e){return Pt(e,"/v1/accounts")}async function zo(){let e=await c.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var QP=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","apps","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","us_region","event_triggers","notification_center","drives","ephemeral_sandboxes"];async function st(){return l(await c.get("/projects"))}async function Yo(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return l(await c.get(`/projects${t}`))}async function sn(e,t){return l(await c.get(`/projects/${e}`,t))}async function Qo(e,t,n="write"){return l(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Jo(e,t){return l(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Xo(e){return l(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function JP(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function on(e,t){let n=l(await c.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function an(e,t){return l(await c.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function cn(e,t){return l(await c.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function XP(e,t){return l(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Zo(e){return l(await c.post("/projects",e))}async function ei(e){return l(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function ti(e,t={}){return l(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Vm=200;function ZP(e){let t=e.split(`
1
+ "use strict";var Beeuni=(()=>{var li=Object.defineProperty;var Yw=Object.getOwnPropertyDescriptor;var Jw=Object.getOwnPropertyNames;var Qw=Object.prototype.hasOwnProperty;var Xw=(e,t)=>{for(var n in t)li(e,n,{get:t[n],enumerable:!0})},Zw=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Jw(t))!Qw.call(e,s)&&s!==n&&li(e,s,{get:()=>t[s],enumerable:!(r=Yw(t,s))||r.enumerable});return e};var ev=e=>Zw(li({},"__esModule",{value:!0}),e);var nU={};Xw(nU,{ABORT_REASONS:()=>uP,ABORT_REASONS_NOT_YET_EMITTED:()=>UL,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>Pi,ANALYTICS_UNAVAILABLE_CODE:()=>Si,ATTACHMENT_PART_REF_PREFIX:()=>VP,ApiError:()=>x,AuthError:()=>oe,BEEUNI_TRANSCRIPT_SCHEMA:()=>ke,BeeuniMemberError:()=>bt,BillingError:()=>rt,CAPTURE_DEVICE_DEFAULTS:()=>NT,CAPTURE_EXCLUSION_GROUPS:()=>$T,CAPTURE_FRAME_INTERVALS_MS:()=>UT,CAPTURE_LAYERS:()=>LT,CAPTURE_MAX_HEIGHTS:()=>FT,CAPTURE_RETENTION_LIMITS:()=>BT,CONNECTION_FAULT_GRACE_MS:()=>ex,CONNECTOR_POLL_FIRST_DELAY_MS:()=>NP,CONNECTOR_POLL_INTERVAL_MS:()=>qP,CONNECTOR_POLL_WINDOW_MS:()=>GP,CONTEXT_TOOLS:()=>bS,ConnectorApprovalPendingError:()=>Ps,ConnectorCallError:()=>Fn,ConnectorPageLimitError:()=>xs,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>SS,DEFAULT_NOTIFICATION_PREFERENCES:()=>KC,DEFAULT_TRANSCRIPT_OPTIONS:()=>af,FEATURE_DISABLED_CODE:()=>ns,FEATURE_FLAG_KEYS:()=>Bv,FEATURE_NOT_SUPPORTED_CODE:()=>yi,FILE_VERBS:()=>ht,FileExistsError:()=>cn,HeadlessAuthError:()=>Zt,HostBoundaryError:()=>vn,INBOX_NOTIFICATION_KINDS:()=>WC,INBOX_OBSERVATION_MAX_MS:()=>Yo,INITIAL_SETTLED_CONNECTION:()=>H$,KNOWN_TOOL_KINDS:()=>Yy,MAX_PROMPT_ATTACHMENTS_BYTES:()=>DA,MAX_PROMPT_ATTACHMENT_BYTES:()=>nl,MAX_PROMPT_ATTACHMENT_FILES:()=>Gy,MEMORY_VERBS:()=>Zj,MODEL_NOT_SERVABLE_CODE:()=>hi,NO_GROUP_ACTIVITY_TOOLS:()=>n_,OPTIMISTIC_ABORT_MAX_MS:()=>Jo,OPTIMISTIC_COMPACTION_MAX_MS:()=>i0,OPTIMISTIC_RECEIPT_MAX_MS:()=>Ho,PERSISTED_QUERY_CACHE_VERSION:()=>y2,PLUMBING_TOOLS:()=>qS,PREVIEW_PROBE_TIMEOUT_MS:()=>B$,PROJECT_ACTIONS:()=>Q,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>hk,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>yk,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>ch,PROVISION_IN_FLIGHT_CODE:()=>_i,PublicSessionShareError:()=>js,REVIEW_CONTROL_ACTIONS:()=>SR,RUNTIME_NOT_READY_MARKERS:()=>KL,RUNTIME_PERMISSION_CAPABILITIES:()=>YC,RUNTIME_PERMISSION_REPLIES:()=>zC,RequestTooLargeError:()=>wt,RuntimeNotReadyError:()=>on,SANDBOX_FS_ROOTS:()=>wo,SANDBOX_PORTS:()=>Je,SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE:()=>bi,SERVER_COMPACTION_REVALIDATE_MS:()=>sx,SERVER_OBSERVATION_MAX_MS:()=>zo,SESSION_LIST_STATUS:()=>S0,SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES:()=>ti,SESSION_LOG_MINOR:()=>Pe,SESSION_LOG_SCHEMA:()=>pe,SESSION_NOTICE:()=>w0,STANDALONE_TOOLS:()=>r_,STREAM_OBSERVATION_MAX_MS:()=>An,SandboxNotReadyError:()=>qr,SessionNotReadyError:()=>Mt,SessionStartError:()=>Es,TRIGGER_CONTROL_ACTIONS:()=>_R,TURN_END_LEDGER_LAG_MS:()=>Z$,TURN_ERROR_CODES:()=>$h,WAKE_ESCALATION_COOLDOWN_MS:()=>d0,WAKE_MAX_RESTARTS:()=>p0,WAKE_NO_PROGRESS_MS:()=>u0,WIRE_ID_BACKDATE_MS:()=>fo,WIRE_ID_CLOCK_TOLERANCE:()=>pt,WIRE_ID_TIME_MASK:()=>Qe,WIRE_ID_TIME_SCALE:()=>nn,WIRE_MESSAGE_ID:()=>C_,__getConfigResolver:()=>rv,__setConfigResolver:()=>nv,abortErrorReason:()=>FL,acceptAccountInvite:()=>us,acceptAccountInviteAndLand:()=>Gi,acceptInvite:()=>d$,accountInviteLanding:()=>Uy,actReviewItem:()=>ad,activateConnection:()=>gc,addComputerToProject:()=>yc,addGroupMembers:()=>Dp,addMarketplaceSource:()=>Nd,advanceWakeEscalation:()=>f0,allDescendantIds:()=>IS,appendPreviewToken:()=>Zf,approveCaptureDeviceGrant:()=>bm,approveCaptureEnrollment:()=>am,approveProjectAccessRequest:()=>ba,approveTask:()=>yE,archiveProject:()=>Un,assignTicket:()=>vE,attachGroupToProject:()=>Ta,authMfa:()=>uo,authUser:()=>ao,authenticatedFetch:()=>j,authenticatedRequest:()=>qn,authorizePreviewUrl:()=>$$,backendApi:()=>l,beeuniAppViewerToken:()=>yw,beeuniBinding:()=>hw,beeuniPty:()=>F_,beeuniToken:()=>fy,bindSlackIdentity:()=>Kk,bindTeamsIdentity:()=>Vk,brokerProjectSecretRequest:()=>Na,browserKeyValueStorage:()=>T$,buildPresentationTemplateImageUrl:()=>q$,buildPresentationTemplatePdfUrl:()=>N$,buildPreviewAuthEndpoint:()=>Xf,buildPublicTemplateUrl:()=>BP,buildRuntimePresentationConversionUrl:()=>ZP,buildSandboxTemplate:()=>zc,buildScrapeFailureResults:()=>$S,buildStaticFileHealthPreviewUrl:()=>SM,buildStaticFileLocalUrl:()=>bM,buildStaticFilePreviewUrl:()=>_M,buildStaticFileServicePath:()=>_b,buildTunnelEventStreamUrl:()=>vB,buildWebProxyUrl:()=>AM,bulkActReviewItems:()=>cd,bulkDeletePolicies:()=>ER,bulkImportPolicies:()=>IR,burstSummary:()=>qo,burstSummaryLabel:()=>GS,burstWorkLabel:()=>Tf,callConnector:()=>Rt,cancelAccountDeletion:()=>Ch,cancelAccountInvite:()=>Ui,cancelSandbox:()=>i$,cancelScheduledChange:()=>Lu,cancelSubscription:()=>Ou,captureHealthBucket:()=>KT,changeRequestControlsFrom:()=>Ah,checkAccessEmail:()=>vP,checkMcpServerSignIn:()=>wA,childMapByParent:()=>fD,claimNext:()=>Wb,claimPerSeatBilling:()=>Fk,claimWarmProjectSession:()=>$l,classifyPart:()=>Sf,classifyPreviewProbeStatus:()=>XP,classifyPtyClose:()=>$_,classifySessionLogMessage:()=>qx,classifyTurn:()=>jo,cleanErrorMessage:()=>xD,cleanResultSnippet:()=>kD,cleanWorkerOutput:()=>Hj,clearBeeuniAppViewerCache:()=>fw,clearModelDefault:()=>_u,clearSessionFresh:()=>zA,closeChangeRequest:()=>yl,closeMilestone:()=>XE,collectTurnParts:()=>pD,commentTicket:()=>kE,commitSessionChanges:()=>bl,compactionExpiryAtMs:()=>c0,compactionTurnInfo:()=>lj,compareMessagesForDisplay:()=>iD,compareSemver:()=>OM,completeInFlight:()=>Kb,completeSlackInstall:()=>zu,completeTeamsInstall:()=>Yu,composerSelectableAgents:()=>_y,computeStatusFromPart:()=>$f,configureAutoTopup:()=>Fu,configureBeeuni:()=>Xr,confirmCheckoutSession:()=>Iu,connectEmail:()=>rp,connectSlack:()=>Vu,connectionFromHealth:()=>V$,connectionIsFaulted:()=>K$,connectionSharedWithEveryone:()=>lA,connectorConnect:()=>Tc,connectorConnectConnection:()=>_c,connectorFinalize:()=>$c,connectorFinalizeConnection:()=>bc,connectorHeadline:()=>A$,contextLabelForTool:()=>jD,contextToolSummary:()=>uO,contextToolTrigger:()=>pO,convertPresentationToGoogleSlides:()=>mC,convertRuntimePresentation:()=>G$,copyFile:()=>xr,costExportUrl:()=>qu,countLiveInboxPrompts:()=>t0,countReviewItemsBySegment:()=>iR,createAccount:()=>Ci,createAccountAuditWebhook:()=>Ed,createAccountSecretResource:()=>Ja,createAccountToken:()=>_d,createApp:()=>Wd,createAppAccessSession:()=>Xd,createAppDeployment:()=>eg,createAppToken:()=>Hd,createAppVolume:()=>hg,createAppVolumeSnapshot:()=>Pg,createArtifactKind:()=>rj,createAssignment:()=>ed,createAuditWebhook:()=>iC,createBackup:()=>f$,createBeeuni:()=>Fb,createBeeuniPty:()=>Fm,createBeeuniSession:()=>go,createCaptureEnrollmentToken:()=>sm,createCheckoutSession:()=>Eu,createConnector:()=>Ec,createConnectorLinkInfoCache:()=>x$,createFile:()=>Pr,createGatewayKey:()=>Pp,createGroup:()=>Ep,createHttpSessionSyncController:()=>iw,createMarketplaceInstallSession:()=>PC,createMilestone:()=>JE,createModelVisibility:()=>Nw,createOAuthClient:()=>Yp,createPerSeatCheckout:()=>Uk,createPersistedQueryCache:()=>C$,createPolicy:()=>RR,createPortalSession:()=>Mu,createProject:()=>Zi,createProjectAgent:()=>LE,createProjectCliToken:()=>wd,createProjectRepo:()=>ea,createProjectResourceGrant:()=>Oa,createProjectSession:()=>Et,createProjectSkill:()=>ia,createProjectTrigger:()=>iu,createPromptAttachmentController:()=>sf,createRole:()=>Np,createSSEStream:()=>AB,createSandbox:()=>ZL,createSandboxShare:()=>ud,createSandboxTemplate:()=>Kc,createSavedCopyStore:()=>dk,createScimToken:()=>jR,createServiceAccountApi:()=>nC,createSessionPrompt:()=>Qn,createSessionPublicShare:()=>Dl,createSessionQueue:()=>qb,createSessionReminder:()=>gd,createSsoGroupMapping:()=>HR,createTask:()=>gE,createTicket:()=>PE,createTunnelEventStream:()=>kB,createWarmSessionPool:()=>pB,currentSavedCopyStore:()=>vl,declineAccountInvite:()=>Wi,declineInvite:()=>g$,deleteAccountImmediately:()=>Th,deleteAccountSecretResource:()=>Za,deleteApp:()=>Vd,deleteAppDeployment:()=>ig,deleteAuditWebhook:()=>cC,deleteBackup:()=>h$,deleteBeeuniProject:()=>KE,deleteConnector:()=>Mc,deleteConnectorCredential:()=>Lc,deleteCredential:()=>oI,deleteDriveFile:()=>UC,deleteEnv:()=>$m,deleteFile:()=>Lt,deleteGatewayBudget:()=>bp,deleteGitHubInstallation:()=>ha,deleteGroup:()=>Mp,deleteMilestone:()=>eI,deleteOAuthClient:()=>Xp,deletePersonalProjectSecret:()=>Ha,deletePolicy:()=>TR,deleteProjectAgent:()=>BE,deleteProjectProviderOAuth:()=>Ga,deleteProjectResourceGrant:()=>Da,deleteProjectSecret:()=>Ka,deleteProjectSession:()=>zl,deleteProjectTrigger:()=>cu,deletePromptAttachment:()=>Ht,deleteRole:()=>Wp,deleteSandboxTemplate:()=>Hc,deleteServiceAccountApi:()=>sC,deleteSessionPrompt:()=>ql,deleteSessionReminder:()=>$s,deleteSessionReminders:()=>fd,deleteSsoGroupMapping:()=>zR,deleteSsoProvider:()=>KR,deleteTask:()=>hE,deleteTicket:()=>RE,denyCaptureDeviceGrant:()=>Sm,denyCaptureEnrollment:()=>cm,describeAccountInvite:()=>qi,describeConnectorTool:()=>ys,destroyAppMachine:()=>gg,destroyAppVolume:()=>bg,detachGroupFromProject:()=>Ia,detectLocalhostUrls:()=>mb,directSubsessions:()=>A0,disableServiceAccountApi:()=>rC,disconnectEmail:()=>sp,disconnectSlack:()=>Qu,discoverConnectionOAuth2:()=>gA,discoverConnectionOAuth2Resource:()=>mA,discoverConnectorAuth:()=>Ic,discoverLocalSandbox:()=>r$,dismissDriveConflict:()=>MC,downloadAccountAudit:()=>$P,downloadDriveFile:()=>DC,dropClientForUrl:()=>fI,dropPublicClientForUrl:()=>_I,editQueued:()=>Yb,editSessionPrompt:()=>Gl,enqueue:()=>Gb,ensurePmSession:()=>DE,ensurePreviewSessionCookie:()=>QP,ensureProjectConnectorConnection:()=>uA,ensureSandbox:()=>mP,ensureWarmProjectSession:()=>Ll,env:()=>j_,exchangeCode:()=>so,execInApp:()=>fg,exportAccountAudit:()=>Cd,extractGatewayErrorDetails:()=>we,extractSkillBaseDir:()=>sP,extractSkillContent:()=>iL,extractSkillFiles:()=>rP,extractWorkerPreview:()=>Yj,failInFlight:()=>Vb,fallbackBusyRowAfterTurnId:()=>Cj,familyForTool:()=>Sn,featureDisabledKey:()=>gi,featureFlags:()=>Xg,fetchAccountStateWithToken:()=>Lk,fetchAccountsWithToken:()=>$v,fetchAttachmentPart:()=>E$,fetchBeeuniAppViewer:()=>my,fetchCostExportCsv:()=>Wk,fetchProjectArchive:()=>el,fetchProjectFileRaw:()=>OA,fetchProjectsForAccountWithToken:()=>Hv,fetchSessionAttachment:()=>Jg,fileDownloadRequest:()=>Q_,filePhase:()=>Xj,fileVerb:()=>Qj,files:()=>sb,finalizeAppArtifact:()=>Fs,finalizeConnectorSetupLink:()=>IP,findActiveTranscriptShare:()=>bk,findFiles:()=>br,findLastTextPart:()=>dD,findSessionAttachments:()=>IT,findText:()=>Sr,fireProjectTrigger:()=>uu,fixSandboxWithAgent:()=>Wc,flattenModels:()=>Bw,flattenThought:()=>mj,forkAppVolume:()=>wg,formatBillingErrorForUI:()=>fi,formatCost:()=>Uj,formatDuration:()=>Uf,formatJsonFailureOutput:()=>wD,formatMessageDay:()=>Sj,formatMessageExact:()=>Pj,formatOpenCodeRuntimeError:()=>YL,formatRawOutput:()=>AD,formatRuntimeError:()=>gP,formatTokens:()=>Fj,formatTranscript:()=>Qb,freshSendHint:()=>Mj,generateSessionId:()=>Nb,getAccount:()=>Ti,getAccountBranding:()=>Ii,getAccountDeletionStatus:()=>kh,getAccountState:()=>wu,getAccountStateMinimal:()=>vu,getAgentCardLabel:()=>wS,getAgentConfig:()=>Ik,getAgentPersona:()=>UE,getAllVersions:()=>yP,getAnsweredQuestionParts:()=>mD,getApp:()=>Bs,getAppAccess:()=>Yd,getAppAuthEnv:()=>zd,getAppDeployment:()=>ng,getAppDeploymentLogs:()=>rg,getApprovalLink:()=>SC,getAuthToken:()=>st,getAuthTokenWithRetry:()=>nA,getAutoTopupSettings:()=>Uu,getAutoTopupSetupStatus:()=>Bk,getBeeuniProject:()=>qE,getBeeuniProjectBySession:()=>GE,getBeeuniPtyWebSocketUrl:()=>Gm,getBillingCreditBreakdown:()=>Ru,getBillingTierConfigurations:()=>Tu,getBillingTransactionsSummary:()=>ku,getBillingUsageHistory:()=>Cu,getCaptureAssetUrl:()=>hm,getCaptureChunkMedia:()=>ym,getCaptureDays:()=>gm,getCaptureDeviceGrant:()=>_m,getCaptureFrame:()=>fm,getCapturePolicy:()=>lm,getCaptureTimeline:()=>pm,getCaptureTimelineItems:()=>dm,getCaptureWorkspace:()=>Pm,getChangeRequest:()=>pl,getChangeRequestDiff:()=>dl,getChangeRequestMergePreview:()=>gl,getChildSessionError:()=>AO,getChildSessionId:()=>Or,getChildSessionToolParts:()=>kO,getClient:()=>gt,getClientForUrl:()=>Oe,getConnectStatus:()=>Dc,getConnectionOAuth2Application:()=>dA,getConnectionOAuth2Status:()=>bA,getConnectionPolicies:()=>SA,getConnectorCatalog:()=>Vt,getConnectorConfig:()=>Rc,getConnectorPolicies:()=>Ac,getConnectorSetupLink:()=>TP,getCostSummary:()=>Gk,getCurrentProject:()=>zm,getDefaultAccountState:()=>xu,getDiagnostics:()=>EO,getDirectory:()=>xS,getDiscoverConnector:()=>Ss,getDiscoverIntegration:()=>RA,getDriveFileUrl:()=>vg,getEmailInstallation:()=>tp,getEmailMode:()=>np,getEnterpriseDemo:()=>uC,getFileStatus:()=>_r,getFileWithDir:()=>mf,getFilename:()=>PS,getFolderAccess:()=>RC,getFullChangelog:()=>Jf,getGatewayBreakdown:()=>mp,getGatewayBudgets:()=>hp,getGatewayErrors:()=>yp,getGatewayKeys:()=>Sp,getGatewayLog:()=>pp,getGatewayOverview:()=>dp,getGatewayRoutingPolicy:()=>ip,getGatewaySeries:()=>gp,getGatewaySessions:()=>fp,getGitHubInstallation:()=>la,getGoogleAuthUrl:()=>gC,getGroup:()=>Tp,getHiddenToolParts:()=>SO,getInvite:()=>p$,getLatestSandboxVersion:()=>fP,getManagedGitBackend:()=>Yv,getManagedGitStatus:()=>Gv,getMarketplaceCatalogItem:()=>Bd,getMarketplaceCatalogItemFile:()=>Ud,getMfaRequired:()=>$R,getMilestone:()=>zE,getMobileClientPolicy:()=>of,getModelDefaults:()=>yu,getMyCaptureFrame:()=>Am,getMyCaptureTimeline:()=>vm,getNotificationPreferences:()=>Tg,getOAuthClient:()=>zp,getOAuthConsentRequest:()=>RP,getOpenCodeConfigInvalidError:()=>qL,getPartText:()=>hO,getPatPolicy:()=>ZR,getPermissionForTool:()=>IO,getProject:()=>kt,getProjectActivity:()=>FE,getProjectCommit:()=>il,getProjectCommitDiff:()=>al,getProjectDetail:()=>jn,getProjectDrive:()=>kC,getProjectFileHistory:()=>cl,getProjectGitToken:()=>Xi,getProjectLlmCatalog:()=>Ln,getProjectLlmCatalogProviders:()=>Fv,getProjectModelAccess:()=>rr,getProjectModelPicker:()=>$n,getProjectSandboxHealth:()=>Nn,getProjectSandboxProviderTransition:()=>Wv,getProjectSession:()=>zn,getProjectSessionConfigState:()=>Ql,getProjectSessionScope:()=>eu,getProrationPreview:()=>$u,getProviders:()=>QL,getProxyBaseUrl:()=>PM,getPublicClientForUrl:()=>hI,getPublicMarketplaceItem:()=>xP,getPublicMarketplaceItemFile:()=>wP,getPublicSessionShare:()=>fC,getPublicSessionShareMessages:()=>yC,getPublicShareByToken:()=>DP,getPublicTemplate:()=>UP,getQuestionForTool:()=>MO,getReferralCode:()=>eR,getReferralStats:()=>rR,getRetryInfo:()=>Nj,getRetryMessage:()=>qj,getReviewItem:()=>od,getReviewSummary:()=>sd,getRolePermissions:()=>Up,getRoleUsage:()=>Fp,getRuntimeConfigInvalidError:()=>Vo,getSSHConnection:()=>b$,getSandbox:()=>XL,getSandboxById:()=>e$,getSandboxPortUrl:()=>JL,getSandboxUrl:()=>Hf,getSandboxUrlForExternalId:()=>Ie,getSecretSetupLink:()=>MP,getServerHealth:()=>vo,getServiceLogs:()=>uI,getSessionAudit:()=>Bl,getSessionCostRecord:()=>nr,getSessionDrives:()=>jh,getSessionHealth:()=>Xm,getSessionLogPage:()=>Fl,getSessionMessageAuthors:()=>ru,getSessionModelUsage:()=>su,getSessionOpenBundle:()=>Sk,getSessionOversight:()=>FR,getSessionParticipants:()=>Rl,getSessionPolicy:()=>YR,getSessionPreviewCandidates:()=>Ml,getSessionProviderSecretPool:()=>rc,getSessionTranscript:()=>Ul,getSessionTranscriptSync:()=>Yn,getSessionTurn:()=>Jn,getSessionWatch:()=>Cl,getShellModePart:()=>Vj,getSlackChannelFile:()=>Xu,getSlackInstallation:()=>Ku,getSlackManifest:()=>Ju,getSlackMode:()=>Hu,getSsoProvider:()=>qR,getStaticFileHealthPath:()=>bb,getTask:()=>uE,getTaskStatus:()=>dE,getTemplate:()=>xC,getTicket:()=>bE,getToolInfo:()=>RO,getToolPrimaryArg:()=>Eo,getTranscriptFilename:()=>Xb,getTurnError:()=>Lj,getTurnErrorDetails:()=>Bj,getTurnErrorRawText:()=>$j,getTurnStatus:()=>Bf,getTurnTokens:()=>Ff,getUsageRollup:()=>Nu,getVersionDiff:()=>ll,getWebPushPublicKey:()=>Ig,getWorkingState:()=>Dj,grantAccountSecretResource:()=>ec,grantSandboxProjectAccess:()=>l$,grantSecretToAgent:()=>Ok,groupMessagesIntoTurns:()=>cD,groupShowSegments:()=>Of,groupSteps:()=>Ef,hasDiffs:()=>Gj,hasLocalhostUrls:()=>fM,hasPreviewTarget:()=>hb,hasRetryingAssistantTurn:()=>wf,heartbeatGapEvent:()=>q_,holdSessionPrompts:()=>Vl,humanizeReviewActionPath:()=>Rp,humanizeSearchQuery:()=>Cr,humanizeToolName:()=>hf,importSsoProviderFromMetadata:()=>GR,inboxObservationSupersedes:()=>e0,initialWakeEscalationState:()=>ty,inputPath:()=>et,installTemplate:()=>wC,interruptSessionPrompt:()=>Wl,invalidateTokenCache:()=>gs,inviteAccountMember:()=>$i,inviteProjectMember:()=>va,inviteRepoCollaborator:()=>Ji,isAbortError:()=>Nr,isAgentPart:()=>dO,isAppRouteUrl:()=>gb,isAttachment:()=>_O,isAttachmentPartRef:()=>HP,isAuthFailure:()=>Nt,isBillingError:()=>mi,isCompactionPart:()=>gO,isConfigured:()=>Zr,isContextTool:()=>lO,isEmptyConversation:()=>gy,isEmptyShowPart:()=>zs,isErrorOutput:()=>hD,isExternalUrl:()=>CM,isFeatureDisabledError:()=>di,isFilePart:()=>ff,isInternalLocalhostUrl:()=>vM,isInvisibleActivityPart:()=>Wg,isInviteSent:()=>Qv,isLastUserMessage:()=>Oj,isLegacyMigratedSession:()=>ox,isManagedGithubProject:()=>Uv,isNoGroupActivityTool:()=>Gg,isOfferedModel:()=>ai,isOpenCodeConfigInvalidError:()=>GL,isPaintableSavedCopy:()=>rh,isPatchPart:()=>fO,isPersistableQueryKey:()=>R$,isPreviewUrl:()=>wM,isProxiableLocalhostUrl:()=>Sb,isQuestionTool:()=>qg,isReasoningPart:()=>Ae,isRetryableTurnError:()=>MS,isRuntimeConfigInvalidError:()=>pP,isRuntimeNotReadyResponse:()=>dP,isRuntimeReady:()=>Qm,isRuntimeStartingError:()=>zL,isSandboxNotReadyError:()=>wn,isSelectableAgent:()=>Js,isServerReachable:()=>Ym,isSessionAttachmentRef:()=>vT,isSessionFresh:()=>Pl,isSessionLogRestoreNote:()=>Vx,isSessionStartError:()=>kk,isShellActivityTool:()=>bT,isShellMode:()=>eP,isShortOutput:()=>zj,isShowContentUnavailable:()=>VC,isShowPayloadEmpty:()=>or,isSnapshotPart:()=>mO,isStandaloneActivityTool:()=>Kg,isStepPart:()=>yO,isSubdomainPreviewUrl:()=>Wr,isTextPart:()=>De,isToolPart:()=>te,isToolPartHidden:()=>PO,isTurnErrorCode:()=>jg,isUnderSandboxRoot:()=>Vm,isWebProxyUrl:()=>RM,isWireIdAheadOf:()=>E_,latestPromptModel:()=>Kw,leaveAccount:()=>Hi,linkCaptureDevice:()=>nm,linkGitHubInstallation:()=>fa,linkRepository:()=>aa,listAccountAudit:()=>kd,listAccountAuditWebhooks:()=>Td,listAccountInvites:()=>Bi,listAccountMembers:()=>Li,listAccountResourceGrants:()=>AR,listAccountSecretResources:()=>Ya,listAccountSessions:()=>QR,listAccountTokens:()=>hd,listAccounts:()=>Ri,listActions:()=>MR,listAgentIdentities:()=>$p,listAllConnections:()=>cc,listAppAgents:()=>Jd,listAppDeployments:()=>tg,listAppMachines:()=>cg,listAppVolumeSnapshots:()=>Sg,listAppVolumes:()=>yg,listApps:()=>Gd,listAssignments:()=>Zp,listAuditEvents:()=>lC,listAuditWebhooks:()=>oC,listBackups:()=>m$,listBeeuniProjectSessions:()=>WE,listBeeuniProjects:()=>NE,listBeeuniPty:()=>Um,listBillingTransactions:()=>Au,listCaptureDevices:()=>em,listCaptureEnrollmentTokens:()=>rm,listCaptureEnrollments:()=>im,listChangeRequests:()=>ul,listChannelBindings:()=>Qk,listColumns:()=>CE,listConnectSections:()=>AA,listConnectToolkits:()=>vA,listConnections:()=>ac,listConnectorAccounts:()=>hs,listConnectorTools:()=>fs,listConnectors:()=>Sc,listCostByProject:()=>qk,listCredentialEvents:()=>nI,listCredentials:()=>tI,listDiscoverConnectors:()=>bs,listDiscoverIntegrations:()=>kA,listDiscoverSections:()=>Oc,listDriveConflicts:()=>IC,listDriveFiles:()=>OC,listDriveFolder:()=>Dh,listDriveVersions:()=>FC,listEnv:()=>jm,listFeaturedMarketplaces:()=>$d,listFields:()=>EE,listFiles:()=>pn,listFolderPrincipals:()=>EC,listGatewayLogs:()=>up,listGitHubInstallations:()=>ua,listGitHubRepositories:()=>da,listGitHubRepositoryBranches:()=>ga,listGroupMembers:()=>Op,listGroupProjectGrants:()=>xR,listGroups:()=>Cp,listLinkableGitHubInstallations:()=>pa,listMarketplaceCatalogItems:()=>jd,listMarketplaceSources:()=>Fd,listMarketplaces:()=>Ld,listMemberGroups:()=>wR,listMemberProjectAccess:()=>vR,listMilestoneEvents:()=>YE,listMilestones:()=>HE,listMyAccountInvites:()=>Ni,listNotifications:()=>Rg,listOAuthClients:()=>Hp,listOAuthGrants:()=>Sd,listPendingApprovals:()=>ja,listPendingProjectInvites:()=>Aa,listPermissions:()=>nd,listPolicies:()=>kR,listProjectAccess:()=>Pa,listProjectAccessRequests:()=>_a,listProjectAgentIdentities:()=>Bp,listProjectAgents:()=>jE,listProjectAudit:()=>Rd,listProjectBranches:()=>sl,listProjectCliTokens:()=>xd,listProjectCommits:()=>ol,listProjectDirectory:()=>Qc,listProjectFiles:()=>Jc,listProjectGroupGrants:()=>Ca,listProjectPolicies:()=>Uc,listProjectProviderOAuth:()=>qa,listProjectReminders:()=>yd,listProjectResourceGrants:()=>Ma,listProjectSandboxTemplates:()=>Nc,listProjectSandboxes:()=>Yc,listProjectSecrets:()=>Ba,listProjectSessions:()=>Tt,listProjectSessionsPage:()=>Al,listProjectSnapshots:()=>qc,listProjectTriggerEventApps:()=>du,listProjectTriggerEventTypes:()=>pu,listProjectTriggers:()=>ou,listProjects:()=>At,listProjectsForAccount:()=>Yi,listPublicMarketplaceItems:()=>SP,listPublicMarketplaces:()=>PP,listReferrals:()=>sR,listReviewItems:()=>rd,listRoles:()=>Lp,listSandboxProjectMembers:()=>c$,listSandboxShares:()=>ld,listSandboxes:()=>n$,listScimTokens:()=>DR,listServiceAccountsApi:()=>tC,listServiceTemplates:()=>lI,listServices:()=>cI,listSessionConnectRequests:()=>xA,listSessionCosts:()=>Wu,listSessionDrives:()=>GC,listSessionPrompts:()=>Nl,listSessionProviderSecretPools:()=>sc,listSessionPublicShares:()=>Ol,listSessionReminders:()=>dd,listSessionsNeedingInput:()=>La,listSignedInDevices:()=>_C,listSsoGroupMappings:()=>VR,listTaskEvents:()=>pE,listTasks:()=>lE,listTemplates:()=>ME,listTicketEvents:()=>SE,listTickets:()=>_E,loadHttpSessionHistory:()=>ow,loadPreviewUrlTemplate:()=>ut,looksLikeError:()=>vf,looksLikeHtml:()=>ED,looksLikeJsonPayload:()=>vD,makeDriveFolder:()=>$C,mapApiReviewItem:()=>hR,markNotificationsRead:()=>Cg,markSessionFresh:()=>Vn,maxWireIdClock:()=>Im,memoryRelPath:()=>eL,mergeBurstSteps:()=>If,mergeChangeRequest:()=>fl,messageCreatedAt:()=>fj,messageTime:()=>YS,mintWireMessageId:()=>yo,mintWireMessageIdAbove:()=>Mm,mkdir:()=>fn,modelInDefaultView:()=>qw,modelRefToKey:()=>oi,moveDriveFile:()=>BC,narrateFailedStep:()=>Rf,narrateStep:()=>Br,narrationToolName:()=>$r,narrowChatEvent:()=>G_,newestWireIdClock:()=>I_,nextConnectorPollDelay:()=>v$,normalizeActivityToolName:()=>he,normalizeCaptureAppId:()=>WT,normalizeCaptureDomain:()=>GT,normalizeExternalInput:()=>TM,normalizeName:()=>ee,normalizeToolName:()=>yf,notifyHostSignal:()=>ax,openChangeRequest:()=>ml,openEventStream:()=>So,paginateConnector:()=>Bc,parseBillingError:()=>On,parseEmbeddedFailure:()=>RD,parseFlagOverride:()=>OT,parseJsonFailure:()=>DS,parseLocalhostUrl:()=>kr,parseMemoryView:()=>tL,parseOpenCodeErrorPayload:()=>NL,parsePresentationOutput:()=>sL,parseProxyHop:()=>Jm,parseQuestionAnswersFromOutput:()=>qf,parseReadOutput:()=>oL,parseRuntimeErrorPayload:()=>Vf,parseScrapeInputUrls:()=>LS,parseScrapeOutput:()=>BS,parseSubdomainUrl:()=>ef,parseTaskRows:()=>Jj,parseWebProxyUrl:()=>kM,parseWebSearchOutput:()=>Af,partOutcome:()=>Bo,patchBeeuniProject:()=>VE,patchVerb:()=>rL,pickerProviderList:()=>$w,platformConfig:()=>C,pollConnectionOAuth2DeviceAuthorization:()=>_A,pollProjectProviderOAuth:()=>ds,previewGatewayRoute:()=>lp,previewMfaRequired:()=>BR,previewSlackIdentity:()=>Hk,previewTeamsIdentity:()=>zk,probeEffectivePermission:()=>Kp,probeEffectivePermissions:()=>Vp,probePreviewPort:()=>U$,projectArchiveRequest:()=>tl,projectCompacting:()=>a0,projectConfigAgentsToOpenCodeAgents:()=>vw,projectConfigAgentsToRuntimeAgents:()=>hy,projectSessionConnection:()=>W$,projectSessionForRuntimeId:()=>k0,projectSessionStartSeed:()=>mu,projectWorking:()=>n0,provisionProject:()=>ta,provisionProjectStream:()=>qv,provisionProjectWithToken:()=>zv,proxyLocalhostUrl:()=>Zm,proxyUrlToInternal:()=>xM,purchaseCredits:()=>Bu,putConnectionOAuth2Application:()=>pA,rawErrorText:()=>Rr,reactivateSandbox:()=>a$,reactivateSubscription:()=>Du,readBeeuniMember:()=>si,readBlob:()=>gn,readDriveFile:()=>jC,readFile:()=>dn,readProjectFile:()=>Zc,readSavedSessionCopy:()=>gw,reasoningIsRunning:()=>Go,rebuildProjectSnapshot:()=>Gc,reconcileConnection:()=>lc,reconcileMemberConnection:()=>uc,reconcileServices:()=>dI,recordPlatformLogout:()=>kP,recoverLinkResults:()=>Uo,recoverProjectSession:()=>Yl,refreshReferralCode:()=>tR,refreshSession:()=>en,registerAppArtifact:()=>Us,registerConnectionOAuth2Client:()=>fA,registerDeviceToken:()=>Ag,registerService:()=>gI,registerWebPushSubscription:()=>Mg,rejectProjectAccessRequest:()=>Sa,relativizePath:()=>TO,reloadProjectSessionConfig:()=>Xl,reloadProjectSessionConfigStream:()=>Zl,removeAccountAuditWebhook:()=>Md,removeAccountBrandingAsset:()=>Di,removeAccountMember:()=>Ki,removeBeeuniPty:()=>qm,removeGroupMember:()=>jp,removeMarketplaceSource:()=>qd,removeQueued:()=>zb,renameConnection:()=>fc,renameFile:()=>vr,renameSandbox:()=>t$,reopenChangeRequest:()=>hl,reopenMilestone:()=>ZE,reorderQueued:()=>Jb,replaceColumns:()=>TE,replaceFields:()=>IE,replaceProjectRepository:()=>ca,replaceTemplates:()=>OE,requestAccountDeletion:()=>Rh,requestChangesOnChangeRequest:()=>_l,requestProjectAccess:()=>Jv,requestProjectConnector:()=>Dd,requestProjectSecret:()=>Od,requestTopUp:()=>$k,requireBeeuniMember:()=>Sw,resendAccountInvite:()=>Fi,resendPendingProjectInvite:()=>Ra,resetAccountBranding:()=>ji,resetClient:()=>yI,resetGatewayRoutingPolicy:()=>cp,resetPassword:()=>oo,resetPublicClient:()=>bI,resolveApproval:()=>$a,resolveComposerAgent:()=>ww,resolveComposerModel:()=>Hw,resolveConnectorStart:()=>w$,resolveModelDefault:()=>Ww,resolvePublicShareUrl:()=>_k,resolveScrapeResults:()=>ID,resolveWorkingTurn:()=>Lf,resolvedPlan:()=>jk,restartAppMachine:()=>dg,restartProjectSession:()=>Xn,restartSandbox:()=>s$,restoreAppVolume:()=>xg,restoreBackup:()=>y$,restoreDriveVersion:()=>NC,restoreProjectSession:()=>Jl,retryAccountSecretResource:()=>Xa,retryFailed:()=>Hb,retrySessionPrompt:()=>Kl,revealCredential:()=>sI,reviewItemTarget:()=>kp,reviewSegmentForStatus:()=>vh,reviewVerdictAllowed:()=>PR,reviewVerdictForStatus:()=>aR,revokeAccountSecretResourceGrant:()=>tc,revokeAccountSession:()=>XR,revokeAccountToken:()=>bd,revokeAssignment:()=>td,revokeCaptureDevice:()=>tm,revokeCaptureEnrollmentToken:()=>om,revokeConnection:()=>dc,revokeGatewayKey:()=>xp,revokeOAuthGrant:()=>Pd,revokePendingProjectInvite:()=>ka,revokeProjectAccess:()=>wa,revokeProjectCliToken:()=>vd,revokeSandboxProjectAccess:()=>u$,revokeSandboxShare:()=>pd,revokeScimToken:()=>LR,revokeSessionPublicShare:()=>jl,rewriteLocalhostUrl:()=>yt,rollbackApp:()=>ag,rootRuntimeSession:()=>ix,rotateAccountSecretResource:()=>Qa,rotateOAuthClientSecret:()=>Qp,runConnector:()=>ws,runGatewayPlayground:()=>wp,runProjectProviderOAuthFlow:()=>tA,runtimeSessionsOf:()=>Qo,runtimeSupports:()=>cb,sanitizePtyChunk:()=>U_,saveGitHubInstallation:()=>ma,savedCopyEmptyRoot:()=>dy,scaleApp:()=>mg,scheduleDowngrade:()=>ju,searchCapture:()=>mm,searchConnectorTools:()=>ic,searchMyCapture:()=>wm,searchProjectFiles:()=>Xc,segmentTurn:()=>Mf,selectableProjectAgents:()=>jT,sendMagicLink:()=>to,sendReferralEmails:()=>oR,serverCompactionRevalidateAtMs:()=>l0,serviceAction:()=>pI,sessionConnectionLabel:()=>x0,sessionListStatus:()=>P0,sessionLogActivityText:()=>jx,sessionLogAnsweredQuestionCall:()=>Nx,sessionLogBurstRunning:()=>Bx,sessionLogBurstSteps:()=>Dx,sessionLogBurstSummary:()=>Lx,sessionLogBurstWorkLabel:()=>$x,sessionLogCallStatus:()=>Rx,sessionLogFullTextAction:()=>Xx,sessionLogFullTextPlan:()=>Zx,sessionLogHarnessSwitches:()=>Hx,sessionLogOfV1Rows:()=>hx,sessionLogOpenCall:()=>Ux,sessionLogPromptMessage:()=>Cx,sessionLogReferencedTexts:()=>Jx,sessionLogRestoreNotice:()=>zx,sessionLogRetrying:()=>cy,sessionLogShowGroupCall:()=>Fx,sessionLogThreadMetrics:()=>Wx,sessionLogTurnSegments:()=>Mx,sessionLogTurns:()=>ei,sessionLogWithFullTexts:()=>ew,sessionModelCandidates:()=>Vw,sessionModelPin:()=>er,sessionParentId:()=>fk,sessionPromptActions:()=>wk,sessionStartKey:()=>Ck,setAccountSecretResourceAccess:()=>nc,setAgentScope:()=>bu,setBootstrapAuthToken:()=>sA,setCachedAuthToken:()=>rA,setCaptureEnabled:()=>xm,setCapturePolicy:()=>um,setConnectionPolicies:()=>PA,setConnectorAuthorizationStrategy:()=>wc,setConnectorCredential:()=>jc,setConnectorCredentialMode:()=>xc,setConnectorName:()=>Cc,setConnectorPolicies:()=>kc,setConnectorSecretBinding:()=>CA,setConnectorSensitive:()=>vc,setDefaultConnection:()=>mc,setEnterpriseDemo:()=>pC,setEnv:()=>Lm,setGatewayBudget:()=>_p,setGatewayRoutingPolicy:()=>ap,setMemberSuperAdmin:()=>OR,setMfaRequired:()=>UR,setModelDefault:()=>hu,setPersonalProjectSecret:()=>Va,setProjectModelAccess:()=>sr,setProjectModelEnablement:()=>Tk,setProjectOnboardingComplete:()=>oa,setProjectOnboardingProfile:()=>Vv,setProjectPolicies:()=>Fc,setProjectSecretStrategy:()=>Fa,setProjectSessionModel:()=>nu,setProjectSessionScope:()=>tu,setProjectSessionSharing:()=>kl,setProjectTriggersActivation:()=>lu,setSavedCopyStore:()=>gk,setSessionArchived:()=>Il,setSessionOversight:()=>NR,setSessionPinned:()=>El,setSessionProviderSecretPool:()=>oc,setSessionWatch:()=>Tl,settleSessionConnection:()=>z$,setupSSH:()=>_$,shareConnection:()=>hc,shareFolder:()=>CC,shellActivityGroupLabel:()=>ST,shellExitCode:()=>Wf,shouldHideResponsePart:()=>jj,shouldShowToolPart:()=>_n,shouldSuppressWorkingTurnBusy:()=>kj,showGroupItems:()=>Df,showTurnBusyIndicator:()=>jf,signInWithPassword:()=>eo,signInWithProvider:()=>ro,signInWithSso:()=>lo,signOut:()=>po,signOutDevice:()=>bC,signUp:()=>Zs,skillDocumentPath:()=>dL,skillInputDir:()=>lL,sortSessions:()=>yD,splitSessionLogTurnWork:()=>Ox,splitTurnWork:()=>Nf,splitUserParts:()=>bO,startApp:()=>sg,startAppMachine:()=>ug,startConnectionOAuth2Authorization:()=>yA,startConnectionOAuth2DeviceAuthorization:()=>hA,startConnectorSetupLink:()=>EP,startProjectProviderOAuth:()=>ps,startProjectSession:()=>it,startProjectSessionOrThrow:()=>fu,startSessionWithToken:()=>jP,startTask:()=>fE,stepLabel:()=>Pn,stopApp:()=>og,stopAppMachine:()=>pg,stopProjectSession:()=>Zn,stopSandbox:()=>o$,storeGitHubUserToken:()=>ya,stripAnsi:()=>DO,stripTrailingSlashes:()=>de,subAgentCalls:()=>Gx,submitAccessRequest:()=>AP,submitDemoRequest:()=>LP,submitOAuthConsent:()=>CP,submitReviewItem:()=>id,submitSecretSetupLink:()=>OP,syncConnectors:()=>Pc,syncSubscription:()=>Nk,systemReload:()=>PI,toDaemonPath:()=>ft,toInternalUrl:()=>Pb,toSandboxAbsolutePath:()=>un,toToolView:()=>bf,toWorkspaceRelative:()=>Hm,toolCallBlock:()=>ar,toolCallError:()=>t_,toolCallMetadata:()=>Qh,toolCallRawOutput:()=>e_,toolCallStatus:()=>Zh,toolInfo:()=>Mo,toolKind:()=>le,toolViewModel:()=>cP,triggerControlsFrom:()=>bR,triggersRequest:()=>L_,turnEndCause:()=>rx,turnEndNotice:()=>o0,turnHasSteps:()=>gD,turnIsConfirmedActive:()=>Tj,turnRendersQueued:()=>Ej,turnRetryLabel:()=>v0,unassignTicket:()=>AE,unregisterDeviceToken:()=>kg,unregisterWebPushSubscription:()=>Og,unshareFolder:()=>TC,unwrapError:()=>_e,updateAccountAuditWebhook:()=>Id,updateAccountBranding:()=>Mi,updateAccountMemberRole:()=>Vi,updateAccountName:()=>Ei,updateAgentConfig:()=>Mk,updateApp:()=>Kd,updateAppAccess:()=>Qd,updateAppVolume:()=>_g,updateAuditWebhook:()=>aC,updateBeeuniPty:()=>Nm,updateChangeRequest:()=>Sl,updateChannelBinding:()=>Xk,updateConnectionCredential:()=>pc,updateEmailPolicy:()=>op,updateExperimentalFeature:()=>ra,updateFeatureFlag:()=>na,updateGroup:()=>Ip,updateMilestone:()=>QE,updateNotificationPreferences:()=>Eg,updateOAuthClient:()=>Jp,updatePassword:()=>io,updatePatPolicy:()=>eC,updatePolicy:()=>CR,updateProject:()=>Bn,updateProjectAccess:()=>xa,updateProjectAgent:()=>$E,updateProjectDefaultAgent:()=>Pu,updateProjectGroupGrant:()=>Ea,updateProjectSandboxProvider:()=>sa,updateProjectSession:()=>Hl,updateProjectTrigger:()=>au,updateRole:()=>qp,updateRolePermissions:()=>Gp,updateSandboxTemplate:()=>Vc,updateSessionPolicy:()=>JR,updateSessionReminder:()=>Ls,updateSessionReminders:()=>md,updateTask:()=>mE,updateTemplateWarmPool:()=>Kv,updateTicket:()=>xE,updateTicketStatus:()=>wE,updateUserMetadata:()=>co,uploadAccountBrandingAsset:()=>Oi,uploadAppArtifactArchive:()=>Zd,uploadConnectorAttachment:()=>_s,uploadDriveFile:()=>LC,uploadFile:()=>mn,uploadNativeFile:()=>Z_,uploadPromptAttachment:()=>Kn,uploadSessionAttachment:()=>Yg,uploadSlackChannelFile:()=>Zu,uploadTimeoutMsForBytes:()=>an,upsertCredential:()=>rI,upsertProjectGitCredential:()=>Wa,upsertProjectSecret:()=>Ua,validateProjectManifest:()=>Qi,validateReferralCode:()=>nR,validateToken:()=>zi,verifyBeeuniToken:()=>xw,verifyGatewayProvider:()=>Zk,verifyOtp:()=>no,verifySsoDomain:()=>WR,wakeEscalationAttemptSummary:()=>b0,wakeEscalationNote:()=>h0,wakeProgressFingerprint:()=>g0,wireIdClock:()=>Dt,wireIdClockAt:()=>rn,wireIdClockDelta:()=>jt,workedForLabel:()=>Kj,workingExpiryAtMs:()=>r0,workingTurnDrawsBusyRow:()=>Ij,writeActivityGroupLabel:()=>PT,writeFile:()=>wr,wsDomain:()=>No,wsFavicon:()=>TD,wsRootDomain:()=>CD});var tv={backendUrl:"",getToken:async()=>null},ui=null,Qr=null;function nv(e){Qr=e}function rv(){return Qr}function Xr(e,t){t?.global!==!1&&(ui=e)}function C(){return Qr?.()??ui??tv}function Zr(){return ui!==null||Qr?.()!==void 0}function sv(e){return new Promise(t=>setTimeout(t,e))}async function es(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(o&&n?.(),s>0&&await sv(s)),i=await e(),i)return i;return i}var pi=12e4;function ov(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Ry(e,t,n=pi){let r=e instanceof Request?e.signal:t?.signal;if(ov(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function ts(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var x=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},oe=class extends x{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},rt=class extends x{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},wt=class extends x{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},iv="ENDPOINT_RETIRED";function G(e,t){let n=t?` ${t}`:"";return new x(`${e}() is retired: the Beeuni API no longer serves this endpoint.${n}`,{code:iv})}var ns="feature_disabled";function Cy(e){if(!(e instanceof x)||e.status!==403||e.code!==ns)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function di(e){let t=Cy(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function gi(e){let t=Cy(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function On(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new rt(t,{message:r?.message||e.message||"Billing error",...r},void 0,{code:e.code,details:e.details,data:e.data,response:e.response,url:e.url,endpoint:e.endpoint})}function mi(e){return e instanceof rt}function Nt(e){if(e instanceof oe)return!0;let t=e?.status;return t===401||t===403}function fi(e){if(!(e instanceof rt))return null;let t=e.detail?.message?.toLowerCase()||"";return t.includes("credit")||t.includes("balance")||t.includes("insufficient")?{alertTitle:"You ran out of credits",alertSubtitle:"Upgrade your plan to get more credits and continue using the AI assistant."}:{alertTitle:"Billing check failed",alertSubtitle:e.detail?.message||"Please upgrade to continue."}}function Re(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function Ce(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(Re())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function rs(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(Re())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var Ty="request_deadline",av=/^Request exceeded the \d+s server processing deadline$/,Ey=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ty||av.test(n),cv="git_mirror_unavailable",lv=/^git mirror is temporarily unavailable$/,uv=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===cv||lv.test(n),pv="connectors_provider_unavailable",dv=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===pv;async function gv(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await Ce(e.json(),t),typeof r.message=="string"?n=r.message:r.error&&typeof r.error=="string"?n=r.error:typeof r.detail=="string"?n=r.detail:typeof r.detail?.message=="string"?n=r.detail.message:typeof r.reason=="string"&&(n=r.reason)}catch{}if(t.aborted)throw Re();return{message:n,data:r}}function mv(e,t,n){return Ey(e,t,n)||uv(e,t,n)||dv(e,t)||e===501&&t?.code===yi||e===409&&(t?.code===hi||t?.code===_i||t?.code===bi)||e===503&&(t?.code===Si||t?.code===Pi)}async function Iy(e,t,n,r){let{message:s,data:o}=await gv(e,t),i=new x(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Ey(e.status,o,s)?Ty:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=On(i));let a=e.status===403&&(o?.code==="account_mfa_required"||o?.code==="sso_required")?o.code:null;if(a){try{C().onAccessRemedy?.(a)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a==="account_mfa_required"?"beeuni:mfa-required":"beeuni:sso-required"))}catch{}}return e.status===431&&(i=new wt(431,{message:"Request is too large to process",suggestion:"Try uploading files one at a time, or reduce the number of files attached to your message."})),n&&!mv(e.status,o,s)&&C().onError?.(i,r),{error:i,success:!1}}var fv="X-Beeuni-Impersonate",My="beeuni.impersonation",qt=null,xi=!1,yv=new Set;function Oy(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function hv(e,t=Date.now()){if(!e||!e.grantId||!e.accountId)return!1;let n=Date.parse(e.expiresAt);return Number.isFinite(n)&&n>t}function _v(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.grantId!="string"||typeof t?.accountId!="string"?null:{grantId:t.grantId,accountId:t.accountId,accountName:typeof t.accountName=="string"?t.accountName:null,expiresAt:typeof t.expiresAt=="string"?t.expiresAt:""}}catch{return null}}function bv(){for(let e of yv)try{e()}catch{}}function Sv(){return xi||(xi=!0,qt=_v(Oy()?.getItem(My)??null)),qt&&!hv(qt)?(Pv(),null):qt}function Pv(){xi=!0;let e=qt!==null;qt=null;try{Oy()?.removeItem(My)}catch{}e&&bv()}var xv=/(^|\/)admin\/(api|analytics)(\/|$)/;function wv(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!xv.test(t)}function Dy(e){if(e!==void 0&&!wv(e))return{};let t=Sv();return t?{[fv]:t.grantId}:{}}var vv=!1;function Av(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function ss(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Gt(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function os(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(Av))Gt(n,s,o);return n}function vi(e,t,n){let r={...t},s=C().clientVersion?.trim();s&&!ss(r,"x-beeuni-client-version")&&Gt(r,"X-Beeuni-Client-Version",s),vv&&Gt(r,"x-beeuni-admin-bypass","1");for(let[i,a]of Object.entries(Dy(e)))Gt(r,i,a);let o=C().credentialHeader?.trim();return o?ss(r,o)||Gt(r,o,n):ss(r,"authorization")||Gt(r,"Authorization",`Bearer ${n}`),r}async function as(e,t){let n=await is();if(!n)throw new oe;return{headers:new Headers(vi(e,os(e,{headers:t}),n)),rejected:()=>Dn(n)}}function kv(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function jy(e,t,n,r,s){if(t instanceof Request){let c=new Headers(vi(t.url,os(t,n),r));return e(new Request(t,{headers:c,...s?{signal:s}:{}}))}let o=String(t),i=vi(o,os(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var Ly=null;async function Ai(e){let t=await es(()=>C().getToken(),e);return t&&(Ly=t),t}var is=Ai;function Dn(e=Ly){e&&C().getToken.invalidate?.(e)}var wi=new Map;function Rv(e){let t=wi.get(e);if(t)return t;let n=(async()=>(Dn(e),is({attempts:2,baseDelayMs:200})))().finally(()=>wi.delete(e));return wi.set(e,n),n}async function vt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=pi}=n,o=n.fetch??C().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:Ry(e,t,s);if(i?.aborted)throw Re();let a=await(i?Ce(is(),i):is());if(!a)throw new oe;let c=r&&!kv(t)&&!ss(os(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await jy(o,e,t,a,i);if(d.status!==401||!c)return d;let g=await Rv(a);return!g||g===a?d:jy(o,p,t,g,i)}async function Fe(e,t,n,r){let s=await vt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new x(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var $y=()=>C().backendUrl||"",Cv=new Set([502,503,504]),Tv=e=>Cv.has(e),By=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Ev=e=>By(e)||(e??"GET").toUpperCase()==="DELETE",Iv=2,cs=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function Ne(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...i}=t,a=new AbortController,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await Mv(e,i,n,r,s,o,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function Mv(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw Re();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},s);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Dv(e,t,c,s,o,i,a);if(p instanceof oe)return{error:p,success:!1};if(!p.ok)return await Iy(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await Ce(p.json(),a.activeController.signal):g?.includes("text/")?d=await Ce(p.text(),a.activeController.signal):d=await Ce(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return jv(c,e,t.method,n,r,s,a)}finally{ls(a)}}function ls(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Ov(e,t,n){try{await Ce(e.arrayBuffer(),t)}catch(r){if(cs(r))throw r}finally{ls(n)}}async function Dv(e,t,n,r,s,o,i){let a=By(t.method),c=Ev(t.method),p=c?Iv+1:1,d;for(let g=0;g<p;g++){g>0&&await rs(250*2**(g-1),t.signal??void 0);let m=g===0?o:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await Ce(vt(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(f){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),f instanceof oe)return new oe;if(i.didTimeout&&cs(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(cs(f)||g===p-1)throw f;continue}if(!a||!Tv(d.status)||g===p-1)return s||ls(i),d;await Ov(d,m.signal,i)}return d}function jv(e,t,n,r,s,o,i){ls(i);let a=cs(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new x("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace($y(),"")||t;c=new x(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(c=new x(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace($y(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&C().onError?.(c,s)):(c=new x(String(e)),r&&C().onError?.(c,s));return{error:c,success:!1}}var qe=()=>C().backendUrl||"",yi="feature_not_supported",hi="model_not_servable",_i="provision_in_flight",bi="sandbox_state_change_in_progress",Si="analytics_unavailable",Pi="accounts_list_unavailable";async function Lv(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await vt(`${qe()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof oe)return ts();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>Ne(`${qe()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>Ne(`${qe()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>Ne(`${qe()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>Ne(`${qe()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>Ne(`${qe()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>Ne(`${qe()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Ne(`${qe()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Ne(`${qe()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:Lv};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function ki(e){return e.replace(/\/v1\/?$/,"")}async function Wt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=ki(e.backendUrl);try{let r=await fetch(`${n}${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(e.timeoutMs??8e3)});return r.ok?await r.json():null}catch{return null}}async function Ri(){return u(await l.get("/accounts"))}async function Ci(e){return u(await l.post("/accounts",e))}async function Ti(e){return u(await l.get(`/accounts/${e}`))}async function Ei(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function Ii(e){return u(await l.get(`/accounts/${e}/branding`))}async function Mi(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function Oi(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function Di(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function ji(e){return u(await l.delete(`/accounts/${e}/branding`))}async function Li(e){return u(await l.get(`/accounts/${e}/members`))}async function $i(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Bi(e){return u(await l.get(`/accounts/${e}/invites`))}async function Ui(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function Fi(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Ni(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function qi(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function us(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}function Uy(e,t){let n=e.bootstrap_grants_applied?.[0]??t?.projects?.[0];return n?{kind:"project",projectId:n.project_id,accountId:e.account_id}:{kind:"account",accountId:e.account_id}}async function Gi(e,t){let n=await us(e);return{accepted:n,landing:Uy(n,t)}}async function Wi(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function Ki(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function Vi(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Hi(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function $v(e){return Wt(e,"/v1/accounts")}async function zi(){let e=await l.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var Bv=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","genui","us_region","event_triggers","notification_center","volumes","drives","session_log","session_log_restore"];async function At(){return u(await l.get("/projects"))}async function Yi(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function kt(e,t){return u(await l.get(`/projects/${e}`,t))}async function Ji(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Qi(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Xi(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function Uv(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function jn(e,t){let n=u(await l.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function Ln(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function $n(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function Fv(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Zi(e){return u(await l.post("/projects",e))}async function ea(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function ta(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Fy=200;function Nv(e){let t=e.split(`
2
2
  `).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
3
- `);try{return JSON.parse(n)}catch(r){let s=n.length>Vm?`${n.slice(0,Vm)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function eS(e,t,n={}){let r=await c.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let u=await r.json().catch(()=>null);throw new b(u?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:u?.code})}let s=r.body?.getReader();if(!s)throw new Error("Provision stream is unavailable on this runtime (no response body)");let o=new TextDecoder,i="",a=null;try{for(;;){let{done:u,value:p}=await s.read();if(u)break;i+=o.decode(p,{stream:!0});let d=i.indexOf(`
3
+ `);try{return JSON.parse(n)}catch(r){let s=n.length>Fy?`${n.slice(0,Fy)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function qv(e,t,n={}){let r=await l.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let c=await r.json().catch(()=>null);throw new x(c?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:c?.code})}let s=r.body?.getReader();if(!s)throw new Error("Provision stream is unavailable on this runtime (no response body)");let o=new TextDecoder,i="",a=null;try{for(;;){let{done:c,value:p}=await s.read();if(c)break;i+=o.decode(p,{stream:!0});let d=i.indexOf(`
4
4
 
5
5
  `);for(;d!==-1;){let g=i.slice(0,d);i=i.slice(d+2),d=i.indexOf(`
6
6
 
7
- `);let m=ZP(g);if(m){if(t(m),m.type==="error")throw new b(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function tS(){try{return l(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function un(e,t){return l(await c.patch(`/projects/${e}`,t))}async function ni(e,t,n){return l(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function ri(e,t,n){return l(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function si(e,t){return l(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function nS(e,t){return l(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function rS(e,t){throw F("updateTemplateWarmPool")}async function oi(e,t){return l(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function sS(e,t){return l(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function ln(e){return l(await c.delete(`/projects/${e}`))}async function oS(e,t){return Pt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function iS(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=ko(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let s=await r.json().catch(()=>null);return s?.project_id?{ok:!0,project:s}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function ii(e,t,n){return l(await c.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function ai(e){return l(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function ci(e){let{project_id:t,...n}=e;return l(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function ui(e){return l(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function li(e){return l(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function pi(e){return l(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function di(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),l(await c.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function gi(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return l(await c.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function mi(e){return l(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function fi(e){return l(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function yi(e){return l(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function hi(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),l(await c.delete(`/projects/github/installation?${n.toString()}`))}async function bi(){return l(await c.get("/projects/git/backend",{showErrors:!1}))}async function _i(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return l(await c.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function aS(e,t){return l(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Pi(e,t){return l(await c.get(`/projects/${e}/access-requests`,t))}async function Si(e,t,n="member"){return l(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function xi(e,t){return l(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function wi(e){return l(await c.get(`/projects/${e}/access`))}async function vi(e,t,n){return l(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function Ai(e,t){return l(await c.delete(`/projects/${e}/access/${t}`))}function cS(e){return"status"in e&&e.status==="invited"}async function ki(e,t,n,r){return l(await c.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Ri(e){return l(await c.get(`/projects/${e}/access/pending-invites`))}async function Ci(e,t){return l(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Ii(e,t){return l(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Ti(e){return l(await c.get(`/projects/${e}/group-grants`))}async function Ei(e,t,n,r){return l(await c.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function Mi(e,t,n,r){return l(await c.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function Oi(e,t){return l(await c.delete(`/projects/${e}/group-grants/${t}`))}async function Di(e){return l(await c.get(`/projects/${e}/resource-grants`))}async function ji(e,t){return l(await c.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function $i(e,t){return l(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function Ui(e,t){return l(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Fi(e,t){return l(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Li(e,t,n,r={}){let s=r.note?.trim();return l(await c.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function Bi(e){return l(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Ni(e,t){return l(await c.post(`/projects/${e}/secrets`,t))}async function qi(e,t,n,r={}){return l(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Gi(e,t,n){return l(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Wi(e){return l(await c.get(`/projects/${e}/oauth`)).items??[]}async function kr(e,t,n){return l(await c.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function Rr(e,t,n){return l(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Ki(e,t){return l(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var uS=2e3,lS=3e3,pS=10*6e4;async function dS(e){let{projectId:t,provider:n,input:r,onChallenge:s,isCancelled:o,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,u=()=>o?.()??!1,p=await kr(t,n,r);if(u())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(uS,p.interval_ms||lS),g=p.expires_at||a()+pS;for(;!u()&&a()<g;){if(await i(d),u())return{status:"cancelled"};let m;try{m=await Rr(t,n,p.flow_id)}catch{continue}if(u())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return u()?{status:"cancelled"}:{status:"expired"}}async function Hi(e,t){return l(await c.put(`/projects/${e}/git-credential`,t))}async function Vi(e,t){return l(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function zi(e,t,n){return l(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Yi(e,t){return l(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var Qi=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,St=(e,t)=>`${Qi(e)}/${encodeURIComponent(t)}`,zm=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Ji(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return l(await c.get(`${Qi(e)}${n}`))}async function Xi(e,t){return l(await c.post(Qi(e),t))}async function Zi(e,t,n){return l(await c.put(`${St(e,t)}/value`,{value:n}))}async function ea(e,t){return l(await c.post(`${St(e,t)}/retry`))}async function ta(e,t){return l(await c.delete(St(e,t)))}async function na(e,t,n,r){return l(await c.put(`${St(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function ra(e,t,n,r){return l(await c.delete(`${St(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function sa(e,t,n,r){return l(await c.put(`${St(e,t)}/access`,{mode:n,user_ids:r}))}async function oa(e,t,n){return l(await c.get(zm(e,t,n)))}async function ia(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return l(await c.get(n))}async function aa(e,t,n,r){return l(await c.put(zm(e,t,n),{secret_ids:r}))}async function Cr(){return Ao()}async function Ym(e){return yr(()=>k().getToken(),e,Ir)}function Ir(){rn()}function gS(e){e===null&&rn()}function mS(e){}async function xt(){return Cr()}async function fS(e){return Ym(e)}async function E(e,t,n){try{return await rt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof Q)return hr();throw r}}function Tr(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function wt(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return l(await c.get(`${Tr(e,"catalog")}${r}`)).connectors??[]}async function Er(e){let t=[];for(let n of await wt(e,{includeSchemas:!1}))for(let r of n.actions)t.push({tool:`${n.slug}.${r.path}`,connector:n.slug,action:r.path,risk:r.risk,description:r.description||r.name,inputSchema:r.inputSchema});return t}async function ca(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await Er(e)){let u=`${a.tool} ${a.description}`.toLowerCase();!r||u.includes(r)?o.push(a):s.every(p=>u.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function Mr(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await wt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===r);if(!s)return null;for(let o of s.actions){let i=`${s.slug}.${o.path}`;if(i===t)return{tool:i,connector:s.slug,action:o.path,risk:o.risk,description:o.description||o.name,inputSchema:o.inputSchema,outputSchema:o.outputSchema??null}}return null}function yS(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var hS=9e4;async function ot(e,t,n={},r={}){let{connector:s,action:o}=yS(t),i=r.account?.trim(),a=r.approvalContext?.trim(),u=l(await c.post(Tr(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??hS,signal:r.signal}));return u.ok&&u.binding!==void 0&&!("output"in u)&&(u.output=u.data),u}async function Or(e,t){let n=await c.get(Tr(e,`connectors/${encodeURIComponent(t)}/accounts`));return l(n).accounts??[]}function bS(e,t){if(e&&typeof e=="object"){let n=e;for(let r of["reason","error","message","detail"])if(typeof n[r]=="string"&&n[r])return n[r]}return`HTTP ${t}`}function _S(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}async function Dr(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Beeuni-Attachment-Filename":encodeURIComponent(r),"X-Beeuni-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Beeuni-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(o["X-Beeuni-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=_S(k().backendUrl),a=Tr(e,"attachments"),u=await E(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await u.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!u.ok)throw new b(bS(d,u.status),{status:u.status,code:String(d&&typeof d=="object"?d.code??u.status:u.status),details:d,response:u,endpoint:a});return d}function PS(e){if(e.owner_type!=="project")return!1;let t=e.shared_with??[];return t.length===0||t.some(n=>n.principal_type==="project")}async function ua(e){return l(await c.get(`/projects/${e}/connections`))}async function la(e){return l(await c.get(`/projects/${e}/connections/all`))}async function pa(e,t){return l(await c.post(`/projects/${e}/connections`,t))}async function da(e,t){return l(await c.post(`/projects/${e}/connections/me`,t))}async function ga(e,t,n){return l(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function Ie(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function SS(e,t){return l(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function xS(e,t,n){return l(await c.put(Ie(e,t,"application"),n))}async function wS(e,t){return l(await c.get(Ie(e,t,"application")))}async function vS(e,t,n){return l(await c.post(Ie(e,t,"discover"),n))}async function AS(e,t,n={}){return l(await c.post(Ie(e,t,"discover-resource"),n))}async function kS(e,t,n){return l(await c.post(Ie(e,t,"register"),n))}async function RS(e,t,n){return l(await c.post(Ie(e,t,"authorize"),n))}async function CS(e,t,n){return l(await c.post(Ie(e,t,"device"),n))}async function IS(e,t,n){return l(await c.post(Ie(e,t,`device/${encodeURIComponent(n)}`),{}))}async function TS(e,t){return l(await c.get(Ie(e,t,"status")))}async function ma(e,t){return l(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function fa(e,t){return l(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function ya(e,t){return l(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function ha(e,t,n){return l(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function ba(e,t){return l(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function _a(e,t,n=[]){return l(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Pa(e,t,n={}){return l(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function Sa(e,t){return l(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function xa(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return l(await c.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function wa(e){return l(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function va(e,t,n){return l(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Aa(e,t,n){return l(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function ka(e,t,n){return l(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Ra(e,t){return l(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Ca(e,t,n){return l(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function ES(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function MS(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Ia(e,t){return l(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Ta(e,t,n){return l(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Qm(e,t,n={}){return l(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var Ea=Qm;async function OS(e,t){return l(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Ma(e,t){return l(await c.post(`/connectors/projects/${e}/connectors`,t))}async function Oa(e,t){return l(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function Da(e,t){return l(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function ja(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return l(await c.get(`/connectors/projects/${e}/pipedream/apps${o?`?${o}`:""}`))}async function $a(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return l(await c.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function DS(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=l(await c.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function jS(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return l(await c.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function jr(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return l(await c.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function Ua(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return l(await c.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function $r(e,t){let n=new URLSearchParams({id:t});return l(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var $S=jr,US=$r;async function Fa(){return l(await c.get("/connectors/connect-status"))}async function La(e,t,n){let r=typeof n=="string"?{value:n}:n;return l(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function Ba(e,t){return l(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function FS(e,t,n){return l(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Jm(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),l(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Na=Jm;var pn=class extends b{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds:u,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=s,this.action=o,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=u??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},Ur=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},Fr=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,s){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=s,Object.setPrototypeOf(this,new.target.prototype)}},ye=e=>typeof e=="string"&&e?e:null;function Xm(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function LS(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function BS(e,t,n){if(!(e instanceof b)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=ye(r.reason)??ye(r.error)??e.message,o=/^upstream_(\d{3})\b/.exec(s),i=typeof r.upstream_status=="number"?r.upstream_status:o?Number(o[1]):null;return new pn(ye(r.message)??ye(r.hint)??s,{status:e.status,code:i===null?Xm(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:ye(r.connector)??t,action:ye(r.action)??n,binding:ye(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:LS(e.response),connectUrl:ye(r.connect_url),hint:ye(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:ye(r.requested_account)})}function NS(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function Lr(e,t,n,r={},s={}){let o=t.trim(),i=n.trim();if(!o||!i)throw new Error("connector slug and action are required");let a;try{a=await ot(e,`${o}.${i}`,r,s)}catch(u){throw BS(u,o,i)}if(a.status==="pending_approval")throw new Ur(o,i,a);if(!a.ok||a.upstream_error){let u=a.upstream_error??a.reason??"connector_error";throw new pn(u,{status:200,code:a.upstream_error?"upstream_error":Xm(u),details:a,data:a,reason:u,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return NS(a)}async function*qa(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,u=r;for(let p=0;u;p++){if(p>=i)throw new Fr(t,n,i,u);let d=await Lr(e,t,n,u,a);yield d,u=o(d,u)}}async function Ga(e){return l(await c.get(`/connectors/projects/${e}/policies`))}async function Wa(e,t,n){return l(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Ka(e){return l(await c.get(`/projects/${e}/sandboxes`))}async function Ha(e){return l(await c.get(`/projects/${e}/snapshots`))}async function dn(e){return l(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Va(e,t){return l(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function za(e){return l(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Ya(e,t){return l(await c.post(`/projects/${e}/sandbox-templates`,t))}async function Qa(e,t,n){return l(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Ja(e,t){return l(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Xa(e,t){return l(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Za(e){return l(await c.get(`/projects/${e}/sandboxes`))}async function gn(e){let t=new URL(k().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Beeuni backend: ${n.origin}`);let{headers:r}=await wr(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function ec(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return l(await c.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function tc(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),l(await c.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function nc(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),l(await c.get(`/projects/${e}/files/search?${r.toString()}`))}async function rc(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),l(await c.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var qS=10*6e4;async function sc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=`${k().backendUrl||""}/projects/${e}/files/archive${s}`;return await(await ke(o,{method:"GET"},{timeoutMs:qS},"Failed to download")).blob()}async function oc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return gn(`${k().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function GS(e,t,n,r){let s=new URLSearchParams({path:t});n&&s.set("ref",n);let o=s.toString()?`?${s.toString()}`:"",i=`${k().backendUrl||""}/projects/${e}/files/raw${o}`;return await(await ke(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var ic=52428800,WS=104857600,Zm=20;var Nr=e=>`/projects/${encodeURIComponent(e)}/attachments`,qr={showErrors:!1,deadlineCoversBody:!0},ef=3e4,KS=12e4,HS=6e4,VS=5*6e4,zS=6e4,YS=6e4;function Br(){return new b("Request aborted",{name:"AbortError",code:"ABORTED"})}function mn(e){if(e?.aborted)throw Br()}function QS(e){return!(e instanceof b)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function fn(e,t,n=!1){let r;for(let s=0;;s++){mn(t);try{return await e()}catch(o){let i=n&&o instanceof b&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(QS(o)||i))throw o;r??=Date.now()+(n?VS:HS);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await _r(a,t)}catch{throw mn(t),o}}}}function JS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function ac(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&JS(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!i)throw new Error("Invalid attachment upload handle");return e}async function tf(e,t,n,r){return l(await c.post(Nr(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...qr,signal:n,timeout:ef}),"Failed to start attachment upload")}async function nf(e,t,n,r){let s=ac({...await fn(()=>tf(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function rf(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new b(r,{status:e,details:n,code:String(n?.statusCode??e)})}function XS(e){if(!(e instanceof b))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function ZS(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,u=!1,p,d=f=>{u||(u=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?o(f):s())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new b("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},zS)},m=()=>{d(Br()),i.abort()};i.open(t.method,t.url);for(let[f,h]of Object.entries(t.headers))i.setRequestHeader(f,h);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d(rf(i.status,i.responseText))},i.onerror=()=>d(new b("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(Br()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function ex(e,t,n){let r=k().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?Br():new b(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw rf(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function tx(e,t,n){mn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?ZS(r,e,t,n):ex(e,t,n)}async function nx(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let i=s.upload;try{await fn(()=>tx(i,t,r),r.signal)}catch(a){let u=XS(a);if(u!==409){if(o||!(u===400||u===401||u===403))throw a;o=!0,s=await nf(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return sf(e,t,s,r)}async function sf(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${Nr(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){mn(r.signal);let a=i.received_bytes,u=Math.min(a+s,t.size),p=t.slice(a,u),d=await fn(async()=>l(await c.putRaw(`${o}/chunks/${a/s}`,p,{...qr,signal:r.signal,timeout:ef}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==u)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:u},r.onUpload?.(i),r.onProgress?.(u,t.size)}return i}async function yn(e,t,n={}){if(!e)throw new Error("A project is required to upload attachments");if(!Number.isSafeInteger(t.size)||t.size<=0||t.size>52428800)throw new Error("Attachment must contain 1 byte to 50 MiB");mn(n.signal);let r=n.resume?ac({...n.resume},t):ac({...await fn(()=>tf(e,t,n.signal),n.signal),received_bytes:0},t);n.onUpload?.(r),r.received_bytes<t.size&&(r.upload.kind==="direct"&&Date.parse(r.upload.expires_at)-Date.now()<YS&&(r=await nf(e,t,r,n)),r=r.upload.kind==="direct"?await nx(e,t,r,n):await sf(e,t,r,n)),n.onProcessing?.();let s=`${Nr(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await fn(async()=>l(await c.post(`${s}/complete`,{},{...qr,signal:n.signal,timeout:KS}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof b&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function vt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${Nr(e)}/${encodeURIComponent(t)}`,{...qr,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function cc(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return l(await c.get(`/projects/${e}/branches${r}`))}async function uc(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return l(await c.get(`/projects/${e}/commits${r}`))}async function lc(e,t){return l(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function pc(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return l(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function dc(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),l(await c.get(`/projects/${e}/files/history?${r.toString()}`))}async function gc(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return l(await c.get(`/projects/${e}/version-diff?${n.toString()}`))}async function mc(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit));let s=r.toString()?`?${r.toString()}`:"";return l(await c.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function fc(e,t){return l(await c.get(`/projects/${e}/change-requests/${t}`))}async function yc(e,t){return l(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function hc(e,t){return l(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function bc(e,t){return l(await c.post(`/projects/${e}/change-requests`,t))}async function _c(e,t,n){return l(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Pc(e,t){return l(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Sc(e,t){return l(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function xc(e,t,n){return l(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function wc(e,t,n){return l(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function vc(e,t,n){return l(await c.patch(`/projects/${e}/change-requests/${t}`,n))}var At=new Set,rx=500;function hn(e){e&&(At.add(e),At.size>rx&&At.delete(At.values().next().value))}function Ac(e){return!!e&&At.has(e)}function sx(e){e&&At.delete(e)}function kc(e){return!!e&&e.available===!0&&e.source==="mirror"&&Array.isArray(e.messages)&&e.messages.length>0&&!!(e.runtime_session_id??e.opencode_session_id)}var Gr=1,ox=12,ix=15e5,ax=3e5,cx=336*60*60*1e3,ux="beeuni.saved-copy";function Rc(e){return!!e&&typeof e.then=="function"}function lx(e,t){return Rc(e)?e.then(t):t(e)}function px(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let s=a=>{let u=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:u,message_count:u.length,complete:!1,next_cursor:String(u[0].info.id)}})},o=s(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(o+a>t)break;o+=a,i+=1}for(;i>0;i-=1){let a=s(i);if(a.length<=t)return a}return null}function dx(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}function gx(e){let{storage:t,userId:n,maxSessions:r=ox,maxBytes:s=ix,maxEnvelopeBytes:o=ax,maxAgeMs:i=cx,namespace:a=ux,now:u=()=>Date.now()}=e,p=`${a}:${n}:`,d=`${p}index`,g=(w,P)=>`${p}${w}/${P}`,m=w=>{try{let P=t.getItem(w);return Rc(P)?P.catch(()=>null):P}catch{return null}},f=w=>{try{let P=t.removeItem(w);Rc(P)&&P.catch(()=>{})}catch{}},h=async w=>{try{await t.removeItem(w)}catch{}},x=w=>{if(!w)return[];try{let P=JSON.parse(w);return P?.v===Gr&&Array.isArray(P.entries)?P.entries:[]}catch{return[]}},D=Promise.resolve(),j=w=>{let P=D.then(w,w);return D=P.catch(()=>{}),P},L=async w=>{try{await t.setItem(d,JSON.stringify({v:Gr,entries:w}))}catch{}},y=async()=>x(await m(d)),_=async(w,P)=>{let A=[...w].sort((T,B)=>T.u-B.u),I=A.reduce((T,B)=>T+B.b,0);for(;A.length>r||I>s;){let T=A.findIndex($=>$.s!==P);if(T===-1)break;let[B]=A.splice(T,1);I-=B.b,await h(`${p}${B.s}`)}return A},S=w=>{j(async()=>{let P=await y(),A=P.find(I=>I.s===w);A&&(A.u=u(),await L(P))})},M=w=>j(async()=>{await h(`${p}${w}`);let P=await y(),A=P.filter(I=>I.s!==w);A.length!==P.length&&await L(A)});return{keyFor:g,read(w,P){let A=`${w}/${P}`;return lx(m(g(w,P)),I=>{if(!I)return null;let T;try{T=JSON.parse(I)}catch{return f(g(w,P)),M(A),null}return!T||T.v!==Gr||T.user!==n||u()-T.at>i||!kc(T.e)?(f(g(w,P)),M(A),null):(S(A),T.e)})},write(w,P,A){let I=`${w}/${P}`;if(!kc(A))return M(I);let T={v:Gr,user:n,at:u(),e:A},B=px(T,o);if(B===null)return M(I);let $=dx(A);return j(async()=>{let N=await y(),q=N.find(xe=>xe.s===I);if(q&&$>0&&q.c>$)return;let de=N.filter(xe=>xe.s!==I),ue={s:I,b:B.length,u:u(),c:$},Xe=await _([...de,ue],I),yt=g(w,P);try{await t.setItem(yt,B)}catch{let xe=Xe.filter(we=>we.s!==I).sort((we,ie)=>we.u-ie.u)[0];xe&&(await h(`${p}${xe.s}`),Xe=Xe.filter(we=>we.s!==xe.s));try{await t.setItem(yt,B)}catch{await h(yt),Xe=Xe.filter(we=>we.s!==I)}}await L(Xe)})},remove(w,P){return M(`${w}/${P}`)},clear(){return j(async()=>{let w=await y();for(let P of w)await h(`${p}${P.s}`);await h(d)})}}}var of=null;function mx(e){of=e}function Cc(){return of}var fx=new Set;function af(e){for(let t of fx)try{t(e)}catch{}}function yx(e){let t=typeof e.parent_session_id=="string"?e.parent_session_id:e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var hx=50,cf=200,bx=cf;function uf(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return t.size>0?`?${t}`:""}async function Ic(e,t){let n=await c.get(`/projects/${e}/sessions${uf(t)}`);return{items:l(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function it(e,t){return l(await c.get(`/projects/${e}/sessions${uf(t)}`))}async function Tc(e,t,n){return l(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Ec(e,t){return l(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Mc(e,t){return l(await c.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Oc(e,t,n){return l(await c.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}function _x(e,t){let n=e.public_url??e.public_path??e.proxy_path??e.public_token??"";if(!n)return"";if(/^https?:\/\//.test(n))return n;if(t)try{return new URL(n,t).toString()}catch{return n}return n}function Px(e,t=new Date){let n=null;for(let r of e)r.resource_type!=="transcript"||r.revoked_at||r.expires_at&&Date.parse(r.expires_at)<=t.getTime()||(!n||Date.parse(r.created_at)>Date.parse(n.created_at))&&(n=r);return n}async function Dc(e,t){return l(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function jc(e,t){return l(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function $c(e,t,n){return l(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Uc(e,t,n){return l(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function at(e,t){let n=l(await c.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||hn(n?.session_id),n}async function Fc(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=l(await c.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||hn(r.session.session_id),r}async function Lc(e,t){let n=l(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return hn(n.session_id),n}async function bn(e,t,n){return l(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Bc(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return l(await c.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function Nc(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return l(await c.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function qc(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),l(await c.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Gc(e,t){return l(await c.get(`/projects/${e}/sessions/${t}/turn`))}async function Sx(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return l(await c.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function xx(e){if(e)return e==="interrupt"?"transcript":"composer"}async function _n(e,t,n){let r=n.placement??xx(n.delivery);return l(await c.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Wc(e,t){return l(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Kc(e,t,n){return l(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Hc(e,t,n,r){return l(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Vc(e,t,n){return l(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function zc(e,t,n){return l(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Yc(e,t,n){return l(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Qc(e,t,n){return l(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function Jc(e,t){let n=l(await c.delete(`/projects/${e}/sessions/${t}`));return Cc()?.remove(e,t),n}async function Pn(e,t,n={}){return l(await c.post(`/projects/${e}/sessions/${t}/restart`,n.reset_machine?{reset_machine:!0,...n.discard_state?{discard_state:!0}:{}}:{}))}async function Sn(e,t){let n=l(await c.post(`/projects/${e}/sessions/${t}/stop`,{}));return af(t),n}async function Xc(e,t){return l(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function wx(e){let t=e.split(`
7
+ `);let m=Nv(g);if(m){if(t(m),m.type==="error")throw new x(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function Gv(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Bn(e,t){return u(await l.patch(`/projects/${e}`,t))}async function na(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function ra(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function sa(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function Wv(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function Kv(e,t){throw G("updateTemplateWarmPool")}async function oa(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function Vv(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Un(e){return u(await l.delete(`/projects/${e}`))}async function Hv(e,t){return Wt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function zv(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=ki(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let s=await r.json().catch(()=>null);return s?.project_id?{ok:!0,project:s}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function ia(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function aa(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function ca(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function la(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ua(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function pa(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function da(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function ga(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await l.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function ma(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function fa(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function ya(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function ha(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await l.delete(`/projects/github/installation?${n.toString()}`))}async function Yv(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function Jv(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function _a(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function ba(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Sa(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Pa(e){return u(await l.get(`/projects/${e}/access`))}async function xa(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function wa(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function Qv(e){return"status"in e&&e.status==="invited"}async function va(e,t,n,r){return u(await l.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Aa(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function ka(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Ra(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Ca(e){return u(await l.get(`/projects/${e}/group-grants`))}async function Ta(e,t,n,r){return u(await l.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function Ea(e,t,n,r){return u(await l.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function Ia(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function Ma(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function Oa(e,t){return u(await l.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function Da(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function ja(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function La(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function $a(e,t,n,r={}){let s=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function Ba(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Ua(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function Fa(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Na(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function qa(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function ps(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function ds(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Ga(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Xv=2e3,Zv=3e3,eA=10*6e4;async function tA(e){let{projectId:t,provider:n,input:r,onChallenge:s,isCancelled:o,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,c=()=>o?.()??!1,p=await ps(t,n,r);if(c())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Xv,p.interval_ms||Zv),g=p.expires_at||a()+eA;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await ds(t,n,p.flow_id)}catch{continue}if(c())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return c()?{status:"cancelled"}:{status:"expired"}}async function Wa(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function Ka(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Va(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Ha(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var za=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Kt=(e,t)=>`${za(e)}/${encodeURIComponent(t)}`,Ny=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Ya(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${za(e)}${n}`))}async function Ja(e,t){return u(await l.post(za(e),t))}async function Qa(e,t,n){return u(await l.put(`${Kt(e,t)}/value`,{value:n}))}async function Xa(e,t){return u(await l.post(`${Kt(e,t)}/retry`))}async function Za(e,t){return u(await l.delete(Kt(e,t)))}async function ec(e,t,n,r){return u(await l.put(`${Kt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function tc(e,t,n,r){return u(await l.delete(`${Kt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function nc(e,t,n,r){return u(await l.put(`${Kt(e,t)}/access`,{mode:n,user_ids:r}))}async function rc(e,t,n){return u(await l.get(Ny(e,t,n)))}async function sc(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function oc(e,t,n,r){return u(await l.put(Ny(e,t,n),{secret_ids:r}))}async function st(){return Ai()}async function nA(e){return es(()=>C().getToken(),e,gs)}function gs(){Dn()}function rA(e){e===null&&Dn()}function sA(e){}async function j(e,t,n){try{return await vt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof oe)return ts();throw r}}function ms(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Vt(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`${ms(e,"catalog")}${r}`)).connectors??[]}async function fs(e){let t=[];for(let n of await Vt(e,{includeSchemas:!1}))for(let r of n.actions)t.push({tool:`${n.slug}.${r.path}`,connector:n.slug,action:r.path,risk:r.risk,description:r.description||r.name,inputSchema:r.inputSchema});return t}async function ic(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await fs(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?o.push(a):s.every(p=>c.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function ys(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await Vt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===r);if(!s)return null;for(let o of s.actions){let i=`${s.slug}.${o.path}`;if(i===t)return{tool:i,connector:s.slug,action:o.path,risk:o.risk,description:o.description||o.name,inputSchema:o.inputSchema,outputSchema:o.outputSchema??null}}return null}function oA(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var iA=9e4;async function Rt(e,t,n={},r={}){let{connector:s,action:o}=oA(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(ms(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??iA,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function hs(e,t){let n=await l.get(ms(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function aA(e,t){if(e&&typeof e=="object"){let n=e;for(let r of["reason","error","message","detail"])if(typeof n[r]=="string"&&n[r])return n[r]}return`HTTP ${t}`}function cA(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}async function _s(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Beeuni-Attachment-Filename":encodeURIComponent(r),"X-Beeuni-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Beeuni-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(o["X-Beeuni-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=cA(C().backendUrl),a=ms(e,"attachments"),c=await j(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new x(aA(d,c.status),{status:c.status,code:String(d&&typeof d=="object"?d.code??c.status:c.status),details:d,response:c,endpoint:a});return d}function lA(e){if(e.owner_type!=="project")return!1;let t=e.shared_with??[];return t.length===0||t.some(n=>n.principal_type==="project")}async function ac(e){return u(await l.get(`/projects/${e}/connections`))}async function cc(e){return u(await l.get(`/projects/${e}/connections/all`))}async function lc(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function uc(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function pc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function Ge(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function uA(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function pA(e,t,n){return u(await l.put(Ge(e,t,"application"),n))}async function dA(e,t){return u(await l.get(Ge(e,t,"application")))}async function gA(e,t,n){return u(await l.post(Ge(e,t,"discover"),n))}async function mA(e,t,n={}){return u(await l.post(Ge(e,t,"discover-resource"),n))}async function fA(e,t,n){return u(await l.post(Ge(e,t,"register"),n))}async function yA(e,t,n){return u(await l.post(Ge(e,t,"authorize"),n))}async function hA(e,t,n){return u(await l.post(Ge(e,t,"device"),n))}async function _A(e,t,n){return u(await l.post(Ge(e,t,`device/${encodeURIComponent(n)}`),{}))}async function bA(e,t){return u(await l.get(Ge(e,t,"status")))}async function dc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function gc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function mc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function fc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function yc(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function hc(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function _c(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function bc(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Sc(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await l.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function Pc(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function xc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function wc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function vc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Ac(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function kc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function SA(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function PA(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Rc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Cc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Tc(e,t,n={}){return u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}async function xA(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Ec(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function Ic(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function wA(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function Mc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function vA(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=u(await l.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function AA(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function bs(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await l.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function Oc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function Ss(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var kA=bs,RA=Ss;async function Dc(){return u(await l.get("/connectors/connect-status"))}async function jc(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function Lc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function CA(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function $c(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Fn=class extends x{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds:c,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=s,this.action=o,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},Ps=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},xs=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,s){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=s,Object.setPrototypeOf(this,new.target.prototype)}},Te=e=>typeof e=="string"&&e?e:null;function qy(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function TA(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function EA(e,t,n){if(!(e instanceof x)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Te(r.reason)??Te(r.error)??e.message,o=/^upstream_(\d{3})\b/.exec(s),i=typeof r.upstream_status=="number"?r.upstream_status:o?Number(o[1]):null;return new Fn(Te(r.message)??Te(r.hint)??s,{status:e.status,code:i===null?qy(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Te(r.connector)??t,action:Te(r.action)??n,binding:Te(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:TA(e.response),connectUrl:Te(r.connect_url),hint:Te(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Te(r.requested_account)})}function IA(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function ws(e,t,n,r={},s={}){let o=t.trim(),i=n.trim();if(!o||!i)throw new Error("connector slug and action are required");let a;try{a=await Rt(e,`${o}.${i}`,r,s)}catch(c){throw EA(c,o,i)}if(a.status==="pending_approval")throw new Ps(o,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new Fn(c,{status:200,code:a.upstream_error?"upstream_error":qy(c),details:a,data:a,reason:c,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return IA(a)}async function*Bc(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,c=r;for(let p=0;c;p++){if(p>=i)throw new xs(t,n,i,c);let d=await ws(e,t,n,c,a);yield d,c=o(d,c)}}async function Uc(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function Fc(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Nc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function qc(e){return u(await l.get(`/projects/${e}/snapshots`))}async function Nn(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Gc(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Wc(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Kc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function Vc(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Hc(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function zc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Yc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function qn(e){let t=new URL(C().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Beeuni backend: ${n.origin}`);let{headers:r}=await as(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function Jc(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function Qc(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),t?.cursor&&n.set("cursor",t.cursor),t?.limit!==void 0&&n.set("limit",String(t.limit)),u(await l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function Xc(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await l.get(`/projects/${e}/files/search?${r.toString()}`))}async function Zc(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var MA=10*6e4;async function el(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=`${C().backendUrl||""}/projects/${e}/files/archive${s}`;return await(await Fe(o,{method:"GET"},{timeoutMs:MA},"Failed to download")).blob()}async function tl(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return qn(`${C().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function OA(e,t,n,r){let s=new URLSearchParams({path:t});n&&s.set("ref",n);let o=s.toString()?`?${s.toString()}`:"",i=`${C().backendUrl||""}/projects/${e}/files/raw${o}`;return await(await Fe(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var nl=52428800,DA=104857600,Gy=20;var As=e=>`/projects/${encodeURIComponent(e)}/attachments`,ks={showErrors:!1,deadlineCoversBody:!0},Wy=3e4,jA=12e4,LA=6e4,$A=5*6e4,BA=6e4,UA=6e4;function vs(){return new x("Request aborted",{name:"AbortError",code:"ABORTED"})}function Gn(e){if(e?.aborted)throw vs()}function FA(e){return!(e instanceof x)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Wn(e,t,n=!1){let r;for(let s=0;;s++){Gn(t);try{return await e()}catch(o){let i=n&&o instanceof x&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(FA(o)||i))throw o;r??=Date.now()+(n?$A:LA);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await rs(a,t)}catch{throw Gn(t),o}}}}function NA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function rl(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&NA(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!i)throw new Error("Invalid attachment upload handle");return e}async function Ky(e,t,n,r){return u(await l.post(As(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...ks,signal:n,timeout:Wy}),"Failed to start attachment upload")}async function Vy(e,t,n,r){let s=rl({...await Wn(()=>Ky(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function Hy(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new x(r,{status:e,details:n,code:String(n?.statusCode??e)})}function qA(e){if(!(e instanceof x))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function GA(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?o(f):s())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new x("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},BA)},m=()=>{d(vs()),i.abort()};i.open(t.method,t.url);for(let[f,h]of Object.entries(t.headers))i.setRequestHeader(f,h);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d(Hy(i.status,i.responseText))},i.onerror=()=>d(new x("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(vs()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function WA(e,t,n){let r=C().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?vs():new x(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw Hy(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function KA(e,t,n){Gn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?GA(r,e,t,n):WA(e,t,n)}async function VA(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let i=s.upload;try{await Wn(()=>KA(i,t,r),r.signal)}catch(a){let c=qA(a);if(c!==409){if(o||!(c===400||c===401||c===403))throw a;o=!0,s=await Vy(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return zy(e,t,s,r)}async function zy(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${As(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Gn(r.signal);let a=i.received_bytes,c=Math.min(a+s,t.size),p=t.slice(a,c),d=await Wn(async()=>u(await l.putRaw(`${o}/chunks/${a/s}`,p,{...ks,signal:r.signal,timeout:Wy}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==c)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:c},r.onUpload?.(i),r.onProgress?.(c,t.size)}return i}async function Kn(e,t,n={}){if(!e)throw new Error("A project is required to upload attachments");if(!Number.isSafeInteger(t.size)||t.size<=0||t.size>52428800)throw new Error("Attachment must contain 1 byte to 50 MiB");Gn(n.signal);let r=n.resume?rl({...n.resume},t):rl({...await Wn(()=>Ky(e,t,n.signal),n.signal),received_bytes:0},t);n.onUpload?.(r),r.received_bytes<t.size&&(r.upload.kind==="direct"&&Date.parse(r.upload.expires_at)-Date.now()<UA&&(r=await Vy(e,t,r,n)),r=r.upload.kind==="direct"?await VA(e,t,r,n):await zy(e,t,r,n)),n.onProcessing?.();let s=`${As(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Wn(async()=>u(await l.post(`${s}/complete`,{},{...ks,signal:n.signal,timeout:jA}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof x&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Ht(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${As(e)}/${encodeURIComponent(t)}`,{...ks,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function sl(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/branches${r}`))}async function ol(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/commits${r}`))}async function il(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function al(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function cl(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await l.get(`/projects/${e}/files/history?${r.toString()}`))}async function ll(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await l.get(`/projects/${e}/version-diff?${n.toString()}`))}async function ul(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit)),n?.cursor&&r.set("cursor",n.cursor);let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function pl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function dl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function gl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function ml(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function fl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function yl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function hl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function _l(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function bl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function Sl(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var zt=new Set,HA=500;function Vn(e){e&&(zt.add(e),zt.size>HA&&zt.delete(zt.values().next().value))}function Pl(e){return!!e&&zt.has(e)}function zA(e){e&&zt.delete(e)}var pe="beeuni.session/2",Pe=1,Yy=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var ie=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Y=e=>typeof e=="string",Ee=e=>Y(e)&&e.length>0,Ke=e=>e===null||Y(e),J=(e,t)=>e===void 0||t(e),We=(...e)=>t=>e.includes(t),Hn=e=>Number.isInteger(e)&&e>=0,Yt=e=>typeof e=="number",Xy=e=>e.schema===pe&&Hn(e.v),Ct=e=>J(e,Y),xl=e=>e===void 0||ie(e)&&Object.values(e).every(t=>ie(t)&&Y(t.version)),Zy=e=>e===null||ie(e)&&Y(e.provider)&&Y(e.model)&&Ct(e.variant),YA=e=>e===null||ie(e)&&Yt(e.input)&&Yt(e.output)&&Yt(e.cache_read)&&Yt(e.cache_write)&&J(e.reasoning,Yt)&&J(e.cost,Yt),Jy=e=>ie(e)&&(e.type==="text"&&Y(e.text)||e.type==="attachment"&&Y(e.mime)),JA=e=>ie(e)&&Array.isArray(e.content)&&e.content.every(Jy)&&J(e.model_content,t=>Array.isArray(t)&&t.every(Jy))&&typeof e.is_error=="boolean",Qy={text:e=>Y(e.text)&&J(e.bytes,Hn)&&Ct(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>Y(e.text),attachment:e=>Y(e.mime)&&Ct(e.ref)&&J(e.bytes,Hn)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>Y(e.call_id)&&Y(e.name)&&Ee(e.kind)&&We("pending","running","complete","error")(e.status)&&J(e.result,JA),compaction:e=>Ke(e.summary)&&Ke(e.first_kept_message_id),subtask:e=>Y(e.thread_id)&&Y(e.agent)&&Y(e.description),step:e=>We("start","finish")(e.phase),harness:e=>Ee(e.harness)&&Ee(e.kind)&&typeof e.model_visible=="boolean"};function QA(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!ie(r)||!Ee(r.id)||n.has(r.id)||!Object.hasOwn(Qy,r.type)||!Qy[r.type](r)||!xl(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function XA(e){return ie(e)&&Xy(e)&&Ee(e.message_id)&&Ee(e.thread_id)&&Number.isInteger(e.seq)&&We("user","assistant","system")(e.role)&&We("turn","compaction","context")(e.kind)&&We("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&J(e.hidden_reason,We("failed_attempt","aborted","retracted","reverted","superseded"))&&J(e.origin,We("prompt","steer","command","automation","subagent","notification"))&&J(e.agent,Ke)&&J(e.reply_to,Ke)&&J(e.parent_message_id,Ke)&&Ct(e.native_agent_id)&&Ct(e.context_ref)&&Zy(e.model)&&YA(e.usage)&&We("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||ie(e.error)&&Ee(e.error.code)&&Y(e.error.message))&&Y(e.created_at)&&Ke(e.completed_at)&&ie(e.producer)&&Ee(e.producer.harness)&&Y(e.producer.harness_version)&&Y(e.producer.adapter_version)&&xl(e.ext)&&QA(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function ZA(e){return ie(e)&&Xy(e)&&Ee(e.thread_id)&&Ke(e.parent_thread_id)&&(e.spawned_by===null||ie(e.spawned_by))&&Y(e.created_at)}function ek(e){return ie(e)&&J(e.schema,t=>t===pe)&&J(e.v,Hn)&&Ct(e.session_id)&&J(e.title,Ke)&&Ct(e.created_at)&&J(e.restore_grade,We("native","converted","partial"))&&J(e.todos,Array.isArray)&&J(e.pending,t=>ie(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&J(e.selection,t=>ie(t)&&J(t.agent,Ke)&&Zy(t.model??null))&&J(e.harness,t=>ie(t)&&Y(t.current)&&Array.isArray(t.history))&&xl(e.ext)}function Rs(e){return ie(e)&&Hn(e.generation)&&typeof e.has_more=="boolean"&&ek(e.session)&&Array.isArray(e.threads)&&e.threads.every(ZA)&&(e.thread_id===null||Ee(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>XA(t)&&t.thread_id===e.thread_id)}var tk=e=>Rs(e)&&e.messages.length>0;function nk(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let s=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(s.length<=t)return s}return null}var eh={paintable:tk,fit:nk,capturedAt:()=>0},rk=new WeakMap;function th(e,t,n){rk.set(e,{read:(r,s)=>t.read(r,s),write:async(r,s,o)=>{await t.write(r,s,o),await n(r,s)}})}function rh(e){return!!e&&e.available===!0&&e.source==="mirror"&&Array.isArray(e.messages)&&e.messages.length>0&&!!(e.runtime_session_id??e.opencode_session_id)}var Cs=1,sk=12,ok=15e5,ik=3e5,ak=336*60*60*1e3,sh="beeuni.saved-copy";function wl(e){return!!e&&typeof e.then=="function"}function ck(e,t){return wl(e)?e.then(t):t(e)}function lk(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let s=a=>{let c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},o=s(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(o+a>t)break;o+=a,i+=1}for(;i>0;i-=1){let a=s(i);if(a.length<=t)return a}return null}function uk(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var pk={paintable:rh,fit:lk,capturedAt:uk};function dk(e){let t=nh(e,pk),n=nh({...e,namespace:`${e.namespace??sh}.log`},eh),r={...t,remove:async(s,o)=>{await Promise.all([t.remove(s,o),n.remove(s,o)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return th(r,n,t.remove),r}function nh(e,t){let{storage:n,userId:r,maxSessions:s=sk,maxBytes:o=ok,maxEnvelopeBytes:i=ik,maxAgeMs:a=ak,namespace:c=sh,now:p=()=>Date.now()}=e,d=`${c}:${r}:`,g=`${d}index`,m=(b,P)=>`${d}${b}/${P}`,f=b=>{try{let P=n.getItem(b);return wl(P)?P.catch(()=>null):P}catch{return null}},h=b=>{try{let P=n.removeItem(b);wl(P)&&P.catch(()=>{})}catch{}},S=async b=>{try{await n.removeItem(b)}catch{}},E=b=>{if(!b)return[];try{let P=JSON.parse(b);return P?.v===Cs&&Array.isArray(P.entries)?P.entries:[]}catch{return[]}},L=Promise.resolve(),D=b=>{let P=L.then(b,b);return L=P.catch(()=>{}),P},w=async b=>{try{await n.setItem(g,JSON.stringify({v:Cs,entries:b}))}catch{}},y=async()=>E(await f(g)),_=async(b,P)=>{let O=[...b].sort(($,N)=>$.u-N.u),A=O.reduce(($,N)=>$+N.b,0);for(;O.length>s||A>o;){let $=O.findIndex(T=>T.s!==P);if($===-1)break;let[N]=O.splice($,1);A-=N.b,await S(`${d}${N.s}`)}return O},R=b=>{D(async()=>{let P=await y(),O=P.find(A=>A.s===b);O&&(O.u=p(),await w(P))})},v=b=>D(async()=>{await S(`${d}${b}`);let P=await y(),O=P.filter(A=>A.s!==b);O.length!==P.length&&await w(O)});return{keyFor:m,read(b,P){let O=`${b}/${P}`;return ck(f(m(b,P)),A=>{if(!A)return null;let $;try{$=JSON.parse(A)}catch{return h(m(b,P)),v(O),null}return!$||$.v!==Cs||$.user!==r||p()-$.at>a||!t.paintable($.e)?(h(m(b,P)),v(O),null):(R(O),$.e)})},write(b,P,O){let A=`${b}/${P}`;if(!t.paintable(O))return v(A);let $={v:Cs,user:r,at:p(),e:O},N=t.fit($,i);if(N===null)return v(A);let T=t.capturedAt(O);return D(async()=>{let q=await y(),W=q.find($e=>$e.s===A);if(W&&T>0&&W.c>T)return;let H=q.filter($e=>$e.s!==A),In={s:A,b:N.length,u:p(),c:T},Le=await _([...H,In],A),Mn=m(b,P);try{await n.setItem(Mn,N)}catch{let $e=Le.filter(ne=>ne.s!==A).sort((ne,St)=>ne.u-St.u)[0];$e&&(await S(`${d}${$e.s}`),Le=Le.filter(ne=>ne.s!==$e.s));try{await n.setItem(Mn,N)}catch{await S(Mn),Le=Le.filter(ne=>ne.s!==A)}}await w(Le)})},remove(b,P){return v(`${b}/${P}`)},clear(){return D(async()=>{let b=await y();for(let P of b)await S(`${d}${P.s}`);await S(g)})}}}var oh=null;function gk(e){oh=e}function vl(){return oh}var mk=new Set;function ih(e){for(let t of mk)try{t(e)}catch{}}var ah=async(e,t,n,r)=>{let s=new URLSearchParams;n.thread!==void 0&&s.set("thread",n.thread),n.before_seq!==void 0&&s.set("before_seq",String(n.before_seq)),n.limit!==void 0&&s.set("limit",String(n.limit));let o=s.toString(),i=await l.get(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/log${o?`?${o}`:""}`,{showErrors:!1,signal:r});if(!i.success)throw i.error??new Error("Session log request failed");return i.data};function fk(e){let t=typeof e.parent_session_id=="string"?e.parent_session_id:e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var yk=50,ch=200,hk=ch;function lh(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return e?.view&&t.set(e.view,"only"),t.size>0?`?${t}`:""}async function Al(e,t){let n=await l.get(`/projects/${e}/sessions${lh(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Tt(e,t){return u(await l.get(`/projects/${e}/sessions${lh(t)}`))}async function kl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Rl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Cl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Tl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function El(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Il(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function _k(e,t){let n=e.public_url??e.public_path??e.proxy_path??e.public_token??"";if(!n)return"";if(/^https?:\/\//.test(n))return n;if(t)try{return new URL(n,t).toString()}catch{return n}return n}function bk(e,t=new Date){let n=null;for(let r of e)r.resource_type!=="transcript"||r.revoked_at||r.expires_at&&Date.parse(r.expires_at)<=t.getTime()||(!n||Date.parse(r.created_at)>Date.parse(n.created_at))&&(n=r);return n}async function Ml(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function Ol(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Dl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function jl(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Et(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||Vn(n?.session_id),n}async function Ll(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Vn(r.session.session_id),r}async function $l(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Vn(n.session_id),n}async function zn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Bl(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return u(await l.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function Ul(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function Yn(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await l.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Fl(e,t,n={},r){let s;try{s=await ah(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!Rs(s))throw new Error("The response is not a session log page");return s}async function Jn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function Sk(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function Pk(e){if(e)return e==="interrupt"?"transcript":"composer"}async function Qn(e,t,n){let r=n.placement??Pk(n.delivery);return u(await l.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Nl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function ql(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Gl(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Wl(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function Kl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Vl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Hl(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function zl(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return vl()?.remove(e,t),n}async function Yl(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function Jl(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Xn(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Zn(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return ih(t),n}async function Ql(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function xk(e){let t=e.split(`
8
8
  `).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).replace(/^ /,""));if(t.length===0)return null;try{return JSON.parse(t.join(`
9
- `))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function Zc(e,t,n={}){return l(await c.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function eu(e,t,n,r,s={}){let o=await c.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,s);if(!o.ok){let d=await o.json().catch(()=>null);throw new b(d?.error||`Reload failed: HTTP ${o.status}`,{status:o.status,code:d?.code,data:d})}let i=o.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,u="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;u+=a.decode(g,{stream:!0});let m=u.indexOf(`
9
+ `))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function Xl(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function Zl(e,t,n,r,s={}){let o=await l.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,s);if(!o.ok){let d=await o.json().catch(()=>null);throw new x(d?.error||`Reload failed: HTTP ${o.status}`,{status:o.status,code:d?.code,data:d})}let i=o.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,c="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;c+=a.decode(g,{stream:!0});let m=c.indexOf(`
10
10
 
11
- `);for(;m!==-1;){let f=u.slice(0,m);u=u.slice(m+2),m=u.indexOf(`
11
+ `);for(;m!==-1;){let f=c.slice(0,m);c=c.slice(m+2),m=c.indexOf(`
12
12
 
13
- `);let h=wx(f);if(h){if(r(h),h.type==="error")throw new b(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function tu(e,t){return l(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function nu(e,t,n){return l(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function ru(e,t,n){return l(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function su(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function ou(e,t){return l(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function iu(e,t){return l(await c.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function vx(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function au(e){return l(await c.get(`/projects/${e}/triggers`))}async function cu(e,t){return l(await c.post(`/projects/${e}/triggers`,t))}async function uu(e,t,n){return l(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function lu(e,t){return l(await c.delete(`/projects/${e}/triggers/${t}`))}async function pu(e,t){return l(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function du(e,t){return l(await c.post(`/projects/${e}/triggers/${t}/fire`,{}))}async function gu(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return l(await c.get(`/projects/${e}/triggers/event-types?${n}`))}async function mu(e){return l(await c.get(`/projects/${e}/triggers/event-apps`))}var Ue=new Map;function fu(e,t){return`${e}::${t}`}function lf(e,t){Ue.delete(e),Ue.set(e,t)}function pf(e,t){let n=fu(e,t),r=Ue.get(n);return r&&lf(n,r),r}function df(e,t,n){let r=fu(e,t);if(!Ue.has(r)&&Ue.size>=512){let s=Ue.keys().next().value;s!==void 0&&Ue.delete(s)}lf(r,n)}function gf(e,t){Ue.delete(fu(e,t))}function Ax(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function xn(){return Ax(k().backendUrl||"http://localhost:8008/v1")}function mf(){let e=k().sandboxId;return e?`${xn()}/p/${e}/8000`:""}function kx(e,t=8e3){return`${xn()}/p/${e}/${t}`}function Fe(e,t=8e3){return kx(e,t)}function Rx(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var Wr=class extends Error{status;code;terminal;constructor(t,n){super(t),this.name="SessionStartError",this.status=n.status,this.code=n.code,this.terminal=n.terminal}};function Cx(e){return e instanceof Error&&e.name==="SessionStartError"}function Ix(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Wr(s,{status:n,code:r,terminal:!0}):null}function ff(e,t,n){let r=typeof n=="number"?n:n?.waitMs,s=typeof n=="number"?void 0:n?.repositoryMode,o=new URLSearchParams;r&&r>0&&o.set("wait_ms",String(Math.floor(r))),s&&o.set("repository_mode",s),typeof n=="object"&&n?.keepStopped&&o.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&o.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=o.size>0?`?${o.toString()}`:"";return c.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function Le(e,t,n){let r=await ff(e,t,n);if(!r.success||!r.data){let s=Ix(r.error);if(s&&!(s.status===404&&Ac(t)))throw s;return null}return yf(e,t,r.data)}async function yu(e,t,n){let r=await ff(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return yf(e,t,r.data)}function yf(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&df(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Fe(r),sandboxId:r}),n}function Tx(e,t){return["session-start",e,t]}async function hu(e){return l(await c.get(`/projects/${e}/model-defaults`))}async function bu(e,t){return l(await c.put(`/projects/${e}/model-defaults`,t))}async function _u(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return l(await c.delete(`/projects/${e}/model-defaults?${n}`))}async function Ex(e,t){return l(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function hf(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Mx(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Kr(e){let t=e.connectors_required?hf(e.connectors_required):void 0,n=e.connectors_personal?hf(e.connectors_personal):void 0;if(t&&n&&!Mx(t,n))throw new Error("connectors_personal must match connectors_required when both fields are present");let r={...e};return delete r.connectors_personal,(t!==void 0||n!==void 0)&&(r.connectors_required=t??n),r}async function Pu(e,t,n){let r=Kr(n);return l(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function Ox(e,t){let n=l(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Su(n.block):null}}async function Dx(e,t,n){let r=Su(n,!0),s=l(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Su(s.block):null}}function Su(e,t=!1){let n=Kr(e);if(n.workspace===void 0)return n;let r=n.workspace==="branch";if(n.repository_access!==void 0&&n.repository_access!==r)throw new Error("repository_access conflicts with workspace");if(t&&n.workspace==="read"&&n.repository_access===void 0)throw new Error("Legacy read is unavailable. Set repository_access explicitly.");return n.repository_access??=r,delete n.workspace,n}async function jx(e,t,n){return l(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function xu(e,t){return l(await c.put(`/projects/${e}/default-agent`,{agent:t}))}var bf="Use createPerSeatCheckout().";function wu(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function $x(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function Ux(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,isGrandfathered:t.is_grandfathered===!0};let n=e??wu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:$x(r),label:s,sublabel:null,isGrandfathered:!1}}async function _f(e){let t=await c.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?wu():t.data}function Pf(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString();return n?`?${n}`:""}async function vu(e){return _f(`/billing/account-state${Pf(e)}`)}async function Au(e){return _f(`/billing/account-state/minimal${Pf(e)}`)}async function ku(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return l(await c.get(`/billing/transactions${n?`?${n}`:""}`))}async function Ru(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return l(await c.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Cu(){return l(await c.get("/billing/credit-breakdown"))}async function Iu(e){let t=e!=null?`?days=${e}`:"";return l(await c.get(`/billing/usage-history${t}`))}async function Tu(){return l(await c.get("/billing/tier-configurations"))}async function Fx(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Pt(e,`/v1/billing/account-state${t}`)}async function Eu(e){throw F("createCheckoutSession",bf)}async function Mu(e,t){throw F("confirmCheckoutSession",bf)}async function Ou(e,t){return l(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Du(e,t){return l(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function ju(e){return l(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function $u(e,t,n){throw F("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Uu(e){return l(await c.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function Fu(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),l(await c.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function Lu(e){return l(await c.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Bu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return l(await c.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function Lx(e){return l(await c.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Nu(e){return l(await c.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function Bx(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return l(await c.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function Nx(e){return l(await c.post("/billing/create-per-seat-checkout",{account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale}),"Failed to create per-seat checkout")}async function qx(e){return l(await c.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function Gx(e){return l(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function qu(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return l(await c.get(`/usage${n?`?${n}`:""}`))}function Wu(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Hr(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Vr(e){return e.size>0?`?${e}`:""}async function Ku(e={}){let t=new URLSearchParams;return Wu(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Hr(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),l(await c.get(`/usage/session-costs${Vr(t)}`))}async function wn(e,t={}){let n=new URLSearchParams;return Wu(n,t),l(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Vr(n)}`))}async function Wx(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Hr(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),l(await c.get(`/usage/cost-by-project${Vr(t)}`))}async function Kx(e={}){let t=new URLSearchParams;return Wu(t,e),e.sessionId&&t.set("session_id",e.sessionId),Hr(t,e),l(await c.get(`/usage/cost-summary${Vr(t)}`))}function Gu(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let s=t;s.ownerId&&n.set("owner_id",s.ownerId)}Hr(n,t),t.sort&&n.set("sort",t.sort),n.set("format","csv");let r=e==="projects"?"/usage/cost-by-project":"/usage/session-costs";return`${k().backendUrl||""}${r}?${n}`}async function Hx(e,t={}){let n=Gu(e==="projects"?"projects":"sessions",t),r=await ke(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),s=r.headers.get("x-beeuni-row-cap"),o=s!=null?Number(s):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(o)?o:null}}async function Sf(e,t){return l(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function Vx(e){return Sf("slack",e)}function zx(e){return Sf("teams",e)}async function xf(e,t){return l(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function Yx(e){return xf("slack",e)}function Qx(e){return xf("teams",e)}async function Hu(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function Vu(e,t){return l(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var Jx={oauth_available:!1,install_url:null};async function zu(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?Jx:t.data}async function wf(e,t,n){return l(await c.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function Yu(e,t){return wf("slack",e,t)}function Qu(e,t){return wf("teams",e,t)}async function Ju(e){return l(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Xu(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function Zu(e,t){return l(await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function el(e,t){return l(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function tl(e){let t=e.connectionId??e.connection_id??null,n=e.connectorSlug??e.connector_slug??e.connectionSlug??e.connection_slug??"beeuni_email";return{...e,connectionId:t,connectorSlug:n}}var Xx={provider:"agentmail",managed_available:!1};async function nl(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?tl(r.data):null}async function rl(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Xx:t.data}async function sl(e,t){let n=l(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return tl(n)}async function ol(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function il(e,t,n){let r=l(await c.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"beeuni_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return tl(r)}async function Zx(e){return l(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function ew(e,t,n){return l(await c.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function al(e){return l(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function cl(e,t){return l(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function ul(e){return l(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function ll(e,t){return l(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function pl(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return l(await c.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function dl(e,t){return l(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function gl(e,t){return l(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function ml(e,t){return l(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function fl(e,t){return l(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function yl(e,t){return l(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function hl(e,t){return l(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function bl(e){return l(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function _l(e,t){return l(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Pl(e,t){return l(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Sl(e){return l(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function xl(e,t){return l(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function wl(e,t){return l(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function vl(e,t,n,r,s){return l(await c.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function tw(e,t){return l(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function nw(){throw F("getReferralCode")}async function rw(){throw F("refreshReferralCode")}async function sw(e){throw F("validateReferralCode")}async function ow(){throw F("getReferralStats")}async function iw(e={}){throw F("listReferrals")}async function aw(e){throw F("sendReferralEmails")}function O(e){return c.get(e,{showErrors:!1})}function v(e){return l(e,"Unexpected empty response")}async function Al(e){return v(await O(`/accounts/${e}/iam/groups`)).groups}async function kl(e,t){return v(await O(`/accounts/${e}/iam/groups/${t}`))}async function Rl(e,t){return v(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Cl(e,t,n){return v(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Il(e,t){return v(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function Tl(e,t){return v(await O(`/accounts/${e}/iam/groups/${t}/members`)).members}async function El(e,t,n){return v(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function cw(e,t){return v(await O(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Ml(e,t,n){return v(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function uw(e,t){return v(await O(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function lw(e,t){let n=v(await O(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function Be(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function pw(e,t={}){let n=Be({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return v(await O(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function dw(e,t={}){let n=Be({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return v(await O(`/accounts/${e}/iam/policies${n}`)).policies}async function gw(e,t){return v(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function mw(e,t,n){return v(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function fw(e,t){return v(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function yw(e,t){return v(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function hw(e,t){return v(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Ol(e){return v(await O(`/accounts/${e}/iam/roles`)).roles}async function Dl(e){return v(await O(`/accounts/${e}/iam/agent-identities`)).agents}async function jl(e){return v(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function $l(e,t){return v(await O(`/accounts/${e}/iam/roles/${t}/permissions`))}async function bw(e){return v(await O(`/accounts/${e}/iam/actions`)).actions}async function Ul(e,t){return v(await O(`/accounts/${e}/iam/roles/${t}/usage`))}async function Fl(e,t){return v(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Ll(e,t,n){return v(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Bl(e,t,n){return v(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Nl(e,t){return v(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function _w(e,t,n){return v(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function Pw(e){return v(await O(`/accounts/${e}/iam/scim/tokens`)).tokens}async function Sw(e,t){return v(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function xw(e,t){return v(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function ww(e){return v(await O(`/accounts/${e}/iam/mfa-required`))}async function vw(e){return v(await O(`/accounts/${e}/iam/mfa-required/preview`))}async function Aw(e,t){return v(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function kw(e){return v(await O(`/accounts/${e}/iam/session-oversight`))}async function Rw(e,t){return v(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function Cw(e){return v(await O(`/accounts/${e}/iam/sso/provider`)).provider}async function Iw(e,t){return v(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function Tw(e,t){return v(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function Ew(e){return v(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function Mw(e){return v(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function Ow(e){return v(await O(`/accounts/${e}/iam/sso/mappings`)).mappings}async function Dw(e,t){return v(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function jw(e,t){return v(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function $w(e){return v(await O(`/accounts/${e}/iam/session-policy`))}async function Uw(e,t){return v(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function Fw(e){return v(await O(`/accounts/${e}/iam/sessions`)).sessions}async function Lw(e,t){return v(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function Bw(e){return v(await O(`/accounts/${e}/iam/pat-policy`))}async function Nw(e,t){return v(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function qw(e){return v(await O(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function Gw(e,t){return v(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function Ww(e,t){return v(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function Kw(e,t){return v(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function Hw(e){return v(await O(`/accounts/${e}/audit/webhooks`)).webhooks}async function Vw(e,t){return v(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function zw(e,t,n){return v(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Yw(e,t){return v(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Qw(e,t={}){let n=Be({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return v(await O(`/accounts/${e}/audit${n}`))}async function ql(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),v(await O(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Gl(e,t,n){return n.length===0?[]:v(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function Jw(e){return v(await O(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function Xw(e,t){return v(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function Wl(e){return l(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function Kl(e,t){return l(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function Hl(e,t){return l(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function Vl(e,t,n){return l(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function zl(e,t){return l(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Yl(e,t){return l(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function Zw(e){return Be({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function Ql(e,t){return l(await O(`/accounts/${e}/iam/assignments${Zw(t)}`)).assignments}async function Jl(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),l(await c.post(`/accounts/${e}/iam/assignments`,n))}async function Xl(e,t){return l(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function Zl(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return l(await O(`/accounts/${e}/iam/permissions${n}`)).permissions}async function ev(){let e=await c.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:l(e,"Failed to load account deletion status")}async function tv(e="User requested deletion"){return l(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function nv(){return l(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function rv(){return l(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function sv(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function ov(){return c.get("/admin/api/provider-distribution").then(e=>l(e))}function iv(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>l(t))}function av(e){return c.put("/admin/api/provider-distribution",e).then(t=>l(t))}function cv(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>l(t))}function uv(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>l(n))}function lv(){return c.get("/admin/api/provider-fallback").then(e=>l(e))}function pv(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>l(t))}function dv(){return c.get("/admin/api/boot-modes").then(e=>l(e))}function gv(e){return c.put("/admin/api/boot-modes",e).then(t=>l(t))}var vf="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function mv(e){throw F("getGoogleAuthUrl",vf)}async function fv(e,t){throw F("convertPresentationToGoogleSlides",vf)}async function ep(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind);let r=n.toString();return l(await c.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function tp(e,t){return l(await c.get(`/projects/${e}/review/items/${t}`))}async function np(e,t){return l(await c.post(`/projects/${e}/review/items`,t))}async function rp(e,t,n){return l(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function sp(e,t){return l(await c.post(`/projects/${e}/review/bulk`,t))}var op="call:";function yv(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(op)&&e.length>op.length?{type:"connector_call",executionId:e.slice(op.length)}:{type:"review_item",reviewItemId:e}}function kf(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function hv(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[kf(n.status)]+=1;return t}function bv(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function ip(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function ap(e){let t=e.indexOf(".");return t<=0?ip(e):`(${ip(e.slice(0,t))}) ${ip(e.slice(t+1))}`}function _v(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var zr=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,he=e=>Array.isArray(e)?e:void 0,Af=e=>typeof e=="number"?e:0,Pv=e=>e.split(`
14
- `).map(t=>t.trim()).filter(Boolean);function Sv(e,t){let n=zr(e.advanced),r=U(e.description),s=he(e.whatChanged)??(r?Pv(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:U(e.impact)??"",verification:he(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:he(e.conflicts),requestedChanges:he(e.requested_changes)??[],advanced:{headRef:U(n.headRef)??U(e.head_ref)??"",baseRef:U(n.baseRef)??U(e.base_ref)??"",headSha:U(n.headSha)??U(e.head_sha)??U(e.head_commit_sha)??"",baseSha:U(n.baseSha)??U(e.base_sha)??"",additions:Af(n.additions),deletions:Af(n.deletions),files:he(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function xv(e,t){let n=he(e.actions);if(n)return{actions:n.map((u,p)=>({id:U(u.id)??`${t.review_item_id}-${p}`,title:U(u.title)??"Action",connector:U(u.connector)??"",action:U(u.action)??"",consequence:U(u.consequence)??"",risk:U(u.risk)??t.risk,icon:U(u.icon)??"generic",argsPreview:he(u.argsPreview)??[],policySource:U(u.policySource)??"Requires approval",decided:u.decided==="approved"||u.decided==="denied"?u.decided:void 0}))};let r=U(e.action_path)??"",{connector:s,action:o}=_v(r),i=zr(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?ap(r):t.title||"Run action",connector:s,action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([u,p])=>({key:u,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,approvalContext:U(e.approval_context),connectorRisk:U(e.risk)??null,policySource:"Requires approval"}]}}function wv(e,t){return{artifactKind:U(e.artifactKind)??"document",artifactLabel:U(e.artifactLabel)??"Output",previewUrl:U(e.previewUrl)??U(e.preview_url),preview:U(e.preview),files:he(e.files),note:U(e.note)??t.summary??""}}function vv(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:he(e.options)??[]}}function Av(e,t){return{note:U(e.note)??t.summary??"",children:he(e.children)??[]}}function kv(e){let t=zr(e.detail);switch(e.kind){case"change":return Sv(t,e);case"approval":return xv(t,e);case"output":return wv(t,e);case"decision":return vv(t,e);case"batch":return Av(t,e)}}function Rv(e,t){let n=typeof e.number=="number"?e.number:void 0,r=U(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function Cv(e,t={}){let n=zr(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?U(n.action_path):void 0,i=e.kind==="change"?Rv(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:o?ap(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:kv(e)}}async function cp(e){return l(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function up(e){return l(await c.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function lp(e,t){let n=await c.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var Yr=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Rf(e,t=""){return`${xn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Cf(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let s=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new Yr(s,t.status)}return r}async function Iv(e){return Cf(Rf(e))}async function Tv(e){return Cf(Rf(e,"/messages"))}async function pp(e,t){return l(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function dp(e,t,n){return l(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Qr(e,t,n,r){return l(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Jr(e,t,n){return l(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var Ev=4;async function If(e,t){let n=new Array(e.length),r=0,s=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(Ev,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let u=n[a];u.ok?o.done.push(i):o.failed.push({reminder:i,error:u.error})}),o}function gp(e,t,n){return If(t,r=>Qr(e,r.sessionId,r.reminderId,n))}function mp(e,t){return If(t,n=>Jr(e,n.sessionId,n.reminderId))}async function fp(e){return l(await c.get(`/projects/${e}/reminders`))}async function yp(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return l(await c.get(`/accounts/tokens${r}`))}async function hp(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return l(await c.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function bp(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return l(await c.delete(`/accounts/tokens/${e}${n}`))}async function _p(){return l(await c.get("/oauth/grants")).grants}async function Pp(e){return l(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function Mv(){return l(await c.get("/accounts/me/devices")).devices}async function Ov(e){return l(await c.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function Sp(e){return l(await c.get(`/projects/${e}/cli-token`))}async function xp(e,t){return l(await c.post(`/projects/${e}/cli-token`,t??{}))}async function wp(e,t){return l(await c.delete(`/projects/${e}/cli-token/${t}`))}function kt(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,s]of Object.entries(e))n.includes(` ${r} `)&&s!=null&&s!==""&&t.set(r,String(s));return t}function vp(e={}){return{format:e.format,action:e.action,actor:e.actor,actor_type:e.actorType,project_id:e.projectId,session_id:e.sessionId,source:e.source,credential_kind:e.credentialKind,phase:e.phase,outcome:e.outcome,resource_type:e.resourceType,request_id:e.requestId,correlation_id:e.correlationId,since:e.since,until:e.until,q:e.q,cursor:e.cursor,limit:e.limit}}async function Ap(e,t){let n=kt(vp(t)).toString();return l(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function kp(e,t){let n=kt(vp({...t,projectId:void 0})).toString();return l(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function Rp(e,t){let n=kt(vp(t)).toString();return l(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Cp(e){return l(await c.get(`/accounts/${e}/audit/webhooks`))}async function Ip(e,t){return l(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function Tp(e,t,n){return l(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Ep(e,t){return l(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Mp(e,t){return l(await c.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function Op(e,t){return l(await c.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function Dv(e){return l(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function Dp(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return l(await c.get(`/marketplace/items${n}`))}async function jp(){return l(await c.get("/marketplace/marketplaces"))}async function $p(){return l(await c.get("/marketplace/marketplaces/featured"))}async function Up(e){return l(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Fp(e,t){return l(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Lp(){return l(await c.get("/marketplace/sources"))}async function Bp(e){return l(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Np(e){return l(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function jv(e,t){return l(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function $v(e){throw F("getTemplate")}async function Uv(e,t){throw F("installTemplate")}async function qp(e){return l(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Gp(e,t){return l(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Xr(e,t){return l(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Wp(e,t,n){return l(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Kp(e,t){return l(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Hp(e,t){return l(await c.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function Vp(e,t){let n=await Xr(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=l(await c.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),s=new TextEncoder().encode(JSON.stringify(r)),o="";for(let i of s)o+=String.fromCharCode(i);return{BEEUNI_AUTH_ISSUER:n.auth.issuer,BEEUNI_AUTH_AUDIENCE:n.auth.audience,BEEUNI_AUTH_JWKS:`data:application/json;base64,${btoa(o)}`}}async function zp(e,t){return l(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Yp(e,t){return l(await c.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function Qp(e,t,n){return l(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Jp(e,t){return l(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Zr(e,t){return l(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function es(e,t,n){return l(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function Fv(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function Lv(e){let t=Uint8Array.from(e),n=await globalThis.crypto.subtle.digest("SHA-256",t.buffer);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}async function Xp(e,t,n={}){let r=await Fv(t),s=n.mediaType??"application/gzip",o=await Zr(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),es(e,o.artifact.artifact_id,{sha256:await Lv(r),size_bytes:r.byteLength})}async function Zp(e,t,n){return l(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function ed(e,t){return l(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function td(e,t,n){return l(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function nd(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return l(await c.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function rd(e,t){return l(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function sd(e,t){return l(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function od(e,t,n){return l(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function id(e,t,n){return l(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var ae=(e,t)=>`/projects/${e}/apps/${t}`;async function ad(e,t){return l(await c.get(`${ae(e,t)}/machines`),"Failed to list machines").machines}async function cd(e,t,n,r){return l(await c.post(`${ae(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var ud=(e,t,n)=>cd(e,t,n,"start"),ld=(e,t,n)=>cd(e,t,n,"stop"),pd=(e,t,n)=>cd(e,t,n,"restart");async function dd(e,t,n){return l(await c.delete(`${ae(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function gd(e,t,n){return l(await c.put(`${ae(e,t)}/scale`,{count:n}),"Failed to scale the App")}async function md(e,t,n){return l(await c.post(`${ae(e,t)}/exec`,n),"Failed to run the command")}async function fd(e,t){return l(await c.get(`${ae(e,t)}/volumes`),"Failed to list volumes").volumes}async function yd(e,t,n){return l(await c.post(`${ae(e,t)}/volumes`,n),"Failed to create the volume")}async function hd(e,t,n,r){return l(await c.patch(`${ae(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function bd(e,t,n,r){l(await c.delete(`${ae(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function _d(e,t,n){return l(await c.get(`${ae(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Pd(e,t,n){return l(await c.post(`${ae(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Sd(e,t,n,r){return l(await c.post(`${ae(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function xd(e,t,n,r){return l(await c.post(`${ae(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function ee(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var re=e=>`/drives/${encodeURIComponent(e)}`;async function Bv(e){let t=l(await c.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new b("Files not found",{status:404});return t[0]}async function Nv(e,t){return l(await c.get(`${re(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function qv(e,t){return l(await c.put(`${re(e)}/access`,t),"Failed to share folder")}async function Gv(e,t){let n=l(await c.delete(`${re(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function Wv(e){return l(await c.get(`${re(e)}/principals`),"Failed to load people")}async function Kv(e){return l(await c.get(`${re(e)}/conflicts`),"Failed to load conflicts").conflicts}async function Hv(e,t){l(await c.post(`${re(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function Vv(e,t="/"){return(await Tf(e,t)).entries}async function Tf(e,t="/"){return l(await c.get(`${re(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function wd(e,t,n){let r=ee(k().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${re(e)}/files/content?${new URLSearchParams(s)}`}async function zv(e,t,n){let r=await E(wd(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new b(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function Yv(e,t,n){let r=await E(wd(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new b(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function Qv(e,t,n,r){return l(await c.putRaw(`${re(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function Jv(e,t){return l(await c.post(`${re(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function Xv(e,t,n){return l(await c.post(`${re(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function Zv(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),l(await c.delete(`${re(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function eA(e){return l(await c.get(`${re(e)}/versions`),"Failed to load versions").versions}async function tA(e,t){l(await c.post(`${re(e)}/restore`,{versionId:t}),"Failed to restore version")}var nA=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function rA(e,t){return(await Ef(e,t)).drives}async function Ef(e,t){return l(await c.get(nA(e,t)),"Failed to load session files")}async function vd(e){return l(await c.post("/notifications/device-token",e))}async function Ad(e,t){return l(await c.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var sA=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered"];async function kd(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return l(await c.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function Rd(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return l(await c.post("/notifications/read",t))}var oA={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1}};async function Cd(){return l(await c.get("/notifications/preferences",{showErrors:!1}))}async function Id(e){return l(await c.put("/notifications/preferences",e))}async function Td(){return l(await c.get("/notifications/web-push/key",{showErrors:!1}))}async function Ed(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return l(await c.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function Md(e,t){return l(await c.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function vn(e){return l(await c.get(`/projects/${e}/model-access`))}async function An(e,t){return l(await c.put(`/projects/${e}/model-access`,t))}var kn=e=>`/provider-connections/${encodeURIComponent(e)}`,Mf=e=>`/projects/${encodeURIComponent(e)}/personal-providers`;async function Od(){return l(await c.get("/provider-connections"))}async function Dd(e,t,n={}){return l(await c.put(kn(e),{api_key:t,...n}))}async function jd(e,t){let n=t?`${kn(e)}/connections/${encodeURIComponent(t)}`:kn(e);return l(await c.delete(n))}async function $d(e,t={}){return l(await c.post(`${kn(e)}/start`,t))}async function Ud(e,t){return l(await c.post(`${kn(e)}/poll`,{flow_id:t}))}async function Fd(e){return l(await c.get(Mf(e)))}async function Ld(e,t,n,r={}){return l(await c.put(`${Mf(e)}/${encodeURIComponent(t)}`,{enabled:n,...r}))}async function iA(e){return l(await c.get(`/projects/${e}/starter-suggestions`))}function aA(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:o,previewIsLinkOnly:i}=e;return t||n?!1:s?o&&!i:r==="error"}function Bd(e){return typeof e=="string"&&e.trim().length>0}function Of(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Bd(t)||Bd(n)||Bd(r)}function cA(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function Rn(e){if(!e)return!0;let t=cA(e.items);return t?!t.some(Of):!Of(e)}function le(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function uA(e){return le(e)==="bash"}function lA(e){let t=le(e);return t==="question"||t==="ask"}function pA(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Df=new Set(["show","show_user"]);function Nd(e){return Df.has(le(e))}function dA(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function qd(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||ts(e))}function ts(e){let t=le(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:Rn(e.state?.input)}var jf=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Gd(e){return jf.has(le(e))}var gA=50*1024*1024,Wd="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",mA=new RegExp(`^beeuni-attachment://(${Wd})/(${Wd})/(${Wd})$`);function Hd(e){if(typeof e!="string")return null;let t=mA.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function fA(e){return Hd(e)!==null}var Kd=new WeakMap;async function Vd(e,t,n,r={}){if(n.size>gA)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:Kd.get(n)?.get(s);if(o?.promise)return o.promise;let i=o??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let u=Kd.get(n)??new Map;u.set(s,i),Kd.set(n,u)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=c.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(l).catch(u=>{throw i.promise=void 0,u}),i.promise}async function zd(e,t){let n=Hd(e);if(!n)throw new Error("Invalid attachment reference");let r=k().backendUrl.replace(/\/$/,""),s=await E(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new b("Could not load attachment",{status:s.status});return s.blob()}var yA=new Set(["show","show_user"]);function hA(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return t;let i=e.indexOf("</file>",o+1);if(i===-1)return t;t.push(e.slice(s,o).trimStart()),n=i+7}}var Rt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Cn=e=>typeof e=="string"&&e.length>0?e:null,$f=e=>typeof e=="string"?Cn(e.split("/").pop()):null;function ns(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function bA(e){if(Array.isArray(e))return e;if(typeof e!="string"||!e.trim())return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function _A(e,t){for(let n of hA(e))t(ns(n,"attachment"),ns(n,"filename")??$f(ns(n,"path")),ns(n,"mime"))}function PA(e,t){for(let n of[e,...bA(e.items)])Rt(n)&&t(n.attachment,$f(n.path),null)}function SA(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!Rt(r)||!Rt(r.info)||!Array.isArray(r.parts))continue;let s=Cn(r.info.id);if(!s)continue;let o=Cn(r.info.role)??"unknown",i=(a,u,p)=>{let d=Hd(a);!d||n.has(a)||(n.add(a),t.push({url:a,attachment_id:d.attachmentId,filename:u,mime:p,message_id:s,role:o}))};for(let a of r.parts)Rt(a)&&(a.type==="file"?i(a.url,Cn(a.filename),Cn(a.mime)):a.type==="text"&&typeof a.text=="string"?_A(a.text,i):a.type==="tool"&&typeof a.tool=="string"&&yA.has(le(a.tool))&&Rt(a.state)&&Rt(a.state.input)&&PA(a.state.input,i))}return t}function Ne(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function xA(e,t){if(e==null)return t;let n=e.trim().toLowerCase();return["1","true","yes","y","on"].includes(n)?!0:["0","false","no","n","off"].includes(n)?!1:t}function wA(e){if(e==null)return;let t=e.trim().toLowerCase();if(["1","true","yes","y","on"].includes(t))return!0;if(["0","false","no","n","off"].includes(t))return!1}function Yd(e,t,n){return e!==void 0?e:xA(Ne(t),n)}var Qd={get disableMobileAdvertising(){return Yd(k().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Yd(k().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Yd(k().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var vA=new Set(["project-manager"]);function rs(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Qd.enableProjects||!vA.has(e.name)}function AA(e){let t=e.agents.filter(rs),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function Uf(){return{projects:{list:st,listForAccount:Yo,get:sn,detail:on,create:Zo,createRepo:ei,provision:ti,update:un,archive:ln,llmCatalog:an,modelPicker:cn,modelAccess:vn,setModelAccess:An,sandboxHealth:dn,sandboxTemplates:Ka,sessions:it,createSession:at},github:{linkRepository:ai,replaceProjectRepository:ci,getInstallation:ui,listInstallations:li,listLinkableInstallations:pi,listRepositories:di,listRepositoryBranches:gi,linkInstallation:fi,saveInstallation:mi,deleteInstallation:hi,storeUserToken:yi},gitBackend:{get:bi,repositories:_i},connectStatus:Fa,marketplace:{items:o=>Dp(o),item:o=>Up(o),itemFile:(o,i)=>Fp(o,i),marketplaces:()=>jp(),featured:()=>$p(),sources:{list:()=>Lp(),add:o=>Bp(o),remove:o=>Np(o)}}}}function Ff(){return{billing:{accountState:vu,accountStateMinimal:Au,transactions:ku,transactionsSummary:Ru,creditBreakdown:Cu,usageHistory:Iu,usageRollup:qu,sessionCosts:{list:Ku,get:wn},tierConfigurations:Tu,checkout:{createSession:n=>Eu(n),confirmSession:(n,r)=>Mu(n,r)},subscription:{createPortalSession:(n,r)=>Ou(n,r),cancel:(n,r)=>Du(n,r),reactivate:n=>ju(n),scheduleDowngrade:(n,r,s)=>$u(n,r,s),cancelScheduledChange:n=>Uu(n),prorationPreview:(n,r)=>Fu(n,r)},credits:{purchase:n=>Lu(n),autoTopupSettings:n=>Bu(n),configureAutoTopup:n=>Nu(n)}},sandboxShares:{list:cp,create:up,revoke:lp}}}var Te={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",BEEUNI_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function qe(){let e=Ne("BACKEND_URL")||k().backendUrl;return e||"http://localhost:8008/v1"}function Tn(e){let t=ee(e);return t.endsWith("/v1")?t:`${t}/v1`}function In(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=In(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return In(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function kA(e){return e==="running"||e==="active"?"active":e==="queued"||e==="branching"||e==="provisioning"?"provisioning":e==="failed"||e==="error"?"error":e==="stopped"||e==="completed"||e==="archived"?"stopped":e||"unknown"}function Jd(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"daytona",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${qe()}/p/${n.external_id}/${Te.BEEUNI_MASTER}`:""),status:kA(n?.status||t.status),metadata:{...t.metadata??{},project_id:e.project_id,session_id:t.session_id,project_name:e.name,runtime_status:n?.status,error:t.error},created_at:n?.created_at||t.created_at,updated_at:n?.updated_at||t.updated_at}}async function Xd(){let e=await st(),t=[];for(let n of e){let r=await it(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Jd(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function ct(e){let t=await Xd();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}var Ct=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function J(e,t,n){let r=n?.fetch??k().fetch??((p,d)=>fetch(p,d)),s=ee(n?.backendUrl??k().backendUrl??"");if(!s)throw new Ct("not_configured","backendUrl is not configured (configureBeeuni / createBeeuni first)",0);let o={accept:"application/json"};t.body!==void 0&&(o["content-type"]="application/json"),t.bearer&&(o.authorization=`Bearer ${t.bearer}`);let i=await r(`${Tn(s)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:o,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),u=null;try{u=a?JSON.parse(a):null}catch{u=a}if(!i.ok){let p=u&&typeof u=="object"?u:{};throw new Ct(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return u}function ss(e,t){return J("/auth/signup",{body:e},t)}function os(e,t){return J("/auth/sign-in/password",{body:e},t)}function is(e,t){return J("/auth/sign-in/magic-link",{body:e},t)}function as(e,t){return J("/auth/verify-otp",{body:e},t)}function cs(e,t){return J("/auth/sign-in/oauth",{body:e},t)}function us(e,t){return J("/auth/oauth/exchange",{body:e},t)}function It(e,t){return J("/auth/refresh",{body:e},t)}function ls(e,t){return J("/auth/password/reset",{body:e},t)}function ps(e,t,n){return J("/auth/password/update",{body:e,bearer:t},n)}function ds(e,t){return J("/auth/user",{bearer:e},t)}function gs(e,t,n){return J("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function ms(e,t){return J("/auth/sign-in/sso",{body:e},t)}var fs={enroll:(e,t,n)=>J("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>J(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>J(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>J(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function ys(e,t={},n){return J("/auth/sign-out",{body:t,bearer:e},n)}function hs(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,u=0,p=new Set,d=x=>(x.expires_at??0)*1e3,g=x=>d(x)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let x of[...p])try{x(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let x=u,D=(async()=>{let j=await e.storage.get();if(x===u&&j)try{let L=JSON.parse(j);L.session?.access_token&&L.session?.refresh_token&&(r=L.session,s=L.user??null)}catch{r=null}return o=!0,r})();i=D,D.then(()=>{i===D&&(i=null)},()=>{i===D&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let x=r.refresh_token,D=u,j=It({refresh_token:x},e.request).then(async L=>(D!==u||(r=L.session,L.user&&(s=L.user),await m()),r)).catch(async L=>{if(D!==u)return r;let y=L&&typeof L=="object"&&"status"in L?L.status:0;if(y>=400&&y<500)return r=null,s=null,await m(),null;throw L}).finally(()=>{a===j&&(a=null)});a=j}return a}return{subscribe(x){return p.add(x),()=>{p.delete(x)}},current:()=>r,user:()=>s,load:f,async set(x,D){await f(),u+=1,a=null,r=x,D!==void 0&&(s=D),x||(s=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){u+=1,a=null,r=null,s=null,o=!0,await m()}}}function Lf(){return{list:Ro,get:Io,create:Co,secretResources:{list:Ji,create:Xi,rotate:Zi,retry:ea,remove:ta,grant:na,revoke:ra,setAccess:sa},updateName:To,branding:{get:Eo,update:Mo,uploadAsset:Oo,removeAsset:Do,reset:jo},leave:Vo,members:$o,invite:Uo,removeMember:Ko,updateMemberRole:Ho,invites:Fo,cancelInvite:Lo,resendInvite:Bo,tokens:{list:yp,create:hp,revoke:bp},connectedApps:{list:_p,revoke:Pp},audit:{log:Ap,export:Rp,webhooks:{list:Cp,create:Ip,update:Tp,remove:Ep}}}}function Bf(){return{assignments:{list:Ql,create:Jl,revoke:Xl},permissions:{list:Zl,forRole:$l},roles:{list:Ol,create:Fl,update:Ll,setPermissions:Bl,remove:Nl,usage:Ul},groups:{list:Al,get:kl,create:Rl,update:Cl,remove:Il,members:{list:Tl,add:El,remove:Ml}},agentIdentities:Dl,oauthClients:{list:Wl,get:Kl,create:Hl,update:Vl,rotateSecret:zl,remove:Yl},can:ql,canBatch:Gl}}function Nf(){let e={signUp:ss,signInWithPassword:os,sendMagicLink:is,verifyOtp:as,signInWithProvider:cs,exchangeCode:us,refresh:It,resetPassword:ls,updatePassword:ps,updateUserMetadata:gs,signInWithSso:ms,mfa:fs,user:ds,signOut:ys,session:hs},t=Lf(),n=Bf();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:No,describe:qo,accept:Go,decline:Wo}}}var En=new Map,Zd=new Map;function eg(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function qf(e){return En.get(eg(e))??null}function Gf(){return[...En.values()].filter(e=>typeof e=="string")}function Wf(e){return En.has(eg(e))}async function Ge(e){let t=eg(e),n=En.get(t);if(n!==void 0)return n;let r=Zd.get(t);if(r)return r;let s=(async()=>{try{let o=await c.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let i=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return En.set(t,i),i}catch{return null}finally{Zd.delete(t)}})();return Zd.set(t,s),s}function Kf(e){let{apiBaseUrl:t}=e;return Wf(t)||Ge(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:qf(t)}}function Hf(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new b(`Beeuni SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/beeuni" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let s=k().backendUrl??e.backendUrl,o=80,i=t(s);return i&&(o=i.port?Number(i.port):i.protocol==="https:"?443:80),Kf({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function Vf(e,t){let n=null;async function r(){n||(n=bn(e,t,{showErrors:!1}).then(s=>{let o=su(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,u=s.agent_name?.trim()||void 0;return{model:a,agent:u}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var Mn=new Map;function zf(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var ut=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};var Tt={url:null,sandboxId:null,dbSandboxId:null,version:0},CA=new Set;function Yf(e,t=null,n=null){if(!(Tt.url===e&&Tt.sandboxId===t&&Tt.dbSandboxId===n)){Tt={url:e,sandboxId:t,dbSandboxId:n,version:Tt.version+1};for(let r of CA)r()}}function Qf(){return Tt.url}function Jf(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await Le(e,t,Math.min(3e4,o()));for(;Date.now()<s&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,o()))),i=await Le(e,t,Math.min(3e4,o()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new b(zf(i),{code:"RUNTIME_UNAVAILABLE"});let u=i.sandbox.external_id;if(!u)throw new b("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Fe(u);return Yf(p,u),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:u}}return n}function Xf(e,t,n){let r=null;function s(){if(r)return r;let p=pf(e,t);return p&&(r=p),r}let o=Jf(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=Ge(k().backendUrl??n.backendUrl).catch(()=>null),f=`${e}
15
- ${t}`,h=Mn.get(f);if(h)return r=await h,await m,r;let x=o(g);Mn.set(f,x);try{return r=await x,await m,r}finally{Mn.get(f)===x&&Mn.delete(f)}}function a(p){let d=s();if(!d)throw new ut(p);return d}function u(){r=null,gf(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:u}}var G=["directory","workspace"],Zf=["messageID","model","agent","noReply","tools","format","system","variant","parts"],R=(e,t,n=G,r=[],s)=>({method:e,path:t,query:n,body:r,bodyParam:s}),IA={"session.list":R("GET","/session",[...G,"scope","path","roots","start","search","limit"]),"session.get":R("GET","/session/{sessionID}"),"session.create":R("POST","/session",G,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":R("DELETE","/session/{sessionID}"),"session.update":R("PATCH","/session/{sessionID}",G,["title","metadata","permission","time"]),"session.status":R("GET","/session/status"),"session.messages":R("GET","/session/{sessionID}/message",[...G,"limit","before"]),"session.prompt":R("POST","/session/{sessionID}/message",G,Zf),"session.promptAsync":R("POST","/session/{sessionID}/prompt_async",G,Zf),"session.abort":R("POST","/session/{sessionID}/abort"),"session.revert":R("POST","/session/{sessionID}/revert",G,["messageID","partID"]),"session.unrevert":R("POST","/session/{sessionID}/unrevert"),"session.summarize":R("POST","/session/{sessionID}/summarize",G,["providerID","modelID","auto"]),"session.command":R("POST","/session/{sessionID}/command",G,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":R("POST","/session/{sessionID}/share"),"session.unshare":R("DELETE","/session/{sessionID}/share"),"session.fork":R("POST","/session/{sessionID}/fork",G,["messageID"]),"session.diff":R("GET","/session/{sessionID}/diff",[...G,"messageID"]),"session.todo":R("GET","/session/{sessionID}/todo"),"permission.list":R("GET","/permission"),"permission.reply":R("POST","/permission/{requestID}/reply",G,["reply","message"]),"question.list":R("GET","/question"),"question.reply":R("POST","/question/{requestID}/reply",G,["answers"]),"question.reject":R("POST","/question/{requestID}/reject"),"part.update":R("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",G,[],"part"),"part.delete":R("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":R("GET","/file",[...G,"path"]),"file.read":R("GET","/file/content",[...G,"path"]),"find.files":R("GET","/find/file",[...G,"query","dirs","type","limit"]),"vcs.diff":R("GET","/vcs/diff",[...G,"mode","context"]),"global.health":R("GET","/global/health",[]),"global.dispose":R("POST","/global/dispose",[]),"global.config.get":R("GET","/global/config",[]),"global.config.update":R("PATCH","/global/config",[],[],"config"),"provider.list":R("GET","/provider"),"provider.auth":R("GET","/provider/auth"),"provider.oauth.authorize":R("POST","/provider/{providerID}/oauth/authorize",G,["method","inputs"]),"provider.oauth.callback":R("POST","/provider/{providerID}/oauth/callback",G,["method","code"]),"auth.set":R("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":R("GET","/agent"),"app.skills":R("GET","/skill"),"app.log":R("POST","/log",G,["service","level","message","extra"]),"command.list":R("GET","/command"),"tool.ids":R("GET","/experimental/tool/ids"),"tool.list":R("GET","/experimental/tool",[...G,"provider","model"]),"mcp.status":R("GET","/mcp"),"mcp.add":R("POST","/mcp",G,["name","config"]),"mcp.connect":R("POST","/mcp/{name}/connect"),"mcp.disconnect":R("POST","/mcp/{name}/disconnect"),"mcp.auth.start":R("POST","/mcp/{name}/auth"),"mcp.auth.callback":R("POST","/mcp/{name}/auth/callback",G,["code"]),"mcp.auth.remove":R("DELETE","/mcp/{name}/auth"),"project.list":R("GET","/project"),"project.current":R("GET","/project/current"),"path.get":R("GET","/path")};function TA(e,t){let n=[];for(let r of e.query){let s=t[r];s!=null&&n.push(`${r}=${encodeURIComponent(String(s))}`)}return n.length?`?${n.join("&")}`:""}function EA(e,t,n={},r={}){let s=IA[t],o=s.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(s.bodyParam)i=n[s.bodyParam],a=i!==void 0;else for(let p of s.body)p in n&&(i={...i,[p]:n[p]},a=!0);let u=new Headers(r.headers);return a&&u.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${o}${TA(s,n)}`,{method:s.method,headers:u,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function MA(e){if(!e)return"stream";let t=e.split(";")[0]?.trim()??"";return t.startsWith("application/json")||t.endsWith("+json")?"json":t==="multipart/form-data"?"formData":["application/","audio/","image/","video/"].some(n=>t.startsWith(n))?"blob":t.startsWith("text/")?"text":"json"}async function OA(e,t){let n=e.fetch??globalThis.fetch,r;try{r=await n(t)}catch(i){return{error:i||{},request:t,response:void 0}}if(r.headers.get("content-type")==="text/html")throw new Error("The session runtime does not serve this request (it answered text/html)");if(r.ok){let i=MA(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let s=await r.text(),o=s;try{o=JSON.parse(s)}catch{}return{error:o||{},request:t,response:r}}function tg(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let s=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!s.ok)throw Object.assign(new Error(`SSE failed: ${s.status} ${s.statusText}`),{status:s.status});if(!s.body)throw new Error("No body in SSE response");let o=s.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{o.cancel()}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:u,value:p}=await o.read();if(u)break;a=(a+p).replace(/\r\n/g,`
13
+ `);let h=xk(f);if(h){if(r(h),h.type==="error")throw new x(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function eu(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function tu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function nu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function er(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function ru(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function su(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function wk(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function ou(e){return u(await l.get(`/projects/${e}/triggers`))}async function iu(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function au(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function cu(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function lu(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function uu(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}async function pu(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await l.get(`/projects/${e}/triggers/event-types?${n}`))}async function du(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var ot=new Map;function gu(e,t){return`${e}::${t}`}function uh(e,t){ot.delete(e),ot.set(e,t)}function ph(e,t){let n=gu(e,t),r=ot.get(n);return r&&uh(n,r),r}function Ts(e,t,n){let r=gu(e,t);if(!ot.has(r)&&ot.size>=512){let s=ot.keys().next().value;s!==void 0&&ot.delete(s)}uh(r,n)}function dh(e,t){ot.delete(gu(e,t))}function vk(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function tr(){return vk(C().backendUrl||"http://localhost:8008/v1")}function gh(){let e=C().sandboxId;return e?`${tr()}/p/${e}/8000`:""}function Ak(e,t=8e3){return`${tr()}/p/${e}/${t}`}function Ie(e,t=8e3){return Ak(e,t)}function mu(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var Es=class extends Error{status;code;terminal;constructor(t,n){super(t),this.name="SessionStartError",this.status=n.status,this.code=n.code,this.terminal=n.terminal}};function kk(e){return e instanceof Error&&e.name==="SessionStartError"}function Rk(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Es(s,{status:n,code:r,terminal:!0}):null}function mh(e,t,n){let r=typeof n=="number"?n:n?.waitMs,s=typeof n=="number"?void 0:n?.repositoryMode,o=new URLSearchParams;r&&r>0&&o.set("wait_ms",String(Math.floor(r))),s&&o.set("repository_mode",s),typeof n=="object"&&n?.keepStopped&&o.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&o.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=o.size>0?`?${o.toString()}`:"";return l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function it(e,t,n){let r=await mh(e,t,n);if(!r.success||!r.data){let s=Rk(r.error);if(s&&!(s.status===404&&Pl(t)))throw s;return null}return fh(e,t,r.data)}async function fu(e,t,n){let r=await mh(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return fh(e,t,r.data)}function fh(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Ts(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Ie(r),sandboxId:r}),n}function Ck(e,t){return["session-start",e,t]}async function yu(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function hu(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function _u(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await l.delete(`/projects/${e}/model-defaults?${n}`))}async function Tk(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function yh(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Ek(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Is(e){let t=e.connectors_required?yh(e.connectors_required):void 0,n=e.connectors_personal?yh(e.connectors_personal):void 0;if(t&&n&&!Ek(t,n))throw new Error("connectors_personal must match connectors_required when both fields are present");let r={...e};return delete r.connectors_personal,(t!==void 0||n!==void 0)&&(r.connectors_required=t??n),r}async function bu(e,t,n){let r=Is(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function Ik(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Su(n.block):null}}async function Mk(e,t,n){let r=Su(n,!0),s=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Su(s.block):null}}function Su(e,t=!1){let n=Is(e);if(n.workspace===void 0)return n;let r=n.workspace==="branch";if(n.repository_access!==void 0&&n.repository_access!==r)throw new Error("repository_access conflicts with workspace");if(t&&n.workspace==="read"&&n.repository_access===void 0)throw new Error("Legacy read is unavailable. Set repository_access explicitly.");return n.repository_access??=r,delete n.workspace,n}async function Ok(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Pu(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var hh="Use createPerSeatCheckout().";function xu(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function Dk(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function jk(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,isGrandfathered:t.is_grandfathered===!0};let n=e??xu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:Dk(r),label:s,sublabel:null,isGrandfathered:!1}}async function _h(e){let t=await l.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?xu():t.data}function bh(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString();return n?`?${n}`:""}async function wu(e){return _h(`/billing/account-state${bh(e)}`)}async function vu(e){return _h(`/billing/account-state/minimal${bh(e)}`)}async function Au(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await l.get(`/billing/transactions${n?`?${n}`:""}`))}async function ku(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await l.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Ru(){return u(await l.get("/billing/credit-breakdown"))}async function Cu(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function Tu(){return u(await l.get("/billing/tier-configurations"))}async function Lk(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Wt(e,`/v1/billing/account-state${t}`)}async function Eu(e){throw G("createCheckoutSession",hh)}async function Iu(e,t){throw G("confirmCheckoutSession",hh)}async function Mu(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Ou(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Du(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function ju(e,t,n){throw G("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Lu(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function $u(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),u(await l.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function Bu(e){return u(await l.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Uu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function $k(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Fu(e){return u(await l.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function Bk(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function Uk(e){return u(await l.post("/billing/create-per-seat-checkout",{account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale}),"Failed to create per-seat checkout")}async function Fk(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function Nk(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function Nu(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await l.get(`/usage${n?`?${n}`:""}`))}function Gu(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Ms(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Os(e){return e.size>0?`?${e}`:""}async function Wu(e={}){let t=new URLSearchParams;return Gu(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Ms(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/session-costs${Os(t)}`))}async function nr(e,t={}){let n=new URLSearchParams;return Gu(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${Os(n)}`))}async function qk(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Ms(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/cost-by-project${Os(t)}`))}async function Gk(e={}){let t=new URLSearchParams;return Gu(t,e),e.sessionId&&t.set("session_id",e.sessionId),Ms(t,e),u(await l.get(`/usage/cost-summary${Os(t)}`))}function qu(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let s=t;s.ownerId&&n.set("owner_id",s.ownerId)}Ms(n,t),t.sort&&n.set("sort",t.sort),n.set("format","csv");let r=e==="projects"?"/usage/cost-by-project":"/usage/session-costs";return`${C().backendUrl||""}${r}?${n}`}async function Wk(e,t={}){let n=qu(e==="projects"?"projects":"sessions",t),r=await Fe(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),s=r.headers.get("x-beeuni-row-cap"),o=s!=null?Number(s):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(o)?o:null}}async function Sh(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function Kk(e){return Sh("slack",e)}function Vk(e){return Sh("teams",e)}async function Ph(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function Hk(e){return Ph("slack",e)}function zk(e){return Ph("teams",e)}async function Ku(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function Vu(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var Yk={oauth_available:!1,install_url:null};async function Hu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?Yk:t.data}async function xh(e,t,n){return u(await l.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function zu(e,t){return xh("slack",e,t)}function Yu(e,t){return xh("teams",e,t)}async function Ju(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Qu(e){let t=await l.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function Xu(e,t){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function Zu(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function ep(e){let t=e.connectionId??e.connection_id??null,n=e.connectorSlug??e.connector_slug??e.connectionSlug??e.connection_slug??"beeuni_email";return{...e,connectionId:t,connectorSlug:n}}var Jk={provider:"agentmail",managed_available:!1};async function tp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?ep(r.data):null}async function np(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Jk:t.data}async function rp(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return ep(n)}async function sp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function op(e,t,n){let r=u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"beeuni_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return ep(r)}async function Qk(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function Xk(e,t,n){return u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function ip(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function ap(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function cp(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function lp(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function up(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await l.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function pp(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function dp(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function gp(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function mp(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function fp(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function yp(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function hp(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function _p(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function bp(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Sp(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Pp(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function xp(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function wp(e,t,n,r,s){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function Zk(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function eR(){throw G("getReferralCode")}async function tR(){throw G("refreshReferralCode")}async function nR(e){throw G("validateReferralCode")}async function rR(){throw G("getReferralStats")}async function sR(e={}){throw G("listReferrals")}async function oR(e){throw G("sendReferralEmails")}var vp="call:";function kp(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(vp)&&e.length>vp.length?{type:"connector_call",executionId:e.slice(vp.length)}:{type:"review_item",reviewItemId:e}}function vh(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function iR(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[vh(n.status)]+=1;return t}function aR(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function Ap(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Rp(e){let t=e.indexOf(".");return t<=0?Ap(e):`(${Ap(e.slice(0,t))}) ${Ap(e.slice(t+1))}`}function cR(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Ds=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,Me=e=>Array.isArray(e)?e:void 0,wh=e=>typeof e=="number"?e:0,lR=e=>e.split(`
14
+ `).map(t=>t.trim()).filter(Boolean);function uR(e,t){let n=Ds(e.advanced),r=U(e.description),s=Me(e.whatChanged)??(r?lR(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:U(e.impact)??"",verification:Me(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:Me(e.conflicts),requestedChanges:Me(e.requested_changes)??[],advanced:{headRef:U(n.headRef)??U(e.head_ref)??"",baseRef:U(n.baseRef)??U(e.base_ref)??"",headSha:U(n.headSha)??U(e.head_sha)??U(e.head_commit_sha)??"",baseSha:U(n.baseSha)??U(e.base_sha)??"",additions:wh(n.additions),deletions:wh(n.deletions),files:Me(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function pR(e,t){let n=Me(e.actions);if(n)return{actions:n.map((c,p)=>({id:U(c.id)??`${t.review_item_id}-${p}`,title:U(c.title)??"Action",connector:U(c.connector)??"",action:U(c.action)??"",consequence:U(c.consequence)??"",risk:U(c.risk)??t.risk,icon:U(c.icon)??"generic",argsPreview:Me(c.argsPreview)??[],policySource:U(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=U(e.action_path)??"",{connector:s,action:o}=cR(r),i=Ds(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?Rp(r):t.title||"Run action",connector:s,action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:U(e.approval_context),connectorRisk:U(e.risk)??null,policySource:"Requires approval"}]}}function dR(e,t){return{artifactKind:U(e.artifactKind)??"document",artifactLabel:U(e.artifactLabel)??"Output",previewUrl:U(e.previewUrl)??U(e.preview_url),preview:U(e.preview),files:Me(e.files),note:U(e.note)??t.summary??""}}function gR(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:Me(e.options)??[]}}function mR(e,t){return{note:U(e.note)??t.summary??"",children:Me(e.children)??[]}}function fR(e){let t=Ds(e.detail);switch(e.kind){case"change":return uR(t,e);case"approval":return pR(t,e);case"output":return dR(t,e);case"decision":return gR(t,e);case"batch":return mR(t,e)}}function yR(e,t){let n=typeof e.number=="number"?e.number:void 0,r=U(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function hR(e,t={}){let n=Ds(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?U(n.action_path):void 0,i=e.kind==="change"?yR(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:o?Rp(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:fR(e)}}var Q={PROJECT_READ:"project.read",PROJECT_WRITE:"project.write",PROJECT_DELETE:"project.delete",PROJECT_SESSION_READ:"project.session.read",PROJECT_SESSION_START:"project.session.start",PROJECT_SESSION_STOP:"project.session.stop",PROJECT_SESSION_BINDINGS_WRITE:"project.session.bindings.write",PROJECT_MEMBERS_READ:"project.members.read",PROJECT_MEMBERS_MANAGE:"project.members.manage",PROJECT_TRIGGER_READ:"project.trigger.read",PROJECT_TRIGGER_CREATE:"project.trigger.create",PROJECT_TRIGGER_UPDATE:"project.trigger.update",PROJECT_TRIGGER_DELETE:"project.trigger.delete",PROJECT_TRIGGER_FIRE:"project.trigger.fire",PROJECT_GATEWAY_LOGS_READ:"project.gateway.logs.read",PROJECT_GATEWAY_SPEND_READ:"project.gateway.spend.read",PROJECT_USAGE_READ:"project.usage.read",PROJECT_GATEWAY_BUDGET_SET:"project.gateway.budget.set",PROJECT_GATEWAY_KEYS_MANAGE:"project.gateway.keys.manage",PROJECT_AGENT_READ:"project.agent.read",PROJECT_AGENT_WRITE:"project.agent.write",PROJECT_SKILL_READ:"project.skill.read",PROJECT_SKILL_WRITE:"project.skill.write",PROJECT_COMMAND_READ:"project.command.read",PROJECT_COMMAND_WRITE:"project.command.write",PROJECT_FILE_READ:"project.file.read",PROJECT_FILE_WRITE:"project.file.write",PROJECT_SETTINGS_WRITE:"project.settings.write",PROJECT_SANDBOX_WRITE:"project.sandbox.write",PROJECT_MODEL_READ:"project.model.read",PROJECT_MODEL_WRITE:"project.model.write",PROJECT_GITOPS_READ:"project.gitops.read",PROJECT_GITOPS_PUSH:"project.gitops.push",PROJECT_GITOPS_MERGE:"project.gitops.merge",PROJECT_GITOPS_REF_ANY:"project.gitops.ref.any",PROJECT_GITOPS_REF_DELETE:"project.gitops.ref.delete",PROJECT_SECRET_READ:"project.secret.read",PROJECT_SECRET_WRITE:"project.secret.write",PROJECT_CONNECTOR_READ:"project.connector.read",PROJECT_CONNECTOR_CONNECTIONS_MANAGE:"project.connector.connections.manage",PROJECT_CONNECTOR_WRITE:"project.connector.write",PROJECT_APP_READ:"project.app.read",PROJECT_APP_WRITE:"project.app.write",PROJECT_APP_DEPLOY:"project.app.deploy",PROJECT_APP_ADMIN:"project.app.admin",PROJECT_REVIEW_READ:"project.review.read",PROJECT_REVIEW_SUBMIT:"project.review.submit",PROJECT_REVIEW_ACT:"project.review.act",PROJECT_CREDENTIALS_ISSUE:"project.credentials.issue"},_R=[Q.PROJECT_WRITE,Q.PROJECT_TRIGGER_CREATE,Q.PROJECT_TRIGGER_FIRE,Q.PROJECT_TRIGGER_UPDATE,Q.PROJECT_TRIGGER_DELETE];function bR(e){let t=r=>e[r]?.allowed===!0,n=t(Q.PROJECT_WRITE);return{canCreate:n&&t(Q.PROJECT_TRIGGER_CREATE),canFire:t(Q.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(Q.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(Q.PROJECT_TRIGGER_DELETE)}}var SR=[Q.PROJECT_WRITE,Q.PROJECT_GITOPS_PUSH,Q.PROJECT_GITOPS_MERGE,Q.PROJECT_REVIEW_ACT];function Ah(e){let t=r=>e[r]?.allowed===!0,n=t(Q.PROJECT_WRITE);return{canOpen:n&&t(Q.PROJECT_GITOPS_PUSH),canMerge:n&&t(Q.PROJECT_GITOPS_MERGE),canClose:n}}function PR(e,t,n){let r=kp(e.id);if(r.type==="connector_call"){let s=e.kind==="approval"?e.detail.actions?.[0]:void 0;return(t==="approve"||t==="reject")&&s?.canResolve!==!1&&s?.previewAuthorized!==!1}if(r.type==="change_request"){if(t==="answer")return!1;if(t==="approve")return Ah(n).canMerge}return n[Q.PROJECT_WRITE]?.allowed===!0&&n[Q.PROJECT_REVIEW_ACT]?.allowed===!0}function B(e){return l.get(e,{showErrors:!1})}function k(e){return u(e,"Unexpected empty response")}async function Cp(e){return k(await B(`/accounts/${e}/iam/groups`)).groups}async function Tp(e,t){return k(await B(`/accounts/${e}/iam/groups/${t}`))}async function Ep(e,t){return k(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Ip(e,t,n){return k(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Mp(e,t){return k(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function Op(e,t){return k(await B(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Dp(e,t,n){return k(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function xR(e,t){return k(await B(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function jp(e,t,n){return k(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function wR(e,t){return k(await B(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function vR(e,t){let n=k(await B(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function at(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function AR(e,t={}){let n=at({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return k(await B(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function kR(e,t={}){let n=at({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return k(await B(`/accounts/${e}/iam/policies${n}`)).policies}async function RR(e,t){return k(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function CR(e,t,n){return k(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function TR(e,t){return k(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function ER(e,t){return k(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function IR(e,t){return k(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Lp(e){return k(await B(`/accounts/${e}/iam/roles`)).roles}async function $p(e){return k(await B(`/accounts/${e}/iam/agent-identities`)).agents}async function Bp(e){return k(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function Up(e,t){return k(await B(`/accounts/${e}/iam/roles/${t}/permissions`))}async function MR(e){return k(await B(`/accounts/${e}/iam/actions`)).actions}async function Fp(e,t){return k(await B(`/accounts/${e}/iam/roles/${t}/usage`))}async function Np(e,t){return k(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function qp(e,t,n){return k(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Gp(e,t,n){return k(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Wp(e,t){return k(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function OR(e,t,n){return k(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function DR(e){return k(await B(`/accounts/${e}/iam/scim/tokens`)).tokens}async function jR(e,t){return k(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function LR(e,t){return k(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function $R(e){return k(await B(`/accounts/${e}/iam/mfa-required`))}async function BR(e){return k(await B(`/accounts/${e}/iam/mfa-required/preview`))}async function UR(e,t){return k(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function FR(e){return k(await B(`/accounts/${e}/iam/session-oversight`))}async function NR(e,t){return k(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function qR(e){return k(await B(`/accounts/${e}/iam/sso/provider`)).provider}async function GR(e,t){return k(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function WR(e){return k(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function KR(e){return k(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function VR(e){return k(await B(`/accounts/${e}/iam/sso/mappings`)).mappings}async function HR(e,t){return k(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function zR(e,t){return k(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function YR(e){return k(await B(`/accounts/${e}/iam/session-policy`))}async function JR(e,t){return k(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function QR(e){return k(await B(`/accounts/${e}/iam/sessions`)).sessions}async function XR(e,t){return k(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function ZR(e){return k(await B(`/accounts/${e}/iam/pat-policy`))}async function eC(e,t){return k(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function tC(e){return k(await B(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function nC(e,t){return k(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function rC(e,t){return k(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function sC(e,t){return k(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function oC(e){return k(await B(`/accounts/${e}/audit/webhooks`)).webhooks}async function iC(e,t){return k(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function aC(e,t,n){return k(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function cC(e,t){return k(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function lC(e,t={}){let n=at({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return k(await B(`/accounts/${e}/audit${n}`))}async function Kp(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),k(await B(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Vp(e,t,n){return n.length===0?[]:k(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function uC(e){return k(await B(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function pC(e,t){return k(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function Hp(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function zp(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function Yp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function Jp(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function Qp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Xp(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function dC(e){return at({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function Zp(e,t){return u(await B(`/accounts/${e}/iam/assignments${dC(t)}`)).assignments}async function ed(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await l.post(`/accounts/${e}/iam/assignments`,n))}async function td(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function nd(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await B(`/accounts/${e}/iam/permissions${n}`)).permissions}async function kh(){let e=await l.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function Rh(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function Ch(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function Th(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}var Eh="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function gC(e){throw G("getGoogleAuthUrl",Eh)}async function mC(e,t){throw G("convertPresentationToGoogleSlides",Eh)}async function rd(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind),t?.sessionId&&n.set("session_id",t.sessionId),t?.limit!=null&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);let r=n.toString();return u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function sd(e){return u(await l.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function od(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function id(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function ad(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function cd(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}async function ld(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function ud(e){return u(await l.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function pd(e,t){let n=await l.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var js=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Ih(e,t=""){return`${tr()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Mh(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let s=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new js(s,t.status)}return r}async function fC(e){return Mh(Ih(e))}async function yC(e){return Mh(Ih(e,"/messages"))}async function dd(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function gd(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Ls(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function $s(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var hC=4;async function Oh(e,t){let n=new Array(e.length),r=0,s=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(hC,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?o.done.push(i):o.failed.push({reminder:i,error:c.error})}),o}function md(e,t,n){return Oh(t,r=>Ls(e,r.sessionId,r.reminderId,n))}function fd(e,t){return Oh(t,n=>$s(e,n.sessionId,n.reminderId))}async function yd(e){return u(await l.get(`/projects/${e}/reminders`))}async function hd(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await l.get(`/accounts/tokens${r}`))}async function _d(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await l.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function bd(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function Sd(){return u(await l.get("/oauth/grants")).grants}async function Pd(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function _C(){return u(await l.get("/accounts/me/devices")).devices}async function bC(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function xd(e){return u(await l.get(`/projects/${e}/cli-token`))}async function wd(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function vd(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function Jt(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,s]of Object.entries(e))n.includes(` ${r} `)&&s!=null&&s!==""&&t.set(r,String(s));return t}function Ad(e={}){return{format:e.format,action:e.action,actor:e.actor,actor_type:e.actorType,project_id:e.projectId,session_id:e.sessionId,source:e.source,credential_kind:e.credentialKind,phase:e.phase,outcome:e.outcome,resource_type:e.resourceType,request_id:e.requestId,correlation_id:e.correlationId,since:e.since,until:e.until,q:e.q,cursor:e.cursor,limit:e.limit}}async function kd(e,t){let n=Jt(Ad(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function Rd(e,t){let n=Jt(Ad({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function Cd(e,t){let n=Jt(Ad(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Td(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Ed(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Id(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Md(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Od(e,t){return u(await l.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function Dd(e,t){return u(await l.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function SC(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function jd(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await l.get(`/marketplace/items${n}`))}async function Ld(){return u(await l.get("/marketplace/marketplaces"))}async function $d(){return u(await l.get("/marketplace/marketplaces/featured"))}async function Bd(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Ud(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Fd(){return u(await l.get("/marketplace/sources"))}async function Nd(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function qd(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function PC(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function xC(e){throw G("getTemplate")}async function wC(e,t){throw G("installTemplate")}async function Gd(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Wd(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Bs(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Kd(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Vd(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Hd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function zd(e,t){let n=await Bs(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await l.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),s=new TextEncoder().encode(JSON.stringify(r)),o="";for(let i of s)o+=String.fromCharCode(i);return{BEEUNI_AUTH_ISSUER:n.auth.issuer,BEEUNI_AUTH_AUDIENCE:n.auth.audience,BEEUNI_AUTH_JWKS:`data:application/json;base64,${btoa(o)}`}}async function Yd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Jd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function Qd(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Xd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Us(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Fs(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function vC(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function AC(e){let t=Uint8Array.from(e),n=await globalThis.crypto.subtle.digest("SHA-256",t.buffer);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}async function Zd(e,t,n={}){let r=await vC(t),s=n.mediaType??"application/gzip",o=await Us(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),Fs(e,o.artifact.artifact_id,{sha256:await AC(r),size_bytes:r.byteLength})}async function eg(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function tg(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function ng(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function rg(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function sg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function og(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function ig(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function ag(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var xe=(e,t)=>`/projects/${e}/apps/${t}`;async function cg(e,t){return u(await l.get(`${xe(e,t)}/machines`),"Failed to list machines").machines}async function lg(e,t,n,r){return u(await l.post(`${xe(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var ug=(e,t,n)=>lg(e,t,n,"start"),pg=(e,t,n)=>lg(e,t,n,"stop"),dg=(e,t,n)=>lg(e,t,n,"restart");async function gg(e,t,n){return u(await l.delete(`${xe(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function mg(e,t,n,r={}){return u(await l.put(`${xe(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function fg(e,t,n){return u(await l.post(`${xe(e,t)}/exec`,n),"Failed to run the command")}async function yg(e,t){return u(await l.get(`${xe(e,t)}/volumes`),"Failed to list volumes").volumes}async function hg(e,t,n){return u(await l.post(`${xe(e,t)}/volumes`,n),"Failed to create the volume")}async function _g(e,t,n,r){return u(await l.patch(`${xe(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function bg(e,t,n,r){u(await l.delete(`${xe(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Sg(e,t,n){return u(await l.get(`${xe(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Pg(e,t,n){return u(await l.post(`${xe(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function xg(e,t,n,r){return u(await l.post(`${xe(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function wg(e,t,n,r){return u(await l.post(`${xe(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function de(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var fe=e=>`/drives/${encodeURIComponent(e)}`;async function kC(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new x("Files not found",{status:404});return t[0]}async function RC(e,t){return u(await l.get(`${fe(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function CC(e,t){return u(await l.put(`${fe(e)}/access`,t),"Failed to share folder")}async function TC(e,t){let n=u(await l.delete(`${fe(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function EC(e){return u(await l.get(`${fe(e)}/principals`),"Failed to load people")}async function IC(e){return u(await l.get(`${fe(e)}/conflicts`),"Failed to load conflicts").conflicts}async function MC(e,t){u(await l.post(`${fe(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function OC(e,t="/"){return(await Dh(e,t)).entries}async function Dh(e,t="/"){return u(await l.get(`${fe(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function vg(e,t,n){let r=de(C().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${fe(e)}/files/content?${new URLSearchParams(s)}`}async function DC(e,t,n){let r=await j(vg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new x(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function jC(e,t,n){let r=await j(vg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new x(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function LC(e,t,n,r){return u(await l.putRaw(`${fe(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function $C(e,t){return u(await l.post(`${fe(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function BC(e,t,n){return u(await l.post(`${fe(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function UC(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${fe(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function FC(e){return u(await l.get(`${fe(e)}/versions`),"Failed to load versions").versions}async function NC(e,t){u(await l.post(`${fe(e)}/restore`,{versionId:t}),"Failed to restore version")}var qC=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function GC(e,t){return(await jh(e,t)).drives}async function jh(e,t){return u(await l.get(qC(e,t)),"Failed to load session files")}async function Ag(e){return u(await l.post("/notifications/device-token",e))}async function kg(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var WC=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered"];async function Rg(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return u(await l.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function Cg(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await l.post("/notifications/read",t))}var KC={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1},capture_device_down:{push:!0,email:!0},capture_device_recovered:{push:!0,email:!1}};async function Tg(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function Eg(e){return u(await l.put("/notifications/preferences",e))}async function Ig(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function Mg(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await l.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function Og(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function rr(e){return u(await l.get(`/projects/${e}/model-access`))}async function sr(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function VC(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:o,previewIsLinkOnly:i}=e;return t||n?!1:s?o&&!i:r==="error"}function Dg(e){return typeof e=="string"&&e.trim().length>0}function Lh(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Dg(t)||Dg(n)||Dg(r)}function HC(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function or(e){if(!e)return!0;let t=HC(e.items);return t?!t.some(Lh):!Lh(e)}var ke="beeuni.transcript.v1",$h=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function jg(e){return typeof e=="string"&&$h.includes(e)}var zC=["once","always","reject"],YC=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var Fh="beeuni-v1-import",JC={harness:Fh,harness_version:ke,adapter_version:"1"},Lg={schema:pe,v:1},QC={opencode:"[Tool execution was interrupted]",pi:"No result provided"},XC="[Old tool result content cleared]",ZC="The following tool was executed by the user",eT=new Map(Object.entries({bash:"shell",powershell:"shell",read:"read",write:"write",edit:"edit",multiedit:"edit",patch:"patch",apply_patch:"patch",list:"list",ls:"list",glob:"glob",find:"glob",grep:"grep",webfetch:"web_fetch",websearch:"web_search",codesearch:"web_search",todowrite:"todo",todoread:"todo",task:"task",question:"question",plan_enter:"plan",plan_exit:"plan"})),tT=e=>eT.get(e)??(e.includes("_")?"mcp":"other"),nT=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),rT=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),F=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),X=e=>typeof e=="string"?e:void 0,Ve=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ws=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,Nh=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Qt=e=>Ve(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Xt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function $g(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>$g(r,t[s]));if(!F(e)||!F(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0);return n.length===Object.keys(t).filter(r=>t[r]!==void 0).length&&n.every(r=>$g(e[r],Ws(t,r)))}function qs(e,t){if($g(e,t))return;if(e===void 0)return{del:!0};if(!F(e)||!F(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let s=qs(Ws(e,r),Ws(t,r));s&&Nh(n,r,s)}return{sub:n}}function Gs(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=F(e)?{...e}:{};for(let[r,s]of Object.entries(t.sub)){let o=Gs(Ws(n,r),s);o===void 0?delete n[r]:Nh(n,r,o)}return n}var ir=e=>Object.values(e??{}).find(t=>t.version===ke),Ks=(e,t)=>({[e]:{version:ke,...t}}),qh=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},Bh=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),sT=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),oT=e=>{if(F(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==ke&&F(n.data?.details));return t?t.data.details:{}};function iT(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=Xt(e.started_at)??t.created,i=Xt(e.ended_at)??o,a=r?.exit_code!==void 0?{exit:r.exit_code}:{};if(e.status==="pending")return{status:"pending",input:e.input??{},raw:""};if(e.status==="running")return{status:"running",input:e.input??{},...e.title&&{title:e.title},time:{start:o}};if(e.status==="error")return{status:"error",...s,error:Bh(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:o,end:i}};let c=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...qh(d,t)}]:[]),p=Xt(r?.cleared_at);return{status:"completed",...s,output:Bh(r?.content),title:e.title??"",metadata:{...oT(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...c.length&&{attachments:c}}}function Gh(e,t){let n=sT(e,t);switch(e.type){case"text":return{...n,type:"text",text:e.text,...e.synthetic!==void 0&&{synthetic:e.synthetic}};case"reasoning":return{...n,type:"reasoning",text:e.text,time:{start:t.created}};case"attachment":return{...n,type:"file",mime:e.mime,...e.name!==void 0&&{filename:e.name},...qh(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:iT(e,t,{...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID})};case"step":return e.phase==="start"?{...n,type:"step-start"}:{...n,type:"step-finish",reason:"stop",cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};case"compaction":return{...n,type:"compaction",auto:e.trigger==="auto"||e.trigger==="overflow",...e.trigger==="overflow"&&{overflow:!0},...e.first_kept_message_id!==null&&{tail_start_id:e.first_kept_message_id}};case"harness":return t.fromV1&&(e.harness==="opencode"||e.harness==="pi")?e.data:e.model_visible&&e.fallback_text!==void 0?{...n,type:"text",text:e.fallback_text,synthetic:!0}:void 0;case"subtask":return}}function aT(e){return jg(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function Wh(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:rT.get(e.finish);return{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"assistant",time:{created:t.created,...e.completed_at!==null&&{completed:Xt(e.completed_at)}},...e.reply_to&&{parentID:e.reply_to},modelID:e.model?.model??"",providerID:e.model?.provider??"",...e.model?.variant!==void 0&&{variant:e.model.variant},mode:e.agent??"",agent:e.agent??"",path:{cwd:"",root:""},cost:r?.cost??0,tokens:{input:r?.input??0,output:r?.output??0,reasoning:r?.reasoning??0,cache:{read:r?.cache_read??0,write:r?.cache_write??0}},...s&&{finish:s},...e.error&&{error:aT(e.error)},...n}}function Kh(e,t){return e.role==="assistant"?Wh(e,t):{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"user",time:{created:t.created},agent:e.agent??"",model:{providerID:e.model?.provider??"",modelID:e.model?.model??"",...e.model?.variant!==void 0&&{variant:e.model.variant}}}}function Vh(e,t,n){let r=`${e.message_id}-summary`;return{info:Wh({...e,reply_to:e.message_id,agent:"compaction",finish:e.status==="complete"?"stop":null},n,{id:r,summary:!0}),parts:[{id:`${r}-p0`,...n.sessionID!==null&&{sessionID:n.sessionID},messageID:r,type:"text",text:t.summary}]}}function cT(e,t,n){let r=n||e.producer.harness===Fh;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=ir(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:Xt(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=Gh(d,i);return g===void 0?[]:[Gs(g,ir(d.ext)?.data)]}),c=[{runtime_session_id:o,info:Gs(Kh(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=Gs(Vh(e,p,i),s?.summary);c.push({runtime_session_id:o,info:d.info,parts:d.parts})}return c}var Bg=e=>Ve(F(e.info)&&F(e.info.time)?e.info.time.created:void 0)??-1/0,Ns=e=>String(F(e.info)?e.info.id:""),Hh=(e,t)=>Bg(e)-Bg(t)||(Ns(e)<Ns(t)?-1:Ns(e)>Ns(t)?1:0),Uh=e=>{let t=ir(e.ext);return t?t.native_id??null:e.thread_id};function Vs(e){let t=structuredClone(e),n=t.threads.find(i=>i.parent_thread_id===null)??t.threads[0],r=t.threads.flatMap(i=>i.messages.flatMap(a=>cT(a,Uh(i),ir(i.ext)!==void 0))),s=ir(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?Uh(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(Hh)}}function lT(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:F(e.model)?{p:e.model.providerID,m:e.model.modelID,v:e.model.variant}:{},n=X(t.p),r=X(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...X(t.v)!==void 0&&{variant:t.v}}}function uT(e){if(!F(e.tokens))return null;let t=e.tokens,n=F(t.cache)?t.cache:{};return{input:Ve(t.input)??0,output:Ve(t.output)??0,cache_read:Ve(n.read)??0,cache_write:Ve(n.write)??0,...Ve(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Ve(e.cost)!==void 0&&{cost:e.cost}}}var pT=e=>({code:X(e.code)||X(e.name)||"UnknownError",message:X(F(e.data)?e.data.message:void 0)??""});function zh(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:X(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...X(e.url)!==void 0&&{url:e.url}}}function dT(e,t,n,r){let s=e.state,o=F(s.time)?s.time:{};F(s.input)||r.tool_input++;let i=F(s.metadata)&&Ve(s.metadata.exit)!==void 0?{exit_code:s.metadata.exit}:{},a,c,p=s.input??null;if(s.status==="completed"){let m=(Array.isArray(s.attachments)?s.attachments:[]).filter(F).map(h=>{let{bytes:S,...E}=zh(h,n,r);return{type:"attachment",...E}}),f=Qt(o.compacted);a="complete",c={content:[...X(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:XC}],cleared_at:f}}}else if(s.status==="error"){let m=X(s.error);a="error",c={content:m!==void 0?[{type:"text",text:m}]:[],is_error:!0,...m!==void 0&&{error:{message:m}},...i}}else if(n.live)a=s.status==="pending"?"pending":"running",a==="pending"&&X(s.raw)&&!(F(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=QC[n.h];a="error",c={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=Qt(o.start),g=Qt(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:tT(e.tool),input:p,status:a,...c&&{result:c},...X(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function gT(e,t,n,r,s,o){let i=(a,c=!1)=>({type:"harness",id:t,harness:s.h,kind:a,data:e,model_visible:c,...c&&{fallback_text:ZC}});if(!F(e))return i("unknown");switch(e.type){case"text":return typeof e.text!="string"||e.ignored===!0?i("text"):{type:"text",id:t,text:e.text,...typeof e.synthetic=="boolean"&&{synthetic:e.synthetic}};case"reasoning":return typeof e.text!="string"?i("reasoning"):{type:"reasoning",id:t,text:e.text};case"file":return e.mime==="text/plain"||e.mime==="application/x-directory"?i("file"):{type:"attachment",id:t,...zh(e,s,o),...X(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&F(e.state)?dT(e,t,s,o):i("tool");case"step-start":case"step-finish":return{type:"step",id:t,phase:e.type==="step-start"?"start":"finish"};case"compaction":{if(e!==n)return i("compaction");let a=e.overflow===!0?"overflow":e.auto===!0?"auto":"manual";return{type:"compaction",id:t,summary:r,first_kept_message_id:X(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(X(e.type)||"unknown")}}function mT(e){let t=e.map((s,o)=>F(s)&&typeof s.id=="string"&&s.id?s.id:`#${o}`),n=new Set(t),r=new Set;return t.map(s=>{if(!r.has(s))return r.add(s),s;let o=2;for(;n.has(`${s}#${o}`);)o++;return n.add(`${s}#${o}`),`${s}#${o}`})}function fT(e,t,n,r,s,o){let i=F(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],c=i.role==="user"?a.find(A=>F(A)&&A.type==="compaction"):void 0,p=t&&F(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",g=c?p:d==="assistant"?i:void 0,m=g&&F(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",h=g&&F(g.time)?Qt(g.time.completed):null,S=o.live?"streaming":"interrupted",E=g?m?f?"aborted":"error":h?"complete":S:c?S:"complete",L=Qt(F(i.time)?i.time.created:void 0)??"",D=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(A=>F(A)&&A.type==="text"&&typeof A.text=="string"?[A.text]:[]).join(""):null,w={tool_input:0,cut_point:0,attachment:0},y=mT(a),_=a.map((A,$)=>gT(A,y[$],c,D,o,w)),R=_.some(A=>A.type==="text"||A.type==="attachment"||A.type==="tool_call"||A.type==="harness"&&A.model_visible),v=!s&&d!=="system"&&(c?E==="complete":!m||f&&R),b=o.live&&v&&E!=="streaming"&&_.some(A=>A.type==="tool_call"&&(A.status==="pending"||A.status==="running"))?"streaming":E,P=s?"superseded":v||!m?void 0:f?"aborted":"failed_attempt";return c&&F(c)&&X(c.tail_start_id)===void 0&&w.cut_point++,{m:{...Lg,message_id:X(i.id)??"",thread_id:n,seq:r,role:d,kind:c?"compaction":"turn",status:b,in_context:v,...P&&{hidden_reason:P},agent:X(i.agent)??null,...d==="assistant"&&{reply_to:X(i.parentID)??null},model:lT(i),usage:g?uT(g):null,finish:!g||c?null:f?"aborted":m?"error":nT.get(i.finish)??null,error:m?pT(m):null,created_at:L,completed_at:g||c?h:L||null,producer:JC,blocks:_},lost:w}}function yT(e,t,n,r,s){let o={};t.runtime_session_id!==r&&(o.runtime_session_id=t.runtime_session_id);let i={sessionID:t.runtime_session_id,messageID:e.message_id,created:Xt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=qs(t.parts[d],Gh(p,i));g&&(p.ext=Ks(s,{data:g}))}):o.parts=t.parts;let a=qs(t.info,Kh(e,i));a&&(o.info=a);let c=e.blocks.find(p=>p.type==="compaction");if(n&&c){let p=qs({info:n.info,parts:n.parts},Vh(e,c,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Ks(s,{data:o}))}function hT(e,t,n){if(t){for(let r of[!0,!1])for(let s of e)if(!(s.runtime_session_id===t||!Array.isArray(s.parts))){for(let o of s.parts)if(!(!F(o)||o.type!=="tool"||!F(o.state))&&(r?F(o.state.metadata)&&o.state.metadata.sessionId===t:n(o.state).includes(t)))return{row:s,part:o}}}}function Hs(e,t={}){let n={h:t.harness??"opencode",resolve:t.resolveAttachment??(()=>null),counts:{tool_input:0,cut_point:0,attachment:0},live:t.live===!0},r=structuredClone(e.rows).sort(Hh),s=new Map;for(let w of r){let y=s.get(w.runtime_session_id);y?y.push(w):s.set(w.runtime_session_id,[w])}let o=e.root_id,i=s.has(o),a=new Map,c=w=>a.get(w)??(a.set(w,JSON.stringify(w)),a.get(w)),p=new Map;for(let w of s.keys()){let y=i&&w===o?void 0:hT(r,w,c);y&&p.set(w,y)}let d=[...r].reverse().find(w=>w.runtime_session_id===null||!p.has(w.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=w=>w!==null&&p.has(w)?w:m,h=Qt(r.map(Bg).find(Number.isFinite))??"",S=[];for(let[w,y]of s){if(w!==g&&(w===null||!p.has(w)))continue;let _=w===g,R=_?r.filter(T=>T.runtime_session_id!==g&&f(T.runtime_session_id)===m):[],v=[...R,...y],b=new Set(R),P=new Map,O=new Set;for(let T of v){let q=F(T.info)?T.info:{};if(q.role!=="user"||!Array.isArray(T.parts)||!T.parts.some(H=>F(H)&&H.type==="compaction"))continue;let W=v.find(H=>!O.has(H)&&H.runtime_session_id===T.runtime_session_id&&F(H.info)&&H.info.role==="assistant"&&H.info.summary===!0&&H.info.parentID===q.id);W&&(P.set(T,W),O.add(W))}let A=[];for(let T of v){if(O.has(T))continue;let q=P.get(T),{m:W,lost:H}=fT(T,q,_?m:w,A.length+1,b.has(T),n);if(yT(W,T,q,w,n.h),W.in_context)for(let In of["tool_input","cut_point","attachment"])n.counts[In]+=H[In];A.push(W)}let $=w===null?void 0:p.get(w),N=A.find(T=>T.role==="user"&&T.kind==="turn");S.push({...Lg,thread_id:_?m:w,parent_thread_id:$?f($.row.runtime_session_id):null,spawned_by:$&&typeof $.part.callID=="string"?{message_id:X($.row.info?.id)??"",call_id:$.part.callID}:null,agent:N?.agent??null,title:null,created_at:A[0]?.created_at||h,messages:A,ext:Ks(n.h,w===null?{}:{native_id:w})})}S.sort((w,y)=>w.parent_thread_id===null?-1:y.parent_thread_id===null?1:D(w)-D(y));let E=S[0]?.messages.filter(w=>w.role==="user"&&w.kind==="turn").at(-1),L=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...Lg,session_id:e.session_id,title:null,created_at:h,restore_grade:L?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:E?.agent??null,model:E?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:S,...g!==o&&{ext:Ks(n.h,{data:{root_id:o}})}};function D(w){return r.findIndex(y=>y.runtime_session_id===w.thread_id)}}var Ug={schema:pe,v:1},_T=Object.freeze({}),Yh=new WeakMap;function ar(e){let t=Yh.get(e);if(t&&t.state===e.state)return t.block;let n=e.sessionID??null,r={id:e.messageID,sessionID:e.sessionID,role:"assistant"},o=Hs({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return Yh.set(e,{state:e.state,block:o}),o}var Fg=new WeakMap;function Ng(e){if(Fg.has(e))return Fg.get(e);let t={...Ug,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:ke}},messages:[{...Ug,message_id:"",thread_id:"",seq:1,role:"assistant",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:"",completed_at:null,producer:{harness:"",harness_version:"",adapter_version:""},blocks:[e]}]},{rows:n}=Vs({...Ug,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[t]}),r=n[0].parts[0];return Fg.set(e,r),r}function ae(e){return Ng(e)}var ye=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",He=e=>ye(e)?ae(e):e;function Qh(e){let t=ae(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:_T}var Xh=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function Zh(e){return e.status==="complete"?"completed":e.status}var Jh=new WeakMap;function e_(e){if(e.status!=="complete")return"";let t=Jh.get(e);return t===void 0&&Jh.set(e,t=Xh(e)),t}function t_(e){return e.status==="error"?e.result?.error?.message||Xh(e):void 0}function he(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function bT(e){return he(e)==="bash"}function qg(e){let t=he(e);return t==="question"||t==="ask"}function ST(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var n_=new Set(["show","show_user"]);function Gg(e){return n_.has(he(e))}function PT(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Wg(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||zs(e))}function zs(e){let t=ye(e)?ae(e):e,n=he(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:or(t.state?.input)}var r_=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Kg(e){return r_.has(he(e))}var xT=50*1024*1024,Vg="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",wT=new RegExp(`^beeuni-attachment://(${Vg})/(${Vg})/(${Vg})$`);function zg(e){if(typeof e!="string")return null;let t=wT.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function vT(e){return zg(e)!==null}var Hg=new WeakMap;async function Yg(e,t,n,r={}){if(n.size>xT)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:Hg.get(n)?.get(s);if(o?.promise)return o.promise;let i=o??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let c=Hg.get(n)??new Map;c.set(s,i),Hg.set(n,c)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=l.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(c=>{throw i.promise=void 0,c}),i.promise}async function Jg(e,t){let n=zg(e);if(!n)throw new Error("Invalid attachment reference");let r=C().backendUrl.replace(/\/$/,""),s=await j(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new x("Could not load attachment",{status:s.status});return s.blob()}var AT=new Set(["show","show_user"]);function kT(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return t;let i=e.indexOf("</file>",o+1);if(i===-1)return t;t.push(e.slice(s,o).trimStart()),n=i+7}}var ze=e=>!!e&&typeof e=="object"&&!Array.isArray(e),cr=e=>typeof e=="string"&&e.length>0?e:null,s_=e=>typeof e=="string"?cr(e.split("/").pop()):null;function Ys(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function RT(e){if(Array.isArray(e))return e;if(typeof e!="string"||!e.trim())return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function CT(e){let t=e.blocks.filter(ze).map(n=>n.type==="attachment"?{type:"file",url:n.ref??n.url,filename:n.name,mime:n.mime}:n.type==="tool_call"?{type:"tool",tool:n.name,state:{input:n.input}}:n.type==="harness"&&ze(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function TT(e,t){for(let n of kT(e))t(Ys(n,"attachment"),Ys(n,"filename")??s_(Ys(n,"path")),Ys(n,"mime"))}function ET(e,t){for(let n of[e,...RT(e.items)])ze(n)&&t(n.attachment,s_(n.path),null)}function IT(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=ze(r)&&Array.isArray(r.blocks)?CT(r):r;if(!ze(s)||!ze(s.info)||!Array.isArray(s.parts))continue;let o=cr(s.info.id);if(!o)continue;let i=cr(s.info.role)??"unknown",a=(c,p,d)=>{let g=zg(c);!g||n.has(c)||(n.add(c),t.push({url:c,attachment_id:g.attachmentId,filename:p,mime:d,message_id:o,role:i}))};for(let c of s.parts)ze(c)&&(c.type==="file"?a(c.url,cr(c.filename),cr(c.mime)):c.type==="text"&&typeof c.text=="string"?TT(c.text,a):c.type==="tool"&&typeof c.tool=="string"&&AT.has(he(c.tool))&&ze(c.state)&&ze(c.state.input)&&ET(c.state.input,a))}return t}function ct(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function MT(e,t){if(e==null)return t;let n=e.trim().toLowerCase();return["1","true","yes","y","on"].includes(n)?!0:["0","false","no","n","off"].includes(n)?!1:t}function OT(e){if(e==null)return;let t=e.trim().toLowerCase();if(["1","true","yes","y","on"].includes(t))return!0;if(["0","false","no","n","off"].includes(t))return!1}function Qg(e,t,n){return e!==void 0?e:MT(ct(t),n)}var Xg={get disableMobileAdvertising(){return Qg(C().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Qg(C().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Qg(C().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var DT=new Set(["project-manager"]);function Js(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Xg.enableProjects||!DT.has(e.name)}function jT(e){let t=e.agents.filter(Js),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function o_(){return{projects:{list:At,listForAccount:Yi,get:kt,detail:jn,create:Zi,createRepo:ea,provision:ta,update:Bn,archive:Un,llmCatalog:Ln,modelPicker:$n,modelAccess:rr,setModelAccess:sr,sandboxHealth:Nn,sandboxTemplates:Nc,sessions:Tt,createSession:Et},github:{linkRepository:aa,replaceProjectRepository:ca,getInstallation:la,listInstallations:ua,listLinkableInstallations:pa,listRepositories:da,listRepositoryBranches:ga,linkInstallation:fa,saveInstallation:ma,deleteInstallation:ha,storeUserToken:ya},connectStatus:Dc,marketplace:{items:s=>jd(s),item:s=>Bd(s),itemFile:(s,o)=>Ud(s,o),marketplaces:()=>Ld(),featured:()=>$d(),sources:{list:()=>Fd(),add:s=>Nd(s),remove:s=>qd(s)}}}}var LT=["screen","actions","audio"],$T=["password_managers","messaging","banking"],BT={localHours:8760,remoteDays:3650},UT=[500,1e3,2e3,5e3,1e4],FT=[720,1080,1440,2160],NT={intervalMs:2e3,maxHeight:1440},qT=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function GT(e){let t=e.trim().toLowerCase();if(!t)return null;let n;try{n=new URL(t.includes("://")?t:`https://${t}`).hostname}catch{return null}return n=n.replace(/^www\./,"").replace(/\.$/,""),qT.test(n)?n:null}function WT(e){let t=e.trim();return!t||t.length>255||t.startsWith("-")||/[\u0000-\u001f\u007f]/.test(t)||/\s/.test(t)&&!t.toLowerCase().endsWith(".exe")?null:t}function KT(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var Z=e=>`/accounts/${e}/capture`;function Ye(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}var i_=e=>Ye({q:e.q,kinds:e.kinds?.join(","),app:e.app,limit:e.limit,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,scope:e.scope}),Zg=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function em(e,t={}){return u(await l.get(`${Z(e)}/devices${Ye({user_id:t.userId,scope:t.scope})}`))}async function tm(e,t){return u(await l.delete(`${Z(e)}/devices/${t}`))}async function nm(e,t,n){return u(await l.put(`${Z(e)}/devices/${t}/link`,{user_id:n}))}async function rm(e){return u(await l.get(`${Z(e)}/enrollment-tokens`))}async function sm(e,t){return u(await l.post(`${Z(e)}/enrollment-tokens`,t))}async function om(e,t){return u(await l.delete(`${Z(e)}/enrollment-tokens/${t}`))}async function im(e,t={}){return u(await l.get(`${Z(e)}/enrollments${Ye({status:t.status})}`))}async function am(e,t,n){return u(await l.post(`${Z(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function cm(e,t){return u(await l.post(`${Z(e)}/enrollments/${t}/deny`,{}))}async function lm(e){return u(await l.get(`${Z(e)}/policy`))}async function um(e,t){return u(await l.put(`${Z(e)}/policy`,{policy:t}))}async function pm(e,t={}){return u(await l.get(`${Z(e)}/timeline${Ye(Zg(t))}`))}async function dm(e,t={}){return u(await l.get(`${Z(e)}/timeline/items${Ye(Zg(t))}`))}async function gm(e,t={}){return u(await l.get(`${Z(e)}/days${Ye({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function mm(e,t){return u(await l.get(`${Z(e)}/search${i_(t)}`))}async function fm(e,t,n={}){return u(await l.get(`${Z(e)}/frames/${t}${Ye({user_id:n.userId})}`))}async function ym(e,t,n={}){return u(await l.get(`${Z(e)}/chunks/${t}/media${Ye({user_id:n.userId})}`))}async function hm(e,t,n){return u(await l.get(`${Z(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function _m(e){return u(await l.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function bm(e,t){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function Sm(e){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function Pm(e){return u(await l.get(Z(e)))}async function xm(e,t){return u(await l.patch(Z(e),{enabled:t}))}async function wm(e){return u(await l.get(`/capture/me/search${i_(e)}`))}async function vm(e={}){return u(await l.get(`/capture/me/timeline${Ye(Zg(e))}`))}async function Am(e){return u(await l.get(`/capture/me/frames/${e}`))}function HT(e){return{workspace:{get:()=>Pm(e),setEnabled:t=>xm(e,t)},devices:{list:t=>em(e,t),revoke:t=>tm(e,t),link:(t,n)=>nm(e,t,n),assetUrl:(t,n)=>hm(e,t,n)},enrollment:{tokens:{list:()=>rm(e),create:t=>sm(e,t),revoke:t=>om(e,t)},list:t=>im(e,t),approve:(t,n)=>am(e,t,n),deny:t=>cm(e,t)},policy:{get:()=>lm(e),set:t=>um(e,t)},timeline:{get:t=>pm(e,t),items:t=>dm(e,t),days:t=>gm(e,t)},search:t=>mm(e,t),frame:(t,n)=>fm(e,t,n),media:(t,n)=>ym(e,t,n)}}var a_={account:e=>HT(e),deviceGrant:_m,approveDevice:bm,denyDevice:Sm,me:{search:wm,timeline:vm,frame:Am}};function c_(){return{billing:{accountState:wu,accountStateMinimal:vu,transactions:Au,transactionsSummary:ku,creditBreakdown:Ru,usageHistory:Cu,usageRollup:Nu,sessionCosts:{list:Wu,get:nr},tierConfigurations:Tu,checkout:{createSession:n=>Eu(n),confirmSession:(n,r)=>Iu(n,r)},subscription:{createPortalSession:(n,r)=>Mu(n,r),cancel:(n,r)=>Ou(n,r),reactivate:n=>Du(n),scheduleDowngrade:(n,r,s)=>ju(n,r,s),cancelScheduledChange:n=>Lu(n),prorationPreview:(n,r)=>$u(n,r)},credits:{purchase:n=>Bu(n),autoTopupSettings:n=>Uu(n),configureAutoTopup:n=>Fu(n)}},sandboxShares:{list:ld,create:ud,revoke:pd}}}var Je={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",BEEUNI_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function lt(){let e=ct("BACKEND_URL")||C().backendUrl;return e||"http://localhost:8008/v1"}function It(e){let t=de(e);return t.endsWith("/v1")?t:`${t}/v1`}function lr(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=lr(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return lr(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function zT(e){return e==="running"||e==="active"?"active":e==="queued"||e==="branching"||e==="provisioning"?"provisioning":e==="failed"||e==="error"?"error":e==="stopped"||e==="completed"||e==="archived"?"stopped":e||"unknown"}function Qs(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"daytona",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${lt()}/p/${n.external_id}/${Je.BEEUNI_MASTER}`:""),status:zT(n?.status||t.status),metadata:{...t.metadata??{},project_id:e.project_id,session_id:t.session_id,project_name:e.name,runtime_status:n?.status,error:t.error},created_at:n?.created_at||t.created_at,updated_at:n?.updated_at||t.updated_at}}async function km(){let e=await At(),t=[];for(let n of e){let r=await Tt(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Qs(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Rm(e){let t=await l.get(`/sessions/${encodeURIComponent(e)}`,{showErrors:!1});if(t.success&&t.data)return t.data;if(t.error?.status===400||t.error?.status===404)return null;throw t.error??new Error("Session request failed")}async function Xs(e){let t=await Rm(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await ur(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function ur(e){let t=await km();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}var Zt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function ce(e,t,n){let r=n?.fetch??C().fetch??((p,d)=>fetch(p,d)),s=de(n?.backendUrl??C().backendUrl??"");if(!s)throw new Zt("not_configured","backendUrl is not configured (configureBeeuni / createBeeuni first)",0);let o={accept:"application/json"};t.body!==void 0&&(o["content-type"]="application/json"),t.bearer&&(o.authorization=`Bearer ${t.bearer}`);let i=await r(`${It(s)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:o,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new Zt(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return c}function Zs(e,t){return ce("/auth/signup",{body:e},t)}function eo(e,t){return ce("/auth/sign-in/password",{body:e},t)}function to(e,t){return ce("/auth/sign-in/magic-link",{body:e},t)}function no(e,t){return ce("/auth/verify-otp",{body:e},t)}function ro(e,t){return ce("/auth/sign-in/oauth",{body:e},t)}function so(e,t){return ce("/auth/oauth/exchange",{body:e},t)}function en(e,t){return ce("/auth/refresh",{body:e},t)}function oo(e,t){return ce("/auth/password/reset",{body:e},t)}function io(e,t,n){return ce("/auth/password/update",{body:e,bearer:t},n)}function ao(e,t){return ce("/auth/user",{bearer:e},t)}function co(e,t,n){return ce("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function lo(e,t){return ce("/auth/sign-in/sso",{body:e},t)}var uo={enroll:(e,t,n)=>ce("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>ce(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>ce(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>ce(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function po(e,t={},n){return ce("/auth/sign-out",{body:t,bearer:e},n)}function go(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,c=0,p=new Set,d=S=>(S.expires_at??0)*1e3,g=S=>d(S)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let S of[...p])try{S(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let S=c,E=(async()=>{let L=await e.storage.get();if(S===c&&L)try{let D=JSON.parse(L);D.session?.access_token&&D.session?.refresh_token&&(r=D.session,s=D.user??null)}catch{r=null}return o=!0,r})();i=E,E.then(()=>{i===E&&(i=null)},()=>{i===E&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let S=r.refresh_token,E=c,L=en({refresh_token:S},e.request).then(async D=>(E!==c||(r=D.session,D.user&&(s=D.user),await m()),r)).catch(async D=>{if(E!==c)return r;let w=D&&typeof D=="object"&&"status"in D?D.status:0;if(w>=400&&w<500)return r=null,s=null,await m(),null;throw D}).finally(()=>{a===L&&(a=null)});a=L}return a}return{subscribe(S){return p.add(S),()=>{p.delete(S)}},current:()=>r,user:()=>s,load:f,async set(S,E){await f(),c+=1,a=null,r=S,E!==void 0&&(s=E),S||(s=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){c+=1,a=null,r=null,s=null,o=!0,await m()}}}function l_(){return{list:Ri,get:Ti,create:Ci,secretResources:{list:Ya,create:Ja,rotate:Qa,retry:Xa,remove:Za,grant:ec,revoke:tc,setAccess:nc},updateName:Ei,branding:{get:Ii,update:Mi,uploadAsset:Oi,removeAsset:Di,reset:ji},leave:Hi,members:Li,invite:$i,removeMember:Ki,updateMemberRole:Vi,invites:Bi,cancelInvite:Ui,resendInvite:Fi,tokens:{list:hd,create:_d,revoke:bd},connectedApps:{list:Sd,revoke:Pd},audit:{log:kd,export:Cd,webhooks:{list:Td,create:Ed,update:Id,remove:Md}}}}function u_(){return{assignments:{list:Zp,create:ed,revoke:td},permissions:{list:nd,forRole:Up},roles:{list:Lp,create:Np,update:qp,setPermissions:Gp,remove:Wp,usage:Fp},groups:{list:Cp,get:Tp,create:Ep,update:Ip,remove:Mp,members:{list:Op,add:Dp,remove:jp}},agentIdentities:$p,oauthClients:{list:Hp,get:zp,create:Yp,update:Jp,rotateSecret:Qp,remove:Xp},can:Kp,canBatch:Vp}}function p_(){let e={signUp:Zs,signInWithPassword:eo,sendMagicLink:to,verifyOtp:no,signInWithProvider:ro,exchangeCode:so,refresh:en,resetPassword:oo,updatePassword:io,updateUserMetadata:co,signInWithSso:lo,mfa:uo,user:ao,signOut:po,session:go},t=l_(),n=u_();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Ni,describe:qi,accept:us,acceptAndLand:Gi,decline:Wi}}}var pr=new Map,Cm=new Map;function Tm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function d_(e){return pr.get(Tm(e))??null}function g_(){return[...pr.values()].filter(e=>typeof e=="string")}function m_(e){return pr.has(Tm(e))}async function ut(e){let t=Tm(e),n=pr.get(t);if(n!==void 0)return n;let r=Cm.get(t);if(r)return r;let s=(async()=>{try{let o=await l.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let i=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return pr.set(t,i),i}catch{return null}finally{Cm.delete(t)}})();return Cm.set(t,s),s}function f_(e){let{apiBaseUrl:t}=e;return m_(t)||ut(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:d_(t)}}function y_(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new x(`Beeuni SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/beeuni" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let s=C().backendUrl??e.backendUrl,o=80,i=t(s);return i&&(o=i.port?Number(i.port):i.protocol==="https:"?443:80),f_({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function h_(e,t){let n=null;async function r(){n||(n=zn(e,t,{showErrors:!1}).then(s=>{let o=er(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,c=s.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var tn={url:null,sandboxId:null,dbSandboxId:null,version:0},JT=new Set;function mo(e,t=null,n=null){if(!(tn.url===e&&tn.sandboxId===t&&tn.dbSandboxId===n)){tn={url:e,sandboxId:t,dbSandboxId:n,version:tn.version+1};for(let r of JT)r()}}function __(){return tn.url}var dr=new Map;function b_(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Mt=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function S_(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await it(e,t,Math.min(3e4,o()));for(;Date.now()<s&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,o()))),i=await it(e,t,Math.min(3e4,o()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new x(b_(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new x("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ie(c);return mo(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function P_(e,t,n){let r=null;function s(){if(r)return r;let p=ph(e,t);return p&&(r=p),r}let o=S_(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=ut(C().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?mu(p.session):null,h=f?.sandbox?.external_id,S=f?.runtime_session_id;if(h&&S){let w=Ie(h);return mo(w,h),r={runtimeSessionId:S,opencodeSessionId:S,runtimeUrl:w,sandboxId:h},Ts(e,t,r),await m,r}let E=`${e}
15
+ ${t}`,L=dr.get(E);if(L)return r=await L,await m,r;let D=o(g);dr.set(E,D);try{return r=await D,await m,r}finally{dr.get(E)===D&&dr.delete(E)}}function a(p){let d=s();if(!d)throw new Mt(p);return d}function c(){r=null,dh(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:c}}var V=["directory","workspace"],x_=["messageID","model","agent","noReply","tools","format","system","variant","parts"],I=(e,t,n=V,r=[],s)=>({method:e,path:t,query:n,body:r,bodyParam:s}),QT={"session.list":I("GET","/session",[...V,"scope","path","roots","start","search","limit"]),"session.get":I("GET","/session/{sessionID}"),"session.create":I("POST","/session",V,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":I("DELETE","/session/{sessionID}"),"session.update":I("PATCH","/session/{sessionID}",V,["title","metadata","permission","time"]),"session.status":I("GET","/session/status"),"session.messages":I("GET","/session/{sessionID}/message",[...V,"limit","before"]),"session.prompt":I("POST","/session/{sessionID}/message",V,x_),"session.promptAsync":I("POST","/session/{sessionID}/prompt_async",V,x_),"session.abort":I("POST","/session/{sessionID}/abort"),"session.revert":I("POST","/session/{sessionID}/revert",V,["messageID","partID"]),"session.unrevert":I("POST","/session/{sessionID}/unrevert"),"session.summarize":I("POST","/session/{sessionID}/summarize",V,["providerID","modelID","auto"]),"session.command":I("POST","/session/{sessionID}/command",V,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":I("POST","/session/{sessionID}/share"),"session.unshare":I("DELETE","/session/{sessionID}/share"),"session.fork":I("POST","/session/{sessionID}/fork",V,["messageID"]),"session.diff":I("GET","/session/{sessionID}/diff",[...V,"messageID"]),"session.todo":I("GET","/session/{sessionID}/todo"),"permission.list":I("GET","/permission"),"permission.reply":I("POST","/permission/{requestID}/reply",V,["reply","message"]),"question.list":I("GET","/question"),"question.reply":I("POST","/question/{requestID}/reply",V,["answers"]),"question.reject":I("POST","/question/{requestID}/reject"),"part.update":I("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",V,[],"part"),"part.delete":I("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":I("GET","/file",[...V,"path"]),"file.read":I("GET","/file/content",[...V,"path"]),"find.files":I("GET","/find/file",[...V,"query","dirs","type","limit"]),"vcs.diff":I("GET","/vcs/diff",[...V,"mode","context"]),"global.health":I("GET","/global/health",[]),"global.dispose":I("POST","/global/dispose",[]),"global.config.get":I("GET","/global/config",[]),"global.config.update":I("PATCH","/global/config",[],[],"config"),"provider.list":I("GET","/provider"),"provider.auth":I("GET","/provider/auth"),"provider.oauth.authorize":I("POST","/provider/{providerID}/oauth/authorize",V,["method","inputs"]),"provider.oauth.callback":I("POST","/provider/{providerID}/oauth/callback",V,["method","code"]),"auth.set":I("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":I("GET","/agent"),"app.skills":I("GET","/skill"),"app.log":I("POST","/log",V,["service","level","message","extra"]),"command.list":I("GET","/command"),"tool.ids":I("GET","/experimental/tool/ids"),"tool.list":I("GET","/experimental/tool",[...V,"provider","model"]),"mcp.status":I("GET","/mcp"),"mcp.add":I("POST","/mcp",V,["name","config"]),"mcp.connect":I("POST","/mcp/{name}/connect"),"mcp.disconnect":I("POST","/mcp/{name}/disconnect"),"mcp.auth.start":I("POST","/mcp/{name}/auth"),"mcp.auth.callback":I("POST","/mcp/{name}/auth/callback",V,["code"]),"mcp.auth.remove":I("DELETE","/mcp/{name}/auth"),"project.list":I("GET","/project"),"project.current":I("GET","/project/current"),"path.get":I("GET","/path")};function XT(e,t){let n=[];for(let r of e.query){let s=t[r];s!=null&&n.push(`${r}=${encodeURIComponent(String(s))}`)}return n.length?`?${n.join("&")}`:""}function ZT(e,t,n={},r={}){let s=QT[t],o=s.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(s.bodyParam)i=n[s.bodyParam],a=i!==void 0;else for(let p of s.body)p in n&&(i={...i,[p]:n[p]},a=!0);let c=new Headers(r.headers);return a&&c.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${o}${XT(s,n)}`,{method:s.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function eE(e){if(!e)return"stream";let t=e.split(";")[0]?.trim()??"";return t.startsWith("application/json")||t.endsWith("+json")?"json":t==="multipart/form-data"?"formData":["application/","audio/","image/","video/"].some(n=>t.startsWith(n))?"blob":t.startsWith("text/")?"text":"json"}async function tE(e,t){let n=e.fetch??globalThis.fetch,r;try{r=await n(t)}catch(i){return{error:i||{},request:t,response:void 0}}if(r.headers.get("content-type")==="text/html")throw new Error("The session runtime does not serve this request (it answered text/html)");if(r.ok){let i=eE(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let s=await r.text(),o=s;try{o=JSON.parse(s)}catch{}return{error:o||{},request:t,response:r}}function Em(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let s=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!s.ok)throw Object.assign(new Error(`SSE failed: ${s.status} ${s.statusText}`),{status:s.status});if(!s.body)throw new Error("No body in SSE response");let o=s.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{o.cancel().catch(()=>{})}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:c,value:p}=await o.read();if(c)break;a=(a+p).replace(/\r\n/g,`
16
16
  `).replace(/\r/g,`
17
17
  `);let d=a.split(`
18
18
 
19
19
  `);a=d.pop()??"";for(let g of d){let m={},f=[];for(let h of g.split(`
20
- `))if(h.startsWith("data:"))f.push(h.replace(/^data:\s*/,""));else if(h.startsWith("id:"))m.id=h.replace(/^id:\s*/,"");else if(h.startsWith("retry:")){let x=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(x)||(m.retry=x)}f.length&&(m.data=f.join(`
21
- `)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*DA(e,t,n){let r=e.eventTransport??tg(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let u=new Headers(n.headers);i!==void 0&&u.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:u,signal:s}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(o=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(u){if(n.onSseError?.(u),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(o*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function On(e){let t=s=>(o,i)=>OA(e,EA(e.baseUrl,s,o,i)),n=s=>o=>t(s)(void 0,o);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(s={})=>({stream:DA(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,s)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var ey=200;async function jA(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function lt(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new b(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function ty(e){let t=e.runtimeUrl.replace(/\/$/,""),n=On({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(u,p)=>{let d=new URLSearchParams;u!==void 0&&d.set("limit",String(u)),p&&d.set("before",p);let g=`/messages/${s}${d.size?`?${d}`:""}`,m=x=>e.fetch(new Request(`${t}${x}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/beeuni/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/beeuni/opencode")),!f.ok)throw new b(`Reading the session transcript failed: ${await jA(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,ey),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await o(Math.min(r.limit-a.length,ey),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,s,o]=await Promise.all([n.session.status().then(i=>lt(i,"Reading the session status failed")),n.permission.list().then(i=>lt(i,"Reading permission requests failed")),n.question.list().then(i=>lt(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{lt(await n.permission.reply({requestID:r,reply:s,...o!==void 0?{message:o}:{}}),"Answering the permission request failed")},answerQuestion:async(r,s)=>{if(s===null){lt(await n.question.reject({requestID:r}),"Dismissing the question failed");return}lt(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let o=await n.global.config.get().then(u=>u.error===void 0?u.data:null),i=typeof o?.model=="string"?o.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(s={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!s)throw new b("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return lt(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function ny(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return ty({runtimeUrl:r,rootId:n,fetch:E})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,s)=>(await t()).answerPermission(n,r,s),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function ry(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await ru(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Et=BigInt(4096),Ee=BigInt(0xffffffffffff),sy=Ee+BigInt(1),$A=sy/BigInt(2),We=BigInt(3600*1e3)*Et,bs=120*1e3,oy=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,UA=/^msg_([0-9a-f]{12})/,iy="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function pt(e){let t=UA.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function Mt(e){return BigInt(Math.trunc(e))*Et&Ee}function dt(e,t){let n=e-t&Ee;return n>=$A&&(n-=sy),n}function ng(e){let t=null;for(let n of e)n!=null&&(t===null||dt(n,t)>BigInt(0))&&(t=n);return t}function ay(e,t){let n=pt(e);return n===null?!1:dt(n,Mt(t))>We}function cy(e,t){let n=t===void 0?null:Mt(t);return uy(e,r=>n===null||dt(r,n)<=We)}function uy(e,t){let n=[];for(let r of e){let s=pt(r);s!==null&&t(s)&&n.push(s)}return ng(n)}function FA(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=iy[n%62])}return e}function rg(e){let t=e.random,n=Mt(e.nowMs-(e.backdateMs??bs)),r=e.newestKnownTime??null;if(r!==null){let o=dt(r,n);o>=BigInt(0)&&o<=We&&(n=r+BigInt(1)&Ee)}let s="";if(t)for(let o=0;o<14;o++)s+=iy[Math.min(61,Math.floor(t()*62))];else s=FA();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function _s(e={}){let t=e.nowMs??Date.now(),n=Mt(t-bs),r=uy(e.after??[],s=>{let o=dt(s,n);return o>=BigInt(0)&&o<=We});return rg({nowMs:t,newestKnownTime:r}).id}function ly(e){return{scope:()=>tu(e.projectId,e.sessionId),providerSecretPool:{list:()=>ia(e.projectId,e.sessionId),get:t=>oa(e.projectId,e.sessionId,t),set:(t,n)=>aa(e.projectId,e.sessionId,t,n)},rescope:t=>nu(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,s=n?.agent??e.agent,o=r&&s?{}:await e.persistedPromptDefaults(),i=r??o.model,a=s??o.agent,u=_s(),p=await _n(e.projectId,e.sessionId,{clientMessageId:u,messageId:u,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new b("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var LA="beeuni.transcript.v1",py=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function BA(e){return typeof e=="string"&&py.includes(e)}var NA=["once","always","reject"],qA=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var dy=async function*(e){let t=k().eventStreamTransport;if(!t){yield*tg(((s,o)=>E(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await wr(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function Me(){let e=Qf();return e||(k().billingEnabled??!1?"":mf())}async function sg(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function og(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function ig(e){let t=og(e),n=await E(`${t}/env`);if(!n.ok)throw new Error(await sg(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function ag(e,t,n){let r=og(e),s=await E(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await sg(s,"Failed to save secret"))}async function cg(e,t){let n=og(e),r=await E(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await sg(r,"Failed to delete secret"))}var gy={list:ig,set:ag,delete:cg};async function my(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await E(`${r}/beeuni/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}async function Ps(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function Dn(e){if(!e)throw new Error("[beeuni-pty] Server URL not ready \u2014 sandbox is still loading");return ee(e)}async function lg(e){let t=Dn(e),n=await E(`${t}/beeuni/pty`);if(!n.ok)throw new Error(await Ps(n,"Failed to list terminals"));return n.json()}async function pg(e,t){let n=Dn(e),r=await E(`${n}/beeuni/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await Ps(r,"Failed to create terminal"));return r.json()}async function dg(e,t,n){let r=Dn(e),s=await E(`${r}/beeuni/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await Ps(s,"Failed to update terminal"));return s.json()}async function gg(e,t){let n=Dn(e),r=await E(`${n}/beeuni/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Ps(r,"Failed to remove terminal"))}async function mg(e,t,n){let r=Dn(t),o=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),ee(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/beeuni/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await xt();a&&i.set("token",a),n?.wake&&i.set("wake","1");let u=i.toString();return u?`${o}${o.includes("?")?"&":"?"}${u}`:o}function fy(e){let t=e.reason.trim().toLowerCase();return t.includes("pty not found")?"replace":t.includes("pty exited")?"ended":e.hadError||t.includes("idle timeout")||t.includes("upstream error")||e.code!==1e3?"reconnect":"ended"}var Ke="\x1B",yy="\x07",GA="\0",ug=`(?:${yy}|${Ke}\\\\)`,WA=[new RegExp(`${Ke}\\]697;[^${yy}${Ke}]*${ug}`,"g"),new RegExp(`${GA}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${Ke}\\][0-9]+;rgb:[0-9a-fA-F/]+${ug}`,"g"),new RegExp(`${Ke}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${ug}`,"g"),new RegExp(`${Ke}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${Ke}\\[\\d+;\\d+R`,"g"),new RegExp(`${Ke}\\[\\?[0-9;]*c`,"g")];function hy(e){let t=e;for(let n of WA)t=t.replace(n,"");return t}var by={list:lg,create:pg,update:dg,remove:gg,webSocketUrl:mg};async function C(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await E(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await o.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!o.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${o.status}`);return a}async function KA(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return C(e,`/beeuni/tasks${r}`)}async function HA(e,t){return C(e,`/beeuni/tasks/${encodeURIComponent(t)}`)}async function VA(e,t){return C(e,`/beeuni/tasks/${encodeURIComponent(t)}/events`)}async function zA(e,t){return C(e,`/beeuni/tasks/${encodeURIComponent(t)}/status`)}async function YA(e,t){return C(e,"/beeuni/tasks",{method:"POST",body:JSON.stringify(t)})}async function QA(e,t,n){return C(e,`/beeuni/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function JA(e,t){return C(e,`/beeuni/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function XA(e,t){return C(e,`/beeuni/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function ZA(e,t){return C(e,`/beeuni/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function ek(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return C(e,`/beeuni/tickets${n}`)}async function tk(e,t){return C(e,`/beeuni/tickets/${encodeURIComponent(t)}`)}async function nk(e,t){return C(e,`/beeuni/tickets/${encodeURIComponent(t)}/events`)}async function rk(e,t){return C(e,"/beeuni/tickets",{method:"POST",body:JSON.stringify(t)})}async function sk(e,t,n){return C(e,`/beeuni/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function ok(e,t,n){return C(e,`/beeuni/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function ik(e,t,n){return C(e,`/beeuni/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function ak(e,t,n){return C(e,`/beeuni/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function ck(e,t,n){return C(e,`/beeuni/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function uk(e,t){return C(e,`/beeuni/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function lk(e,t){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/columns`)}async function pk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function dk(e,t){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/fields`)}async function gk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function mk(e,t){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/templates`)}async function fk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function yk(e,t){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function hk(e,t){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/agents`)}async function bk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function _k(e,t,n,r){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function Pk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Sk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function xk(e,t,n=200){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function wk(e){return C(e,"/beeuni/projects")}async function vk(e,t){return C(e,`/beeuni/projects/${encodeURIComponent(t)}`)}async function Ak(e,t){return C(e,`/beeuni/projects/by-session/${encodeURIComponent(t)}`)}async function kk(e,t){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/sessions`)}async function Rk(e,t){return C(e,`/beeuni/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Ck(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function Ik(e,t,n="all"){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function Tk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function Ek(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function Mk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function Ok(e,t,n,r){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function Dk(e,t,n,r){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function jk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function $k(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Uk(e,t){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials`)}async function Fk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function Lk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function Bk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function Nk(e,t,n){return C(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var qk=1e4,Gk={retryOnAuthError:!1};function Ot(e,t,n){return C(e,t,{signal:AbortSignal.timeout(qk),...n},Gk)}async function Wk(e,t=!1){return(await Ot(e,`/beeuni/services${t?"?all=true":""}`)).services??[]}async function Kk(e){return(await Ot(e,"/beeuni/services/templates")).templates??[]}async function Hk(e,t){return(await Ot(e,`/beeuni/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function Vk(e,t,n){let r=n==="delete",s=r?`/beeuni/services/${encodeURIComponent(t)}`:`/beeuni/services/${encodeURIComponent(t)}/${n}`;return Ot(e,s,{method:r?"DELETE":"POST"})}async function zk(e,t){return Ot(e,`/beeuni/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function Yk(e,t){return Ot(e,"/beeuni/services/register",{method:"POST",body:JSON.stringify(t)})}var Oe=new Map,Qk=256,Dt=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function He(){let e=Me();if(!e)throw new Dt;return be(e)}function be(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Oe.get(e);if(t)return Oe.delete(e),Oe.set(e,t),t;if(!fr())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureBeeuni()/createBeeuni() before talking to a sandbox runtime.");let n=On({baseUrl:e,fetch:E,eventTransport:dy});return Oe.set(e,n),Oe.size>Qk&&Oe.delete(Oe.keys().next().value),n}function Jk(e){Oe.delete(e)}function Xk(){Oe.clear()}var Ss=new Map;function Zk(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=Ss.get(e);if(t)return t;let n=On({baseUrl:e,fetch});return Ss.set(e,n),n}function eR(e){Ss.delete(e)}function tR(){Ss.clear()}async function nR(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n?.error||n?.message||t||e.statusText||`HTTP ${e.status}`}catch{return t||e.statusText||`HTTP ${e.status}`}}async function rR(e){let t=Me();if(!t)throw new b("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/beeuni/refresh":"/global/dispose",r=await E(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new b(`System reload failed (${r.status}): ${await nR(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new b(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(u){throw new b(`System reload returned malformed JSON from ${n}: ${u instanceof Error?u.message:String(u)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var _y="frontend";function xs(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${_y}] ${t}`,...n?[n]:[]);try{He().app.log({service:_y,level:e,message:t,extra:n})}catch{}}var Ve={debug:(e,t)=>xs("debug",e,t),info:(e,t)=>xs("info",e,t),warn:(e,t)=>xs("warn",e,t),error:(e,t)=>xs("error",e,t)};function Py(e){return{type:"heartbeat-gap",gapMs:e}}function Sy(e){switch(e.type){case"message.updated":return{type:"message.updated",sessionID:e.properties.sessionID,message:e.properties.info};case"message.removed":return{type:"message.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID};case"message.part.updated":return{type:"message.part.updated",sessionID:e.properties.sessionID,part:e.properties.part};case"message.part.removed":return{type:"message.part.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID,partID:e.properties.partID};case"session.status":return{type:"session.status",sessionID:e.properties.sessionID,status:e.properties.status};case"session.idle":return{type:"session.idle",sessionID:e.properties.sessionID};case"session.error":return{type:"session.error",sessionID:e.properties.sessionID,error:e.properties.error};case"question.asked":return{type:"question.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,questions:e.properties.questions,tool:e.properties.tool};case"question.replied":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"replied",answers:e.properties.answers};case"question.rejected":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"rejected"};case"permission.asked":return{type:"permission.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,permission:e.properties.permission,patterns:e.properties.patterns,tool:e.properties.tool};case"permission.replied":return{type:"permission.replied",sessionID:e.properties.sessionID,requestID:e.properties.requestID,reply:e.properties.reply};case"todo.updated":return{type:"todo.updated",sessionID:e.properties.sessionID,todos:e.properties.todos};case"server.connected":return{type:"connection",status:"connected"};default:return null}}var sR={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},oR=16,iR=8,aR=6e4,cR=5e3,uR=250,lR=1e3,pR=3e4,dR=5,gR=1e4,mR=4,fR=.5,yR=3e3,hR=3e4,bR=2e4,_R=2e3,PR=8;function SR(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function xR(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function xy(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}var jn=new WeakMap;function wR(e,t,n){let r=t.timers??sR,s=t.connectTimeoutMs??bR,o=t.heartbeatTimeoutMs??aR,i=t.maxConsecutiveHardFailures??PR,a=new AbortController;function u(_,...S){for(let M of n){let w=_(M);if(w)try{w(...S)}catch(P){console.warn("[opencode-events] subscriber handler threw, skipping",P)}}}let p=null,d=!1,g=_=>{p!==_&&(p=_,_&&u(S=>S.onConnectionChange,_))},m=r.now(),f=null,h=[],x,D=0,j=new Map,L=()=>{if(x&&r.clearTimeout(x),x=void 0,h.length===0)return;let _=h;h=[],j.clear(),D=r.now(),m=r.now();for(let S of _)S&&u(M=>M.onEvent,S.event)},y=()=>{if(x)return;let _=r.now()-D;x=r.setTimeout(L,Math.max(0,oR-_))};return(async()=>{let _=0,S=0,M=0;for(;!a.signal.aborted;){let w=!1,P=!1,A,I,T=null,B=r.now(),$=new AbortController;g("connecting");let N=xy(a.signal);N.promise.then(()=>$.abort());try{let ie=await new Promise((ht,et)=>{let ne=!1;I=r.setTimeout(()=>{ne||(ne=!0,Ve.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:s}),$.abort(),et(new Error(`SSE connect timed out after ${s}ms`)))},s),e.global.event({signal:$.signal,sseDefaultRetryDelay:yR,sseMaxRetryDelay:hR,sseMaxRetryAttempts:1}).then(ve=>{ne||(ne=!0,r.clearTimeout(I),ht(ve))},ve=>{ne||(ne=!0,r.clearTimeout(I),et(ve))})}),{stream:en}=ie;if(f){let ht=r.now()-f.lastActivityAt,et=f.eventful;f=null,(et||ht>cR)&&u(ne=>ne.onGapRehydrate,ht)}m=r.now();let Ze=()=>{r.clearTimeout(A),A=r.setTimeout(()=>{Ve.warn("SSE heartbeat timeout, forcing reconnect"),$.abort()},o)};Ze();let dr=r.now(),gP=en[Symbol.asyncIterator]();for(;!$.signal.aborted;){let ht=gP.next().then(Ae=>({kind:"next",result:Ae}),Ae=>({kind:"error",error:Ae})),et=xy($.signal),ne=await Promise.race([ht,et.promise.then(()=>({kind:"aborted"}))]);if(et.cleanup(),ne.kind==="aborted")break;if(ne.kind==="error")throw ne.error;if(ne.result.done)break;g("open"),Ze();let ve=ne.result.value,bt=ve&&typeof ve=="object"&&"payload"in ve?ve.payload:ve;if(!bt?.type)continue;bt.type!=="server.connected"&&(w=!0);let no=xR(h[h.length-1]?.event,bt);if(no)h[h.length-1]={type:no.type,event:no};else{let Ae=SR(bt);if(Ae){let Tm=j.get(Ae);Tm!==void 0&&(h[Tm]=void 0),j.set(Ae,h.length)}h.push({type:bt.type,event:bt})}y(),!(r.now()-dr<iR)&&(dr=r.now(),await new Promise(Ae=>r.setTimeout(Ae,0)))}P=w}catch(ie){if(a.signal.aborted)break;T=ie;let en=String(ie),Ze=_t(ie)||_t(ie?.cause);if(Ve.error("SSE event stream error",{error:en,retryCount:_,isAuthError:Ze}),Ze)try{Ir(),await Cr(),Ve.info("SSE: refreshed auth token after auth error")}catch(dr){Ve.error("SSE: failed to refresh auth token",{error:String(dr)})}}finally{r.clearTimeout(A),r.clearTimeout(I),$.abort(),N.cleanup(),L()}if(a.signal.aborted)break;let q=r.now()-B,de=T?.cause?.status;if(S=!w&&(typeof de=="number"&&de>=400||q<_R)?S+1:0,S>=i){Ve.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:S,lastError:String(T)}),p=null,d=!0,u(ie=>ie.onParked,{consecutiveFailures:S,lastError:T});break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||w},M=P&&q<gR?M+1:0;let yt=P&&M<=mR;yt?_=0:(_++,_>1&&Ve.warn("SSE event stream reconnecting",{retryCount:_}));let xe=yt?uR:Math.min(lR*2**Math.min(_-1,dR),pR),we=Math.round(xe*(1+fR*(r.random?.()??0)));await new Promise(ie=>{let en=r.setTimeout(ie,we),Ze=()=>{r.clearTimeout(en),ie()};a.signal.addEventListener("abort",Ze,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),x&&r.clearTimeout(x)}}}function ws(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?be(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s},u=jn.get(i);if(u?.isParked()&&(jn.delete(i),u=void 0),!u)u=wR(i,e,new Set([a])),jn.set(i,u);else{u.subscribers.add(a);let f=u.connectionState();f&&s?.(f)}let p=u,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),jn.get(i)===p&&jn.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function wy(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return be(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return be(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return be(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return ws({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Ry(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new b(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Ut(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function Y(e){let t=(e??Me()).trim();if(!t)throw new Dt;return t}async function As(e,t){let n=await E(`${Y(t)}${e}`);if(!n.ok)throw new b(await Ut(n),{status:n.status,response:n});return n.json()}var ks=["/workspace","/tmp","/home","/opt"],vR=ks.filter(e=>e!=="/workspace");function hg(e){return ks.some(t=>e===t||e.startsWith(`${t}/`))}function Ft(e){return hg(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function ze(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(vR.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var bg=ze;async function Lt(e,t){let n=Y(t),r=ze(e)||".";return(await As(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function Bt(e,t){let n=Y(t),r=ze(e),s=await E(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!s.ok)throw new b(await Ut(s),{status:s.status,response:s});return s.json()}async function AR(e,t,n){let r=Y(n),s=ze(e),o=await E(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new b(await Ut(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new b("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var kR=8,vs=0,Cy=[];async function RR(){if(vs<kR){vs++;return}await new Promise(e=>Cy.push(e)),vs++}function CR(){vs--,Cy.shift()?.()}function Iy(e,t){let n=Y(t);return gn(`${n}/file/raw?path=${encodeURIComponent(ze(e))}`)}async function Nt(e,t){await RR();try{let n=Y(t);try{return await AR(e,void 0,n)}catch{}let r=await Bt(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{CR()}}async function Fn(e){return As("/file/status",Y(e))}async function Ln(e,t,n){let r=Y(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),As(`/find/file?${s.toString()}`,r)}async function Bn(e,t){let n=Y(t);return(await As(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var $n=[400,1200],IR=e=>e===408||e===429||e===502||e===503||e===504,vy=e=>new Promise(t=>setTimeout(t,e));function TR(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var fg=3e4,Ty=15*6e4,ER=256;function jt(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return fg;let t=fg+e/ER;return Math.min(Ty,Math.max(fg,Math.round(t)))}async function MR(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function Un(e,t){let n;for(let s=0;s<=$n.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,TR(a)||s===$n.length)break;await vy($n[s]);continue}if(o.ok)return o.json();let i=await MR(o);if(n=new b(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!IR(o.status)||s===$n.length)throw n;await vy($n[s])}if(n instanceof b)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new b(`Upload failed: ${r}`)}var yg=8*1024*1024;function OR(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new b(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Ay(e,t){try{e?.onProgress?.(t)}catch{}}function ky(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function DR(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function qt(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=Y(o),u=jt(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=yg){let f=await Un(()=>ky(e,t,p),h=>E(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:u}));return OR(f[0],e.size),Ay(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await Un(()=>ky(new Blob([],{type:e.type}),t,p),f=>E(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:jt(0)})))[0]?.path;if(!g)throw new b("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=DR(g);if(!m.name)throw new b(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=yg){let h=Math.min(e.size,f+yg),x=e.slice(f,h,e.type),D=await Un(()=>{let j=new FormData;return m.parent&&j.append("path",m.parent),j.append("filename",m.name),j.append("first",f===0?"true":"false"),j.append("offset",String(f)),j.append("file",x,m.name),j},j=>E(`${a}/file/append`,{method:"POST",body:j},{timeoutMs:jt(x.size)}));if(D.path!==g||D.size!==h)throw new b(`Upload verification failed for ${g}: expected ${h} bytes, received ${D.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Ay(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await gt(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function Ey(e,t,n){let r=Y(n);return Un(()=>{let s=new FormData;return t&&s.append("path",t),s.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),s},s=>E(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:jR}))}var jR=Ty;function $R(e,t,n){let r=Y(n),s=jt(t.size);return Un(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>E(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var $t=class extends b{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function Nn(e,t){let n=Y(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",u=Ft(`${a}/${i}`),p=[];try{p=await Lt(My(u),n)}catch(g){if(!(g instanceof b&&g.status===404))throw g}if(p.some(g=>g.name===Oy(u)))throw new $t(u);let d=await Dy(u,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function qn(e,t,n){let r=Y(n);return $R(t,await Nt(e,r),r)}function UR(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function My(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Oy(e){return e.slice(e.lastIndexOf("/")+1)}function FR(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function Gn(e,t,n){let r=Y(n),s=Ft(UR(e.trim()));return Dy(s,t,r,{overwrite:!0})}async function Dy(e,t,n,r){let s=Oy(e);if(!s)throw new b(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=My(e);await Gt(o,n).catch(()=>{});let i=FR(),a=await qt(t,o,`.${s}.beeuni-write-${i}`,n),u=a[0]?.path;if(!u)throw new b(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=Ft(u);try{await jy(p,e,n,r.overwrite)}catch(g){throw await gt(p,n).catch(()=>{}),!r.overwrite&&g instanceof b&&g.status===409?new $t(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function gt(e,t){let n=await E(`${Y(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Delete failed (${n.status}): ${await Ut(n)}`,{status:n.status,response:n});return n.json()}async function Gt(e,t){let n=await E(`${Y(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Mkdir failed (${n.status}): ${await Ut(n)}`,{status:n.status,response:n});return n.json()}async function Wn(e,t,n){return jy(e,t,Y(n),!0)}async function jy(e,t,n,r){let s=await E(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!s.ok)throw new b(`Rename failed (${s.status}): ${await Ut(s)}`,{status:s.status,response:s});return s.json()}async function _g(){return Ry(await He().project.current())}async function Rs(){return Ry(await He().global.health())}async function Pg(){try{return(await Rs()).healthy===!0}catch{return!1}}var $y={list:Lt,read:Bt,readBlob:Nt,status:Fn,findFiles:Ln,findText:Bn,upload:qt,write:Gn,create:Nn,copy:qn,remove:gt,mkdir:Gt,rename:Wn,currentProject:_g,health:Rs,isReachable:Pg,toDaemonPath:ze,toSandboxAbsolutePath:Ft,toWorkspaceRelative:bg};function Uy(e){return{list:async t=>Lt(t,(await e()).runtimeUrl),read:async t=>Bt(t,(await e()).runtimeUrl),readBlob:async t=>Nt(t,(await e()).runtimeUrl),status:async()=>Fn((await e()).runtimeUrl),findFiles:async(t,n)=>Ln(t,n,(await e()).runtimeUrl),findText:async t=>Bn(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>qt(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>Gn(t,n,(await e()).runtimeUrl),create:async t=>Nn(t,(await e()).runtimeUrl),copy:async(t,n)=>qn(t,n,(await e()).runtimeUrl),remove:async t=>gt(t,(await e()).runtimeUrl),mkdir:async t=>Gt(t,(await e()).runtimeUrl),rename:async(t,n)=>Wn(t,n,(await e()).runtimeUrl)}}function Fy(e){return{get:t=>bn(e.projectId,e.sessionId,t),presence:(t,n)=>c.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>wn(e.sessionId,{projectId:e.projectId}),update:t=>Qc(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),Jc(e.projectId,e.sessionId)),start:(...t)=>Le(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>yu(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Pn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Sn(e.projectId,e.sessionId)),configState:()=>Xc(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),Zc(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),eu(e.projectId,e.sessionId,...t)),setSharing:t=>Tc(e.projectId,e.sessionId,t),previews:()=>Dc(e.projectId,e.sessionId),participants:()=>Ec(e.projectId,e.sessionId),watch:()=>Mc(e.projectId,e.sessionId),setWatch:t=>Oc(e.projectId,e.sessionId,t),commit:t=>wc(e.projectId,e.sessionId,t),publicShares:{list:()=>jc(e.projectId,e.sessionId),create:(...t)=>$c(e.projectId,e.sessionId,...t),revoke:(...t)=>Uc(e.projectId,e.sessionId,...t)}}}function Ly(e){return{reminders:{list:()=>pp(e.projectId,e.sessionId),create:t=>dp(e.projectId,e.sessionId,t),update:(t,n)=>Qr(e.projectId,e.sessionId,t,n),remove:t=>Jr(e.projectId,e.sessionId,t)},audit:(t,n)=>Bc(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Vd(e.projectId,e.sessionId,t,n),read:(t,n)=>zd(`beeuni-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Nc(e.projectId,e.sessionId,t),messageAuthors:()=>ou(e.projectId,e.sessionId),modelUsage:()=>iu(e.projectId,e.sessionId),transcriptSync:t=>qc(e.projectId,e.sessionId,t),turn:()=>Gc(e.projectId,e.sessionId),prompts:{create:t=>_n(e.projectId,e.sessionId,t),list:()=>Wc(e.projectId,e.sessionId),remove:t=>Kc(e.projectId,e.sessionId,t),retry:t=>zc(e.projectId,e.sessionId,t),edit:(t,n)=>Hc(e.projectId,e.sessionId,t,n),interrupt:t=>Vc(e.projectId,e.sessionId,t),hold:t=>Yc(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function By(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var BR=["control_plane","provider_ingress","daemon","upstream_port"];function Sg(e){return typeof e=="string"&&BR.includes(e)?e:null}function xg(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.harness?e.harness.ready===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function wg(e,t){let n=(e===void 0?Me():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await E(`${n}/beeuni/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let i=o,a=Sg(r.headers.get("X-Beeuni-Proxy-Hop"))??Sg(o?.hop),u=Number(r.headers.get("X-Beeuni-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(u)&&u>0?u:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var Ny=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,qy=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,Gy=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,Wy=new Set([22,4096,parseInt(Te.BEEUNI_MASTER,10)]);function NR(e){return qy.test(e)}function Cs(e){if(!e)return"/";let t=e,n=t.indexOf("](");n!==-1&&(t=t.slice(0,n));let r=t.toLowerCase().indexOf("%5d(");return r!==-1&&(t=t.slice(0,r)),t?t.startsWith("/")?t:`/${t}`:"/"}function qR(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var GR=new Set(["'",'"',"`","<","(","["]),WR=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function KR(e){let t=0,n=e.length;for(;t<n&&(e[t]===" "||e[t]===" ");)t++;for(;n>t&&(e[n-1]===" "||e[n-1]===" ");)n--;for(;t<n&&GR.has(e[t]);)t++;for(;n>t&&WR.has(e[n-1]);)n--;return e.slice(t,n)}function HR(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var VR=/^\/proxy\/(\d{1,5})(\/.*)?$/,zR=/^\/(connectors|settings|dashboard|projects|agents|skills|tools|commands|support|changelog|files|p|browser|desktop|terminal|sessions|services|workspace|channels|scheduled-tasks|marketplace|templates|tunnel|admin|auth)(\/|$|\?)/;function Ky(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:zR.test(t.pathname)}catch{return!1}}function Hn(e){if(!e)return null;let t=KR(qR(e.trim())),n=Ag(t);if(n){let r=Cs(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(Te.BEEUNI_MASTER,10);if(s===i){let u=r.pathname.match(VR);if(u){let p=parseInt(u[1],10);if(p>=1&&p<=65535)return s=p,o=Cs(`${u[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=Cs(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=HR(e);return r&&r!==e?Hn(r):null}}function YR(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,i=o+r[0].length;t.some(([u,p])=>o>=u&&i<=p)||t.push([o,i])}return t}function QR(e,t){return t.some(([n,r])=>e>=n&&e<r)}function Hy(e){let t=[],n=new Set,r=YR(e);Ny.lastIndex=0;let s;for(;(s=Ny.exec(e))!==null;){let o=Hn(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:u}=o;a<1||a>65535||Wy.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:u,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:QR(s.index,r)}))}return t}function JR(e){return Hy(e).length>0}function XR(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function Vy(e){return e.trim().toLowerCase().split("_").join("-")}function zy(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function ZR(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let s=r.split("{port}").join(String(e)).split("{sandbox}").join(Vy(n.sandboxId));return`${zy(s)}${t}`}function Yy(e){return e.sandboxId.trim().length>0}function Ye(e,t,n){let r=Cs(t);if(!Yy(n))return Zy(e,r);let s=ZR(e,r,n);return s||(XR(n.apiBaseUrl)?`http://p${e}-${Vy(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${zy(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function eC(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return Ye(3211,`/open?path=/workspace/${r}`,t)}function Qy(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function tC(e){return`http://localhost:3211${Qy(e)}`}function Jy(){return"/health"}function nC(e){return Ye(3211,Jy(),e)}function rC(e,t){return Ye(e,"/",t)}function Xy(e){let t=Hn(e);return!(!t||Wy.has(t.port)||Ky(e))}function vg(e,t){if(!e)return e;let n=Hn(e);return n?Xy(n.originalUrl)?Ye(n.port,n.path,t):n.originalUrl:e}function Zy(e,t="/"){return`http://localhost:${e}${t}`}var eh=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function Ag(e){let t=e.match(qy);if(t)return{port:parseInt(t[1],10),sandboxId:t[2],backendPort:t[3]?parseInt(t[3],10):80,path:t[4]||"/"};let n=e.match(Gy);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(eh);if(r)try{let s=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(s.port,10)||(s.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function sC(e){try{let t=Ag(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function oC(e){return NR(e)||Gy.test(e)||eh.test(e)}function iC(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Kn="/web-proxy/";function aC(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Kn}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(Te.BEEUNI_MASTER,10);return`${Ye(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function cC(e){try{let t=new URL(e),n=t.pathname.indexOf(Kn);if(n===-1)return null;let s=t.pathname.slice(n+Kn.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],i=s[2],a=s[3]||"/";return`${o}://${i}${a}${t.search}${t.hash}`}catch{return null}}function uC(e){try{return new URL(e).pathname.includes(Kn)}catch{return e.includes(Kn)}}function lC(e){if(!e)return!1;let t=e.trim();return!!(/^https?:\/\/(?!localhost|127\.0\.0\.1)/i.test(t)||/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t))}function pC(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t)?`https://${t}`:null:null}function th(e){return{health:t=>wg(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>Ye(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>vg(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Fe(e.requireReady("sandboxPortUrl").sandboxId,t)}}function kg(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=Vf(e,t),{ensureReady:u,tryResolveReady:p,requireReady:d,forgetReady:g}=Xf(e,t,n),m={projectId:e,sessionId:t,ensureReady:u,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return s},set model(f){s=f},get agent(){return o},set agent(f){o=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...Fy(m),...Ly(m),...th(m),...ry(m),...ly(m),...wy(m),files:Uy(u),...ny(m),get runtime(){return be(d("runtime").runtimeUrl)}}}function nh(e){return{apps:{list:()=>qp(e),create:t=>Gp(e,t),get:t=>Xr(e,t),update:(...t)=>Wp(e,...t),access:{get:(...t)=>zp(e,...t),update:(...t)=>Qp(e,...t),session:(...t)=>Jp(e,...t),agents:t=>Yp(e,t)},remove:t=>Kp(e,t),token:t=>Hp(e,t),authEnv:t=>Vp(e,t),artifacts:{register:t=>Zr(e,t),uploadArchive:(...t)=>Xp(e,...t),finalize:(...t)=>es(e,...t)},deployments:{create:(...t)=>Zp(e,...t),list:t=>ed(e,t),get:(...t)=>td(e,...t),logs:(...t)=>nd(e,...t),remove:(...t)=>od(e,...t)},start:t=>rd(e,t),stop:t=>sd(e,t),rollback:(...t)=>id(e,...t),machines:{list:t=>ad(e,t),start:(t,n)=>ud(e,t,n),stop:(t,n)=>ld(e,t,n),restart:(t,n)=>pd(e,t,n),destroy:(t,n)=>dd(e,t,n)},scale:(t,n)=>gd(e,t,n),exec:(...t)=>md(e,...t),volumes:{list:t=>fd(e,t),create:(...t)=>yd(e,...t),update:(...t)=>hd(e,...t),destroy:(...t)=>bd(e,...t),snapshots:(...t)=>_d(e,...t),snapshot:(...t)=>Pd(e,...t),restore:(...t)=>Sd(e,...t),fork:(...t)=>xd(e,...t)}}}}function rh(e){return{list:()=>wi(e),invite:(...t)=>ki(e,...t),update:(...t)=>vi(e,...t),revoke:t=>Ai(e,t),pendingInvites:()=>Ri(e),resendInvite:(...t)=>Ii(e,...t),revokeInvite:(...t)=>Ci(e,...t),requests:()=>Pi(e),approveRequest:(...t)=>Si(e,...t),rejectRequest:(...t)=>xi(e,...t),groupGrants:()=>Ti(e),attachGroupGrant:(...t)=>Ei(e,...t),updateGroupGrant:(...t)=>Mi(e,...t),detachGroupGrant:t=>Oi(e,t),resourceGrants:{list:()=>Di(e),create:t=>ji(e,t),remove:t=>$i(e,t)}}}function sh(e){return{tokens:{list:()=>Sp(e),create:t=>xp(e,t),revoke:t=>wp(e,t)},setupLinks:{requestSecret:t=>Mp(e,t),requestConnector:t=>Op(e,t)},validateManifest:t=>Jo(e,t),gitToken:()=>Xo(e),agentIdentities:()=>jl(e),secrets:{list:()=>Bi(e),upsert:t=>Ni(e,t),setStrategy:(...t)=>qi(e,...t),broker:(...t)=>Gi(e,...t),remove:t=>Vi(e,t),setPersonal:(...t)=>zi(e,...t),removePersonal:t=>Yi(e,t),setGitCredential:t=>Hi(e,t),listProviderOAuth:()=>Wi(e),startProviderOAuth:(...t)=>kr(e,...t),pollProviderOAuth:(...t)=>Rr(e,...t),removeProviderOAuth:t=>Ki(e,t)},access:rh(e)}}function oh(e){return{list:()=>ua(e),listAll:()=>la(e),reconcile:(...t)=>pa(e,...t),reconcileMember:(...t)=>da(e,...t),updateCredential:(...t)=>ga(e,...t),revoke:(...t)=>ma(e,...t),activate:(...t)=>fa(e,...t),setDefault:(...t)=>ya(e,...t),rename:(...t)=>ha(e,...t),share:(...t)=>_a(e,...t),addComputer:(...t)=>ba(e,...t),pipedreamConnect:(...t)=>Pa(e,...t),pipedreamFinalize:(...t)=>Sa(e,...t)}}function Is(e){return{catalog:t=>wt(e,t),tools:()=>Er(e),search:(...t)=>ca(e,...t),describe:(...t)=>Mr(e,...t),call:(...t)=>ot(e,...t),callAction:(t,n,r,s)=>ot(e,`${t}.${n}`,r,s),accounts:(...t)=>Or(e,...t),uploadAttachment:(...t)=>Dr(e,...t)}}function Rg(e,t){return{slug:t,run:(r,s,o)=>Lr(e,t,r,s,o),call:(r,s,o)=>ot(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?Mr(e,`${t}.${r}`):(await wt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>Or(e,t),paginate:(r,s,o)=>qa(e,t,r,s,o),uploadAttachment:(r,s)=>Dr(e,r,{...s,connector:t})}}var dC=100,gC=0,mC=new Set(["attachment_size_mismatch","attachment_failed"]),ih=()=>new b("Attachment expired. Attach the file again.",{code:"attachment_expired"});function ah(e){if(!e||typeof e.attachment_id!="string"||!e.attachment_id||typeof e.filename!="string"||!e.filename||typeof e.mime!="string"||!e.mime||!Number.isSafeInteger(e.size)||e.size<=0||e.size>52428800||!Number.isFinite(Date.parse(e.expires_at))||Date.parse(e.expires_at)<=Date.now())throw new Error("Attachment metadata is invalid or expired. Attach the file again.");return{attachment_id:e.attachment_id,filename:e.filename,mime:e.mime,size:e.size,expires_at:e.expires_at}}function Cg(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,i=0,a=!1,u,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,_){y.removalDeleted||(y.removalDeleted=!0,vt(e,_).catch(()=>{}))}function m(){u&&clearTimeout(u);let y=d().map(({item:S})=>S);(y.length!==p.attachments.length||y.some((S,M)=>S!==p.attachments[M]))&&(p={attachments:y});let _=Math.min(...y.filter(S=>S.status==="ready").map(S=>Date.parse(S.attachment.expires_at)));Number.isFinite(_)&&!a&&(u=setTimeout(()=>{for(let S of d())S.item.status==="ready"&&Date.parse(S.item.attachment.expires_at)<=Date.now()&&(S.item={...S.item,status:"error",error:ih()});m()},Math.min(2147483647,Math.max(0,_-Date.now()))),typeof u=="object"&&"unref"in u&&u.unref());for(let S of s)S();for(let S of[...o])S()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(y){f();let _=d();if(_.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(M=>!Number.isSafeInteger(M)||M<=0||M>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(_.reduce((M,w)=>M+w.item.size,0)+y.reduce((M,w)=>M+w,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function x(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let _=y.item.file;i++;let S=++y.generation,M=new AbortController;y.abort=M,y.item={...y.item,status:"uploading",error:void 0};let w=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===S,P,A=0,I,T=()=>{I=void 0,!(!w()||y.item.status!=="uploading"||P===void 0)&&(y.item={...y.item,receivedBytes:P},P=void 0,A=Date.now(),m())},B=$=>Math.floor($*100/y.item.size);yn(e,_,{resume:y.upload,signal:M.signal,onUpload:$=>{y.upload=$,y.removed&&(M.abort(),g(y,$.attachment_id))},onProgress:$=>{if(!w()||B($)===B(y.item.receivedBytes)||(P=$,I))return;let N=A+dC-Date.now();if(N<=0)return T();I=setTimeout(T,N),typeof I=="object"&&"unref"in I&&I.unref()},onProcessing:()=>{I&&clearTimeout(I),I=void 0,P=void 0,w()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then($=>{w()&&(y.item={...y.item,status:"ready",attachment:ah($),receivedBytes:$.size})}).catch($=>{$ instanceof b&&mC.has($.code??"")&&(y.upload=void 0),w()&&(y.item={...y.item,status:$ instanceof b&&$.code==="ABORTED"?"aborted":"error",error:$ instanceof Error?$:new Error(String($))})}).finally(()=>{i--,I&&clearTimeout(I),y.abort===M&&(y.abort=void 0),m(),x()})}m()}function D(y){h(y.map(S=>S.size));let _=y.map(S=>{let M=`attachment-${++gC}`;return r.set(M,{generation:0,item:{id:M,file:S,filename:S.name,mime:S.type||"application/octet-stream",size:S.size,status:"pending",receivedBytes:0}}),M});return m(),x(),_}function j(y){let _=r.get(y);!_||_.item.status==="ready"||(_.generation++,_.abort?.abort(),_.item={..._.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function L(y,{signal:_}={}){let S=[...y];return new Promise((M,w)=>{let P=()=>{o.delete(T),_?.removeEventListener("abort",I)},A=B=>{P(),w(B)},I=()=>A(me()),T=()=>{let B=!1;for(let N of S){let q=r.get(N);if(!q)return A(new Error("Attachment was removed before it was sent"));if(a&&!q.handedOff)return A(new Error("Attachment controller is disposed"));if(q.item.status==="error"||q.item.status==="aborted")return A(q.item.error??new Error("Attachment upload failed"));q.item.status!=="ready"&&(B=!0)}if(B)return;let $;try{$=S.map(N=>{let q=ah(r.get(N).item.attachment);return{type:"file",attachment_id:q.attachment_id,filename:q.filename,mime:q.mime}})}catch(N){return A(N instanceof Error?N:new Error(String(N)))}P(),M($)};if(_?.aborted)return I();o.add(T),_?.addEventListener("abort",I,{once:!0}),T()})}return{add:y=>D([y])[0],addMany:D,retry(y){let _=r.get(y);if(_?.handedOff||f(),!(!_||_.item.status==="ready"||_.item.status==="uploading"||_.item.status==="processing"||_.item.status==="pending")){if(!_.item.file||_.upload&&Date.parse(_.upload.expires_at)<=Date.now())throw ih();_.item={..._.item,status:"pending",error:void 0},x()}},async remove(y){let _=r.get(y);if(!_)return;_.removed=!0,_.generation++,r.delete(y);let S=_.upload?.attachment_id??_.item.attachment?.attachment_id;S&&_.abort?.abort(),m(),x(),S&&g(_,S)},abort:j,submit(y){if(!a){for(let _ of y){let S=r.get(_);S&&(S.handedOff=!0)}m()}},reclaim(y){if(!a){for(let _ of y){let S=r.get(_);S&&(S.handedOff=!1)}m()}},whenReady:L,forget(y=d().map(_=>_.item.id)){for(let _ of y){let S=r.get(_);S&&(S.generation++,S.abort?.abort(),r.delete(_))}m(),x()},dispose(){if(!a){a=!0,u&&clearTimeout(u);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let _=y.upload?.attachment_id??y.item.attachment?.attachment_id;_&&e&&vt(e,_).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(y){return s.add(y),()=>{s.delete(y)}}}}function ch(e){return{attachments:{upload:(...t)=>yn(e,...t),delete:(...t)=>vt(e,...t),createController:t=>Cg(e,t)},get:t=>sn(e,t),detail:()=>on(e),skills:{create:(...t)=>ii(e,...t)},audit:t=>kp(e,t),update:t=>un(e,t),archive:()=>ln(e),llmCatalog:()=>an(e),modelPicker:()=>cn(e),modelAccess:()=>vn(e),setModelAccess:t=>An(e,t),sandboxHealth:()=>dn(e),onboardingComplete:(...t)=>oi(e,...t)}}function uh(e){return{sessions:{list:t=>it(e,t),listPage:t=>Ic(e,t),create:t=>at(e,t),ensureWarm:()=>Fc(e),claimWarm:t=>Lc(e,t)},review:{list:t=>ep(e,t),get:t=>tp(e,t),submit:t=>np(e,t),act:(...t)=>rp(e,...t),bulkAct:t=>sp(e,t)},approvals:{list:t=>Ui(e,t),resolve:(...t)=>Li(e,...t),sessionsNeedingInput:t=>Fi(e,t)}}}function lh(e){return{files:{list:t=>ec(e,t),listDirectory:t=>tc(e,t),read:(t,n)=>rc(e,t,n),search:(...t)=>nc(e,...t),archive:(...t)=>sc(e,...t),archiveRequest:(...t)=>oc(e,...t),history:(...t)=>dc(e,...t)},git:{commits:()=>uc(e),commit:t=>lc(e,t),commitDiff:t=>pc(e,t),branches:()=>cc(e),versionDiff:(...t)=>gc(e,...t),inviteCollaborator:(...t)=>Qo(e,...t)},changeRequests:{list:()=>mc(e),get:t=>fc(e,t),update:(...t)=>vc(e,...t),diff:t=>yc(e,t),mergePreview:t=>hc(e,t),open:(...t)=>bc(e,...t),merge:(...t)=>_c(e,...t),close:(...t)=>Pc(e,...t),reopen:(...t)=>Sc(e,...t),requestChanges:(...t)=>xc(e,...t)},...uh(e)}}function ph(e){return{policies:{list:()=>Ga(e),set:(...t)=>Wa(e,...t)},reminders:{list:()=>fp(e),updateMany:(...t)=>gp(e,...t),removeMany:(...t)=>mp(e,...t)},triggers:{list:()=>au(e),eventApps:()=>mu(e),eventTypes:(...t)=>gu(e,...t),create:(...t)=>cu(e,...t),update:(...t)=>uu(e,...t),remove:(...t)=>lu(e,...t),fire:(...t)=>du(e,...t),setActivation:(...t)=>pu(e,...t)},...lh(e)}}function dh(e,t){return{connectors:{...Is(e),list:()=>xa(e),config:(...n)=>Ia(e,...n),create:(...n)=>Ma(e,...n),remove:(...n)=>Da(e,...n),sync:()=>wa(e),auth:{discover:(...n)=>Oa(e,...n)},setName:(...n)=>Ta(e,...n),setCredentialMode:(...n)=>va(e,...n),setAuthorizationStrategy:(...n)=>Aa(e,...n),setCredential:(...n)=>La(e,...n),deleteCredential:(...n)=>Ba(e,...n),setSensitive:(...n)=>ka(e,...n),connections:t,policies:{get:(...n)=>Ra(e,...n),set:(...n)=>Ca(e,...n)},pipedream:{listApps:(...n)=>ja(e,...n),listSections:(...n)=>$a(e,...n),connect:(...n)=>Ea(e,...n),finalize:(...n)=>Na(e,...n)},discover:{list:(...n)=>jr(e,...n),sections:(...n)=>Ua(e,...n),detail:(...n)=>$r(e,...n)}},...ph(e)}}function gh(e){return{gateway:{logs:t=>pl(e,t),log:t=>dl(e,t),overview:t=>gl(e,t),series:t=>ml(e,t),breakdown:t=>fl(e,t),sessions:t=>yl(e,t),errors:t=>hl(e,t),budgets:()=>bl(e),setBudget:t=>_l(e,t),deleteBudget:t=>Pl(e,t),keys:()=>Sl(e),createKey:t=>xl(e,t),revokeKey:t=>wl(e,t),routing:{get:()=>al(e),set:t=>cl(e,t),reset:()=>ul(e),preview:t=>ll(e,t)},playground:(t,n,r)=>vl(e,t,n,r)}}}function mh(e){return{modelDefaults:{get:()=>hu(e),set:t=>bu(e,t),clear:t=>_u(e,t)},setDefaultAgent:t=>xu(e,t),sandbox:{list:()=>Za(e),snapshots:()=>Ha(e),rebuildSnapshot:t=>Va(e,t),fixWithAgent:()=>za(e),createTemplate:t=>Ya(e,t),updateTemplate:(...t)=>Qa(e,...t),removeTemplate:t=>Ja(e,t),buildTemplate:t=>Xa(e,t),setProvider:t=>si(e,t)},setAgentScope:(...t)=>Pu(e,...t)}}function fh(e){return{channels:{slack:{installation:()=>Hu(e),connect:t=>Vu(e,t),mode:()=>zu(e),completeInstall:t=>Yu(e,t),manifest:()=>Ju(e),disconnect:()=>Xu(e),getFile:t=>Zu(e,t),uploadFile:t=>el(e,t)},teams:{completeInstall:t=>Qu(e,t)},email:{installation:t=>nl(e,t),mode:()=>rl(e),connect:t=>sl(e,t),disconnect:t=>ol(e,t),updatePolicy:(...t)=>il(e,...t)}},updateFeatureFlag:(...t)=>ni(e,...t),updateExperimentalFeature:(...t)=>ri(e,...t),...mh(e)}}function fC(){return He()}var yh=null,hh=!1;function yC(e){let t=yh;yh=e,!(hh||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(hh=!0,console.warn("[beeuni] createBeeuni() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedBeeuni() from @beeuni/sdk/server.")))}function bh(e,t){t?.global!==!1&&yC(e),mr(e,t);let n=Hf(e),{auth:r,accounts:s,iam:o,accountInvites:i}=Nf(),{billing:a,sandboxShares:u}=Ff(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=Uf();function h(x){let D=oh(x);return{...ch(x),...nh(x),...sh(x),...dh(x,D),...gh(x),...fh(x),connector:j=>Rg(x,j),session:j=>kg(x,j,e,n)}}return{config:e,auth:r,accounts:s,providerConnections:{list:Od,saveApiKey:Dd,remove:jd,startOAuth:$d,pollOAuth:Ud,listProject:Fd,setProject:Ld},iam:o,accountInvites:i,projects:p,connectors:Is(),connector:x=>Rg(void 0,x),project:h,session:(x,D)=>kg(x,D,e,n),github:d,gitBackend:g,billing:a,sandboxShares:u,connectStatus:m,marketplace:f,notifications:{registerDeviceToken:vd,unregisterDeviceToken:Ad,list:kd,markRead:Rd,preferences:Cd,updatePreferences:Id,webPushPublicKey:Td,registerWebPushSubscription:Ed,unregisterWebPushSubscription:Md},validateToken:zo,runtime:fC}}function _h(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<16;r++)t[r]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(r=>r.toString(16).padStart(2,"0"));return`${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n.slice(10).join("")}`}function Ph(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Wt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function Sh(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function xh(e){if(Wt(e).length>0)return{state:e};let t=e.pending[0];if(!t)return{state:e};let n={...t,attempts:t.attempts+1};return{state:{...e,pending:[n,...e.pending.slice(1)],inFlightId:n.id,inFlightIds:[n.id]},claimed:n}}function wh(e){let t=Wt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function vh(e,t){let n=Wt(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function Ah(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function kh(e,t){return Wt(e).includes(t)?e:e.pending.some(n=>n.id===t)?{...e,pending:e.pending.filter(n=>n.id!==t)}:e.failed.some(n=>n.id===t)?{...e,failed:e.failed.filter(n=>n.id!==t)}:e}function Rh(e,t,n){return Wt(e).includes(t)||!e.pending.some(r=>r.id===t)?e:{...e,pending:e.pending.map(r=>r.id===t?{...r,text:n}:r)}}function Ch(e,t,n){let r=Wt(e);if(r.includes(t))return e;let s=e.pending.findIndex(p=>p.id===t);if(s===-1)return e;let o=r.length,i=Math.min(Math.max(n,o),e.pending.length-1);if(i===s)return e;let a=[...e.pending],[u]=a.splice(s,1);return a.splice(i,0,u),{...e,pending:a}}var Ig={thinking:!1,toolDetails:!0,assistantMetadata:!0};function hC(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function bC(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=t%60;return`${n}m ${r.toFixed(0)}s`}function _C(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
20
+ `))if(h.startsWith("data:"))f.push(h.replace(/^data:\s*/,""));else if(h.startsWith("id:"))m.id=h.replace(/^id:\s*/,"");else if(h.startsWith("retry:")){let S=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(S)||(m.retry=S)}f.length&&(m.data=f.join(`
21
+ `)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*nE(e,t,n){let r=e.eventTransport??Em(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal:s}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(o=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(c){if(n.onSseError?.(c),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(o*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function gr(e){let t=s=>(o,i)=>tE(e,ZT(e.baseUrl,s,o,i)),n=s=>o=>t(s)(void 0,o);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(s={})=>({stream:nE(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,s)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var w_=200;async function rE(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function Ot(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new x(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function v_(e){let t=e.runtimeUrl.replace(/\/$/,""),n=gr({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${s}${d.size?`?${d}`:""}`,m=S=>e.fetch(new Request(`${t}${S}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/beeuni/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/beeuni/opencode")),!f.ok)throw new x(`Reading the session transcript failed: ${await rE(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,w_),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await o(Math.min(r.limit-a.length,w_),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,s,o]=await Promise.all([n.session.status().then(i=>Ot(i,"Reading the session status failed")),n.permission.list().then(i=>Ot(i,"Reading permission requests failed")),n.question.list().then(i=>Ot(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{Ot(await n.permission.reply({requestID:r,reply:s,...o!==void 0?{message:o}:{}}),"Answering the permission request failed")},answerQuestion:async(r,s)=>{if(s===null){Ot(await n.question.reject({requestID:r}),"Dismissing the question failed");return}Ot(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let o=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof o?.model=="string"?o.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(s={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!s)throw new x("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return Ot(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function A_(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return v_({runtimeUrl:r,rootId:n,fetch:j})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,s)=>(await t()).answerPermission(n,r,s),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function k_(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await nu(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var nn=BigInt(4096),Qe=BigInt(0xffffffffffff),R_=Qe+BigInt(1),sE=R_/BigInt(2),pt=BigInt(3600*1e3)*nn,fo=120*1e3,C_=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,oE=/^msg_([0-9a-f]{12})/,T_="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Dt(e){let t=oE.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function rn(e){return BigInt(Math.trunc(e))*nn&Qe}function jt(e,t){let n=e-t&Qe;return n>=sE&&(n-=R_),n}function Im(e){let t=null;for(let n of e)n!=null&&(t===null||jt(n,t)>BigInt(0))&&(t=n);return t}function E_(e,t){let n=Dt(e);return n===null?!1:jt(n,rn(t))>pt}function I_(e,t){let n=t===void 0?null:rn(t);return M_(e,r=>n===null||jt(r,n)<=pt)}function M_(e,t){let n=[];for(let r of e){let s=Dt(r);s!==null&&t(s)&&n.push(s)}return Im(n)}function iE(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=T_[n%62])}return e}function Mm(e){let t=e.random,n=rn(e.nowMs-(e.backdateMs??fo)),r=e.newestKnownTime??null;if(r!==null){let o=jt(r,n);o>=BigInt(0)&&o<=pt&&(n=r+BigInt(1)&Qe)}let s="";if(t)for(let o=0;o<14;o++)s+=T_[Math.min(61,Math.floor(t()*62))];else s=iE();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function yo(e={}){let t=e.nowMs??Date.now(),n=rn(t-fo),r=M_(e.after??[],s=>{let o=jt(s,n);return o>=BigInt(0)&&o<=pt});return Mm({nowMs:t,newestKnownTime:r}).id}function O_(e){return{scope:()=>eu(e.projectId,e.sessionId),providerSecretPool:{list:()=>sc(e.projectId,e.sessionId),get:t=>rc(e.projectId,e.sessionId,t),set:(t,n)=>oc(e.projectId,e.sessionId,t,n)},rescope:t=>tu(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,s=n?.agent??e.agent,o=r&&s?{}:await e.persistedPromptDefaults(),i=r??o.model,a=s??o.agent,c=yo(),p=await Qn(e.projectId,e.sessionId,{clientMessageId:c,messageId:c,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new x("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var D_=async function*(e){let t=C().eventStreamTransport;if(!t){yield*Em(((s,o)=>j(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await as(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function Xe(){let e=__();return e||(C().billingEnabled??!1?"":gh())}async function Om(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Dm(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function jm(e){let t=Dm(e),n=await j(`${t}/env`);if(!n.ok)throw new Error(await Om(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Lm(e,t,n){let r=Dm(e),s=await j(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await Om(s,"Failed to save secret"))}async function $m(e,t){let n=Dm(e),r=await j(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Om(r,"Failed to delete secret"))}var j_={list:jm,set:Lm,delete:$m};async function L_(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await j(`${r}/beeuni/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}async function ho(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function mr(e){if(!e)throw new Error("[beeuni-pty] Server URL not ready \u2014 sandbox is still loading");return de(e)}async function Um(e){let t=mr(e),n=await j(`${t}/beeuni/pty`);if(!n.ok)throw new Error(await ho(n,"Failed to list terminals"));return n.json()}async function Fm(e,t){let n=mr(e),r=await j(`${n}/beeuni/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await ho(r,"Failed to create terminal"));return r.json()}async function Nm(e,t,n){let r=mr(e),s=await j(`${r}/beeuni/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await ho(s,"Failed to update terminal"));return s.json()}async function qm(e,t){let n=mr(e),r=await j(`${n}/beeuni/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await ho(r,"Failed to remove terminal"))}async function Gm(e,t,n){let r=mr(t),o=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),de(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/beeuni/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await st();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${o}${o.includes("?")?"&":"?"}${c}`:o}function $_(e){let t=e.reason.trim().toLowerCase();return t.includes("pty not found")?"replace":t.includes("pty exited")?"ended":e.hadError||t.includes("idle timeout")||t.includes("upstream error")||e.code!==1e3?"reconnect":"ended"}var dt="\x1B",B_="\x07",aE="\0",Bm=`(?:${B_}|${dt}\\\\)`,cE=[new RegExp(`${dt}\\]697;[^${B_}${dt}]*${Bm}`,"g"),new RegExp(`${aE}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${dt}\\][0-9]+;rgb:[0-9a-fA-F/]+${Bm}`,"g"),new RegExp(`${dt}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Bm}`,"g"),new RegExp(`${dt}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${dt}\\[\\d+;\\d+R`,"g"),new RegExp(`${dt}\\[\\?[0-9;]*c`,"g")];function U_(e){let t=e;for(let n of cE)t=t.replace(n,"");return t}var F_={list:Um,create:Fm,update:Nm,remove:qm,webSocketUrl:Gm};async function M(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await j(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await o.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!o.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${o.status}`);return a}async function lE(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return M(e,`/beeuni/tasks${r}`)}async function uE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}`)}async function pE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}/events`)}async function dE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}/status`)}async function gE(e,t){return M(e,"/beeuni/tasks",{method:"POST",body:JSON.stringify(t)})}async function mE(e,t,n){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function fE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function yE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function hE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function _E(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return M(e,`/beeuni/tickets${n}`)}async function bE(e,t){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}`)}async function SE(e,t){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}/events`)}async function PE(e,t){return M(e,"/beeuni/tickets",{method:"POST",body:JSON.stringify(t)})}async function xE(e,t,n){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function wE(e,t,n){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function vE(e,t,n){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function AE(e,t,n){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function kE(e,t,n){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function RE(e,t){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function CE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/columns`)}async function TE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function EE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/fields`)}async function IE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function ME(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/templates`)}async function OE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function DE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function jE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/agents`)}async function LE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function $E(e,t,n,r){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function BE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function UE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function FE(e,t,n=200){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function NE(e){return M(e,"/beeuni/projects")}async function qE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}`)}async function GE(e,t){return M(e,`/beeuni/projects/by-session/${encodeURIComponent(t)}`)}async function WE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/sessions`)}async function KE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function VE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function HE(e,t,n="all"){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function zE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function YE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function JE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function QE(e,t,n,r){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function XE(e,t,n,r){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function ZE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function eI(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function tI(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials`)}async function nI(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function rI(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function sI(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function oI(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var iI=1e4,aI={retryOnAuthError:!1};function sn(e,t,n){return M(e,t,{signal:AbortSignal.timeout(iI),...n},aI)}async function cI(e,t=!1){return(await sn(e,`/beeuni/services${t?"?all=true":""}`)).services??[]}async function lI(e){return(await sn(e,"/beeuni/services/templates")).templates??[]}async function uI(e,t){return(await sn(e,`/beeuni/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function pI(e,t,n){let r=n==="delete",s=r?`/beeuni/services/${encodeURIComponent(t)}`:`/beeuni/services/${encodeURIComponent(t)}/${n}`;return sn(e,s,{method:r?"DELETE":"POST"})}async function dI(e,t){return sn(e,`/beeuni/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function gI(e,t){return sn(e,"/beeuni/services/register",{method:"POST",body:JSON.stringify(t)})}var Ze=new Map,mI=256,on=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function gt(){let e=Xe();if(!e)throw new on;return Oe(e)}function Oe(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Ze.get(e);if(t)return Ze.delete(e),Ze.set(e,t),t;if(!Zr())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureBeeuni()/createBeeuni() before talking to a sandbox runtime.");let n=gr({baseUrl:e,fetch:j,eventTransport:D_});return Ze.set(e,n),Ze.size>mI&&Ze.delete(Ze.keys().next().value),n}function fI(e){Ze.delete(e)}function yI(){Ze.clear()}var _o=new Map;function hI(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=_o.get(e);if(t)return t;let n=gr({baseUrl:e,fetch});return _o.set(e,n),n}function _I(e){_o.delete(e)}function bI(){_o.clear()}async function SI(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n?.error||n?.message||t||e.statusText||`HTTP ${e.status}`}catch{return t||e.statusText||`HTTP ${e.status}`}}async function PI(e){let t=Xe();if(!t)throw new x("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/beeuni/refresh":"/global/dispose",r=await j(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new x(`System reload failed (${r.status}): ${await SI(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new x(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new x(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var N_="frontend";function bo(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${N_}] ${t}`,...n?[n]:[]);try{gt().app.log({service:N_,level:e,message:t,extra:n})}catch{}}var mt={debug:(e,t)=>bo("debug",e,t),info:(e,t)=>bo("info",e,t),warn:(e,t)=>bo("warn",e,t),error:(e,t)=>bo("error",e,t)};function q_(e){return{type:"heartbeat-gap",gapMs:e}}function G_(e){switch(e.type){case"message.updated":return{type:"message.updated",sessionID:e.properties.sessionID,message:e.properties.info};case"message.removed":return{type:"message.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID};case"message.part.updated":return{type:"message.part.updated",sessionID:e.properties.sessionID,part:e.properties.part};case"message.part.removed":return{type:"message.part.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID,partID:e.properties.partID};case"session.status":return{type:"session.status",sessionID:e.properties.sessionID,status:e.properties.status};case"session.idle":return{type:"session.idle",sessionID:e.properties.sessionID};case"session.error":return{type:"session.error",sessionID:e.properties.sessionID,error:e.properties.error};case"question.asked":return{type:"question.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,questions:e.properties.questions,tool:e.properties.tool};case"question.replied":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"replied",answers:e.properties.answers};case"question.rejected":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"rejected"};case"permission.asked":return{type:"permission.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,permission:e.properties.permission,patterns:e.properties.patterns,tool:e.properties.tool};case"permission.replied":return{type:"permission.replied",sessionID:e.properties.sessionID,requestID:e.properties.requestID,reply:e.properties.reply};case"todo.updated":return{type:"todo.updated",sessionID:e.properties.sessionID,todos:e.properties.todos};case"server.connected":return{type:"connection",status:"connected"};default:return null}}var xI={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},wI=16,vI=8,AI=6e4,kI=5e3,RI=250,CI=1e3,TI=3e4,EI=5,II=1e4,MI=4,OI=.5,DI=3e3,jI=3e4,LI=2e4,$I=2e3,BI=8;function UI(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function FI(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function W_(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}var fr=new WeakMap;function NI(e,t,n){let r=t.timers??xI,s=t.connectTimeoutMs??LI,o=t.heartbeatTimeoutMs??AI,i=t.maxConsecutiveHardFailures??BI,a=new AbortController;function c(y,..._){for(let R of n){let v=y(R);if(v)try{v(..._)}catch(b){console.warn("[opencode-events] subscriber handler threw, skipping",b)}}}let p=null,d=!1,g=y=>{p!==y&&(p=y,y&&c(_=>_.onConnectionChange,y))},m=r.now(),f=null,h=[],S,E=0,L=new Map,D=()=>{if(S&&r.clearTimeout(S),S=void 0,h.length===0)return;let y=h;h=[],L.clear(),E=r.now(),m=r.now();for(let _ of y)_&&c(R=>R.onEvent,_.event)},w=()=>{if(S)return;let y=r.now()-E;S=r.setTimeout(D,Math.max(0,wI-y))};return(async()=>{let y=0,_=0,R=0;for(;!a.signal.aborted;){let v=!1,b=!1,P,O,A=null,$=r.now(),N=new AbortController;g("connecting");let T=W_(a.signal);T.promise.then(()=>N.abort());try{let ne=await new Promise((Ut,xt)=>{let me=!1;O=r.setTimeout(()=>{me||(me=!0,mt.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:s}),N.abort(),xt(new Error(`SSE connect timed out after ${s}ms`)))},s),e.global.event({signal:N.signal,sseDefaultRetryDelay:DI,sseMaxRetryDelay:jI,sseMaxRetryAttempts:1}).then(Be=>{me||(me=!0,r.clearTimeout(O),Ut(Be))},Be=>{me||(me=!0,r.clearTimeout(O),xt(Be))})}),{stream:St}=ne;if(f){let Ut=r.now()-f.lastActivityAt,xt=f.eventful;f=null,(xt||Ut>kI)&&c(me=>me.onGapRehydrate,Ut)}m=r.now();let Pt=()=>{r.clearTimeout(P),P=r.setTimeout(()=>{mt.warn("SSE heartbeat timeout, forcing reconnect"),N.abort()},o)};Pt();let Jr=r.now(),zw=St[Symbol.asyncIterator]();for(;!N.signal.aborted;){let Ut=zw.next().then(Ue=>({kind:"next",result:Ue}),Ue=>({kind:"error",error:Ue})),xt=W_(N.signal),me=await Promise.race([Ut,xt.promise.then(()=>({kind:"aborted"}))]);if(xt.cleanup(),me.kind==="aborted")break;if(me.kind==="error")throw me.error;if(me.result.done)break;g("open"),Pt();let Be=me.result.value,Ft=Be&&typeof Be=="object"&&"payload"in Be?Be.payload:Be;if(!Ft?.type)continue;Ft.type!=="server.connected"&&(v=!0);let ci=FI(h[h.length-1]?.event,Ft);if(ci)h[h.length-1]={type:ci.type,event:ci};else{let Ue=UI(Ft);if(Ue){let ky=L.get(Ue);ky!==void 0&&(h[ky]=void 0),L.set(Ue,h.length)}h.push({type:Ft.type,event:Ft})}w(),!(r.now()-Jr<vI)&&(await new Promise(Ue=>r.setTimeout(Ue,0)),Jr=r.now())}b=v}catch(ne){if(a.signal.aborted)break;A=ne;let St=String(ne),Pt=Nt(ne)||Nt(ne?.cause);if(mt.error("SSE event stream error",{error:St,retryCount:y,isAuthError:Pt}),Pt)try{gs(),await st(),mt.info("SSE: refreshed auth token after auth error")}catch(Jr){mt.error("SSE: failed to refresh auth token",{error:String(Jr)})}}finally{r.clearTimeout(P),r.clearTimeout(O),N.abort(),T.cleanup(),D()}if(a.signal.aborted)break;let q=r.now()-$,W=A?.cause?.status;if(_=!v&&(typeof W=="number"&&W>=400||q<$I)?_+1:0,_>=i){mt.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:_,lastError:String(A)}),p=null,d=!0,c(ne=>ne.onParked,{consecutiveFailures:_,lastError:A});break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||v},R=b&&q<II?R+1:0;let Le=b&&R<=MI;Le?y=0:(y++,y>1&&mt.warn("SSE event stream reconnecting",{retryCount:y}));let Mn=Le?RI:Math.min(CI*2**Math.min(y-1,EI),TI),$e=Math.round(Mn*(1+OI*(r.random?.()??0)));await new Promise(ne=>{let St=r.setTimeout(ne,$e),Pt=()=>{r.clearTimeout(St),ne()};a.signal.addEventListener("abort",Pt,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),S&&r.clearTimeout(S)}}}function So(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?Oe(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s},c=fr.get(i);if(c?.isParked()&&(fr.delete(i),c=void 0),!c)c=NI(i,e,new Set([a])),fr.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&s?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),fr.get(i)===p&&fr.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function K_(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Oe(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Oe(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Oe(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return So({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Y_(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new x(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function ln(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function se(e){let t=(e??Xe()).trim();if(!t)throw new on;return t}async function xo(e,t){let n=await j(`${se(t)}${e}`);if(!n.ok)throw new x(await ln(n),{status:n.status,response:n});return n.json()}var wo=["/workspace","/tmp","/home","/opt"],qI=wo.filter(e=>e!=="/workspace");function Vm(e){return wo.some(t=>e===t||e.startsWith(`${t}/`))}function un(e){return Vm(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function ft(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(qI.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Hm=ft;async function pn(e,t){let n=se(t),r=ft(e)||".";return(await xo(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function dn(e,t){let n=se(t),r=ft(e),s=await j(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!s.ok)throw new x(await ln(s),{status:s.status,response:s});return s.json()}async function GI(e,t,n){let r=se(n),s=ft(e),o=await j(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new x(await ln(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new x("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var WI=8,Po=0,J_=[];async function KI(){if(Po<WI){Po++;return}await new Promise(e=>J_.push(e)),Po++}function VI(){Po--,J_.shift()?.()}function Q_(e,t){let n=se(t);return qn(`${n}/file/raw?path=${encodeURIComponent(ft(e))}`)}async function gn(e,t){await KI();try{let n=se(t);try{return await GI(e,void 0,n)}catch{}let r=await dn(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{VI()}}async function _r(e){return xo("/file/status",se(e))}async function br(e,t,n){let r=se(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),xo(`/find/file?${s.toString()}`,r)}async function Sr(e,t){let n=se(t);return(await xo(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var yr=[400,1200],HI=e=>e===408||e===429||e===502||e===503||e===504,V_=e=>new Promise(t=>setTimeout(t,e));function zI(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Wm=3e4,X_=15*6e4,YI=256;function an(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Wm;let t=Wm+e/YI;return Math.min(X_,Math.max(Wm,Math.round(t)))}async function JI(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function hr(e,t){let n;for(let s=0;s<=yr.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,zI(a)||s===yr.length)break;await V_(yr[s]);continue}if(o.ok)return o.json();let i=await JI(o);if(n=new x(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!HI(o.status)||s===yr.length)throw n;await V_(yr[s])}if(n instanceof x)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new x(`Upload failed: ${r}`)}var Km=8*1024*1024;function QI(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new x(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function H_(e,t){try{e?.onProgress?.(t)}catch{}}function z_(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function XI(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function mn(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=se(o),c=an(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Km){let f=await hr(()=>z_(e,t,p),h=>j(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return QI(f[0],e.size),H_(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await hr(()=>z_(new Blob([],{type:e.type}),t,p),f=>j(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:an(0)})))[0]?.path;if(!g)throw new x("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=XI(g);if(!m.name)throw new x(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=Km){let h=Math.min(e.size,f+Km),S=e.slice(f,h,e.type),E=await hr(()=>{let L=new FormData;return m.parent&&L.append("path",m.parent),L.append("filename",m.name),L.append("first",f===0?"true":"false"),L.append("offset",String(f)),L.append("file",S,m.name),L},L=>j(`${a}/file/append`,{method:"POST",body:L},{timeoutMs:an(S.size)}));if(E.path!==g||E.size!==h)throw new x(`Upload verification failed for ${g}: expected ${h} bytes, received ${E.size}`,{code:"UPLOAD_SIZE_MISMATCH"});H_(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await Lt(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function Z_(e,t,n){let r=se(n);return hr(()=>{let s=new FormData;return t&&s.append("path",t),s.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),s},s=>j(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:ZI}))}var ZI=X_;function eM(e,t,n){let r=se(n),s=an(t.size);return hr(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>j(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var cn=class extends x{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function Pr(e,t){let n=se(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",c=un(`${a}/${i}`),p=[];try{p=await pn(eb(c),n)}catch(g){if(!(g instanceof x&&g.status===404))throw g}if(p.some(g=>g.name===tb(c)))throw new cn(c);let d=await nb(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function xr(e,t,n){let r=se(n);return eM(t,await gn(e,r),r)}function tM(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function eb(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function tb(e){return e.slice(e.lastIndexOf("/")+1)}function nM(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function wr(e,t,n){let r=se(n),s=un(tM(e.trim()));return nb(s,t,r,{overwrite:!0})}async function nb(e,t,n,r){let s=tb(e);if(!s)throw new x(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=eb(e);await fn(o,n).catch(()=>{});let i=nM(),a=await mn(t,o,`.${s}.beeuni-write-${i}`,n),c=a[0]?.path;if(!c)throw new x(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=un(c);try{await rb(p,e,n,r.overwrite)}catch(g){throw await Lt(p,n).catch(()=>{}),!r.overwrite&&g instanceof x&&g.status===409?new cn(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Lt(e,t){let n=await j(`${se(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new x(`Delete failed (${n.status}): ${await ln(n)}`,{status:n.status,response:n});return n.json()}async function fn(e,t){let n=await j(`${se(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new x(`Mkdir failed (${n.status}): ${await ln(n)}`,{status:n.status,response:n});return n.json()}async function vr(e,t,n){return rb(e,t,se(n),!0)}async function rb(e,t,n,r){let s=await j(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!s.ok)throw new x(`Rename failed (${s.status}): ${await ln(s)}`,{status:s.status,response:s});return s.json()}async function zm(){return Y_(await gt().project.current())}async function vo(){return Y_(await gt().global.health())}async function Ym(){try{return(await vo()).healthy===!0}catch{return!1}}var sb={list:pn,read:dn,readBlob:gn,status:_r,findFiles:br,findText:Sr,upload:mn,write:wr,create:Pr,copy:xr,remove:Lt,mkdir:fn,rename:vr,currentProject:zm,health:vo,isReachable:Ym,toDaemonPath:ft,toSandboxAbsolutePath:un,toWorkspaceRelative:Hm};function ob(e){return{list:async t=>pn(t,(await e()).runtimeUrl),read:async t=>dn(t,(await e()).runtimeUrl),readBlob:async t=>gn(t,(await e()).runtimeUrl),status:async()=>_r((await e()).runtimeUrl),findFiles:async(t,n)=>br(t,n,(await e()).runtimeUrl),findText:async t=>Sr(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>mn(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>wr(t,n,(await e()).runtimeUrl),create:async t=>Pr(t,(await e()).runtimeUrl),copy:async(t,n)=>xr(t,n,(await e()).runtimeUrl),remove:async t=>Lt(t,(await e()).runtimeUrl),mkdir:async t=>fn(t,(await e()).runtimeUrl),rename:async(t,n)=>vr(t,n,(await e()).runtimeUrl)}}function ib(e){return{get:t=>zn(e.projectId,e.sessionId,t),presence:(t,n)=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>nr(e.sessionId,{projectId:e.projectId}),update:t=>Hl(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),zl(e.projectId,e.sessionId)),restore:()=>Jl(e.projectId,e.sessionId),recover:()=>Yl(e.projectId,e.sessionId),start:(...t)=>it(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>fu(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Xn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Zn(e.projectId,e.sessionId)),configState:()=>Ql(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),Xl(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),Zl(e.projectId,e.sessionId,...t)),setSharing:t=>kl(e.projectId,e.sessionId,t),previews:()=>Ml(e.projectId,e.sessionId),participants:()=>Rl(e.projectId,e.sessionId),watch:()=>Cl(e.projectId,e.sessionId),setWatch:t=>Tl(e.projectId,e.sessionId,t),setPinned:t=>El(e.projectId,e.sessionId,t),setArchived:t=>Il(e.projectId,e.sessionId,t),commit:t=>bl(e.projectId,e.sessionId,t),publicShares:{list:()=>Ol(e.projectId,e.sessionId),create:(...t)=>Dl(e.projectId,e.sessionId,...t),revoke:(...t)=>jl(e.projectId,e.sessionId,...t)}}}function ab(e){return{reminders:{list:()=>dd(e.projectId,e.sessionId),create:t=>gd(e.projectId,e.sessionId,t),update:(t,n)=>Ls(e.projectId,e.sessionId,t,n),remove:t=>$s(e.projectId,e.sessionId,t)},audit:(t,n)=>Bl(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Yg(e.projectId,e.sessionId,t,n),read:(t,n)=>Jg(`beeuni-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Ul(e.projectId,e.sessionId,t),messageAuthors:()=>ru(e.projectId,e.sessionId),modelUsage:()=>su(e.projectId,e.sessionId),transcriptSync:t=>Yn(e.projectId,e.sessionId,t),log:t=>Fl(e.projectId,e.sessionId,t),turn:()=>Jn(e.projectId,e.sessionId),prompts:{create:t=>Qn(e.projectId,e.sessionId,t),list:()=>Nl(e.projectId,e.sessionId),remove:t=>ql(e.projectId,e.sessionId,t),retry:t=>Kl(e.projectId,e.sessionId,t),edit:(t,n)=>Gl(e.projectId,e.sessionId,t,n),interrupt:t=>Wl(e.projectId,e.sessionId,t),hold:t=>Vl(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function cb(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var sM=["control_plane","provider_ingress","daemon","upstream_port"];function Jm(e){return typeof e=="string"&&sM.includes(e)?e:null}function Qm(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.harness?e.harness.ready===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function Xm(e,t){let n=(e===void 0?Xe():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await j(`${n}/beeuni/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let i=o,a=Jm(r.headers.get("X-Beeuni-Proxy-Hop"))??Jm(o?.hop),c=Number(r.headers.get("X-Beeuni-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var lb=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,ub=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,pb=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,db=new Set([22,4096,parseInt(Je.BEEUNI_MASTER,10)]);function oM(e){return ub.test(e)}function Ao(e){if(!e)return"/";let t=e,n=t.indexOf("](");n!==-1&&(t=t.slice(0,n));let r=t.toLowerCase().indexOf("%5d(");return r!==-1&&(t=t.slice(0,r)),t?t.startsWith("/")?t:`/${t}`:"/"}function iM(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var aM=new Set(["'",'"',"`","<","(","["]),cM=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function lM(e){let t=0,n=e.length;for(;t<n&&(e[t]===" "||e[t]===" ");)t++;for(;n>t&&(e[n-1]===" "||e[n-1]===" ");)n--;for(;t<n&&aM.has(e[t]);)t++;for(;n>t&&cM.has(e[n-1]);)n--;return e.slice(t,n)}function uM(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var pM=/^\/proxy\/(\d{1,5})(\/.*)?$/,dM=/^\/(connectors|settings|dashboard|projects|agents|skills|tools|commands|support|changelog|files|p|browser|desktop|terminal|sessions|services|workspace|channels|scheduled-tasks|marketplace|templates|tunnel|admin|auth)(\/|$|\?)/;function gb(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:dM.test(t.pathname)}catch{return!1}}function kr(e){if(!e)return null;let t=lM(iM(e.trim())),n=ef(t);if(n){let r=Ao(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(Je.BEEUNI_MASTER,10);if(s===i){let c=r.pathname.match(pM);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return s=p,o=Ao(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=Ao(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=uM(e);return r&&r!==e?kr(r):null}}function gM(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,i=o+r[0].length;t.some(([c,p])=>o>=c&&i<=p)||t.push([o,i])}return t}function mM(e,t){return t.some(([n,r])=>e>=n&&e<r)}function mb(e){let t=[],n=new Set,r=gM(e);lb.lastIndex=0;let s;for(;(s=lb.exec(e))!==null;){let o=kr(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:c}=o;a<1||a>65535||db.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:mM(s.index,r)}))}return t}function fM(e){return mb(e).length>0}function yM(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function fb(e){return e.trim().toLowerCase().split("_").join("-")}function yb(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function hM(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let s=r.split("{port}").join(String(e)).split("{sandbox}").join(fb(n.sandboxId));return`${yb(s)}${t}`}function hb(e){return e.sandboxId.trim().length>0}function yt(e,t,n){let r=Ao(t);if(!hb(n))return Pb(e,r);let s=hM(e,r,n);return s||(yM(n.apiBaseUrl)?`http://p${e}-${fb(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${yb(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function _M(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return yt(3211,`/open?path=/workspace/${r}`,t)}function _b(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function bM(e){return`http://localhost:3211${_b(e)}`}function bb(){return"/health"}function SM(e){return yt(3211,bb(),e)}function PM(e,t){return yt(e,"/",t)}function Sb(e){let t=kr(e);return!(!t||db.has(t.port)||gb(e))}function Zm(e,t){if(!e)return e;let n=kr(e);return n?Sb(n.originalUrl)?yt(n.port,n.path,t):n.originalUrl:e}function Pb(e,t="/"){return`http://localhost:${e}${t}`}var xb=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function ef(e){let t=e.match(ub);if(t)return{port:parseInt(t[1],10),sandboxId:t[2],backendPort:t[3]?parseInt(t[3],10):80,path:t[4]||"/"};let n=e.match(pb);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(xb);if(r)try{let s=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(s.port,10)||(s.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function xM(e){try{let t=ef(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function wM(e){return oM(e)||pb.test(e)||xb.test(e)}function vM(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Ar="/web-proxy/";function AM(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Ar}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(Je.BEEUNI_MASTER,10);return`${yt(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function kM(e){try{let t=new URL(e),n=t.pathname.indexOf(Ar);if(n===-1)return null;let s=t.pathname.slice(n+Ar.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],i=s[2],a=s[3]||"/";return`${o}://${i}${a}${t.search}${t.hash}`}catch{return null}}function RM(e){try{return new URL(e).pathname.includes(Ar)}catch{return e.includes(Ar)}}function CM(e){if(!e)return!1;let t=e.trim();return!!(/^https?:\/\/(?!localhost|127\.0\.0\.1)/i.test(t)||/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t))}function TM(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t)?`https://${t}`:null:null}function wb(e){return{health:t=>Xm(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>yt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>Zm(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ie(e.requireReady("sandboxPortUrl").sandboxId,t)}}function tf(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=h_(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=P_(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return s},set model(f){s=f},get agent(){return o},set agent(f){o=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...ib(m),...ab(m),...wb(m),...k_(m),...O_(m),...K_(m),files:ob(c),...A_(m),get runtime(){return Oe(d("runtime").runtimeUrl)}}}function vb(e){return{apps:{list:()=>Gd(e),create:t=>Wd(e,t),get:t=>Bs(e,t),update:(...t)=>Kd(e,...t),access:{get:(...t)=>Yd(e,...t),update:(...t)=>Qd(e,...t),session:(...t)=>Xd(e,...t),agents:t=>Jd(e,t)},remove:t=>Vd(e,t),token:t=>Hd(e,t),authEnv:t=>zd(e,t),artifacts:{register:t=>Us(e,t),uploadArchive:(...t)=>Zd(e,...t),finalize:(...t)=>Fs(e,...t)},deployments:{create:(...t)=>eg(e,...t),list:t=>tg(e,t),get:(...t)=>ng(e,...t),logs:(...t)=>rg(e,...t),remove:(...t)=>ig(e,...t)},start:t=>sg(e,t),stop:t=>og(e,t),rollback:(...t)=>ag(e,...t),machines:{list:t=>cg(e,t),start:(t,n)=>ug(e,t,n),stop:(t,n)=>pg(e,t,n),restart:(t,n)=>dg(e,t,n),destroy:(t,n)=>gg(e,t,n)},scale:(...t)=>mg(e,...t),exec:(...t)=>fg(e,...t),volumes:{list:t=>yg(e,t),create:(...t)=>hg(e,...t),update:(...t)=>_g(e,...t),destroy:(...t)=>bg(e,...t),snapshots:(...t)=>Sg(e,...t),snapshot:(...t)=>Pg(e,...t),restore:(...t)=>xg(e,...t),fork:(...t)=>wg(e,...t)}}}}function Ab(e){return{list:()=>Pa(e),invite:(...t)=>va(e,...t),update:(...t)=>xa(e,...t),revoke:t=>wa(e,t),pendingInvites:()=>Aa(e),resendInvite:(...t)=>Ra(e,...t),revokeInvite:(...t)=>ka(e,...t),requests:()=>_a(e),approveRequest:(...t)=>ba(e,...t),rejectRequest:(...t)=>Sa(e,...t),groupGrants:()=>Ca(e),attachGroupGrant:(...t)=>Ta(e,...t),updateGroupGrant:(...t)=>Ea(e,...t),detachGroupGrant:t=>Ia(e,t),resourceGrants:{list:()=>Ma(e),create:t=>Oa(e,t),remove:t=>Da(e,t)}}}function kb(e){return{tokens:{list:()=>xd(e),create:t=>wd(e,t),revoke:t=>vd(e,t)},setupLinks:{requestSecret:t=>Od(e,t),requestConnector:t=>Dd(e,t)},validateManifest:t=>Qi(e,t),gitToken:()=>Xi(e),agentIdentities:()=>Bp(e),secrets:{list:()=>Ba(e),upsert:t=>Ua(e,t),setStrategy:(...t)=>Fa(e,...t),broker:(...t)=>Na(e,...t),remove:t=>Ka(e,t),setPersonal:(...t)=>Va(e,...t),removePersonal:t=>Ha(e,t),setGitCredential:t=>Wa(e,t),listProviderOAuth:()=>qa(e),startProviderOAuth:(...t)=>ps(e,...t),pollProviderOAuth:(...t)=>ds(e,...t),removeProviderOAuth:t=>Ga(e,t)},access:Ab(e)}}function Rb(e){return{list:()=>ac(e),listAll:()=>cc(e),reconcile:(...t)=>lc(e,...t),reconcileMember:(...t)=>uc(e,...t),updateCredential:(...t)=>pc(e,...t),revoke:(...t)=>dc(e,...t),activate:(...t)=>gc(e,...t),setDefault:(...t)=>mc(e,...t),rename:(...t)=>fc(e,...t),share:(...t)=>hc(e,...t),addComputer:(...t)=>yc(e,...t),connect:(...t)=>_c(e,...t),finalize:(...t)=>bc(e,...t)}}function ko(e){return{catalog:t=>Vt(e,t),tools:()=>fs(e),search:(...t)=>ic(e,...t),describe:(...t)=>ys(e,...t),call:(...t)=>Rt(e,...t),callAction:(t,n,r,s)=>Rt(e,`${t}.${n}`,r,s),accounts:(...t)=>hs(e,...t),uploadAttachment:(...t)=>_s(e,...t)}}function nf(e,t){return{slug:t,run:(r,s,o)=>ws(e,t,r,s,o),call:(r,s,o)=>Rt(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?ys(e,`${t}.${r}`):(await Vt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>hs(e,t),paginate:(r,s,o)=>Bc(e,t,r,s,o),uploadAttachment:(r,s)=>_s(e,r,{...s,connector:t})}}var EM=100,Cb=0,IM=new Set(["attachment_size_mismatch","attachment_failed"]),Tb=()=>new x("Attachment expired. Attach the file again.",{code:"attachment_expired"});function rf(e){if(!e||typeof e.attachment_id!="string"||!e.attachment_id||typeof e.filename!="string"||!e.filename||typeof e.mime!="string"||!e.mime||!Number.isSafeInteger(e.size)||e.size<=0||e.size>52428800||!Number.isFinite(Date.parse(e.expires_at))||Date.parse(e.expires_at)<=Date.now())throw new Error("Attachment metadata is invalid or expired. Attach the file again.");return{attachment_id:e.attachment_id,filename:e.filename,mime:e.mime,size:e.size,expires_at:e.expires_at}}function sf(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,i=0,a=!1,c,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,_){y.removalDeleted||(y.removalDeleted=!0,Ht(e,_).catch(()=>{}))}function m(){c&&clearTimeout(c);let y=d().map(({item:R})=>R);(y.length!==p.attachments.length||y.some((R,v)=>R!==p.attachments[v]))&&(p={attachments:y});let _=Math.min(...y.filter(R=>R.status==="ready").map(R=>Date.parse(R.attachment.expires_at)));Number.isFinite(_)&&!a&&(c=setTimeout(()=>{for(let R of d())R.item.status==="ready"&&Date.parse(R.item.attachment.expires_at)<=Date.now()&&(R.item={...R.item,status:"error",error:Tb()});m()},Math.min(2147483647,Math.max(0,_-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let R of s)R();for(let R of[...o])R()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(y){f();let _=d();if(_.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(v=>!Number.isSafeInteger(v)||v<=0||v>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(_.reduce((v,b)=>v+b.item.size,0)+y.reduce((v,b)=>v+b,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function S(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let _=y.item.file;i++;let R=++y.generation,v=new AbortController;y.abort=v,y.item={...y.item,status:"uploading",error:void 0};let b=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===R,P,O=0,A,$=()=>{A=void 0,!(!b()||y.item.status!=="uploading"||P===void 0)&&(y.item={...y.item,receivedBytes:P},P=void 0,O=Date.now(),m())},N=T=>Math.floor(T*100/y.item.size);Kn(e,_,{resume:y.upload,signal:v.signal,onUpload:T=>{y.upload=T,y.removed&&(v.abort(),g(y,T.attachment_id))},onProgress:T=>{if(!b()||N(T)===N(y.item.receivedBytes)||(P=T,A))return;let q=O+EM-Date.now();if(q<=0)return $();A=setTimeout($,q),typeof A=="object"&&"unref"in A&&A.unref()},onProcessing:()=>{A&&clearTimeout(A),A=void 0,P=void 0,b()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then(T=>{b()&&(y.item={...y.item,status:"ready",attachment:rf(T),receivedBytes:T.size})}).catch(T=>{T instanceof x&&IM.has(T.code??"")&&(y.upload=void 0),b()&&(y.item={...y.item,status:T instanceof x&&T.code==="ABORTED"?"aborted":"error",error:T instanceof Error?T:new Error(String(T))})}).finally(()=>{i--,A&&clearTimeout(A),y.abort===v&&(y.abort=void 0),m(),S()})}m()}function E(y){h(y.map(R=>R.size));let _=y.map(R=>{let v=`attachment-${++Cb}`;return r.set(v,{generation:0,item:{id:v,file:R,filename:R.name,mime:R.type||"application/octet-stream",size:R.size,status:"pending",receivedBytes:0}}),v});return m(),S(),_}function L(y){let _=y.map(({attachment:v,file:b})=>{try{return{attachment:rf(v),file:b}}catch{return}});h(_.flatMap(v=>v?[v.attachment.size]:[]));let R=_.map(v=>{if(!v)return;let b=`attachment-${++Cb}`,{attachment:P,file:O}=v;return r.set(b,{generation:0,item:{id:b,...O?{file:O}:{},filename:P.filename,mime:P.mime,size:P.size,status:"ready",receivedBytes:P.size,attachment:P}}),b});return m(),R}function D(y){let _=r.get(y);!_||_.item.status==="ready"||(_.generation++,_.abort?.abort(),_.item={..._.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function w(y,{signal:_}={}){let R=[...y];return new Promise((v,b)=>{let P=()=>{o.delete($),_?.removeEventListener("abort",A)},O=N=>{P(),b(N)},A=()=>O(Re()),$=()=>{let N=!1;for(let q of R){let W=r.get(q);if(!W)return O(new Error("Attachment was removed before it was sent"));if(a&&!W.handedOff)return O(new Error("Attachment controller is disposed"));if(W.item.status==="error"||W.item.status==="aborted")return O(W.item.error??new Error("Attachment upload failed"));W.item.status!=="ready"&&(N=!0)}if(N)return;let T;try{T=R.map(q=>{let W=rf(r.get(q).item.attachment);return{type:"file",attachment_id:W.attachment_id,filename:W.filename,mime:W.mime}})}catch(q){return O(q instanceof Error?q:new Error(String(q)))}P(),v(T)};if(_?.aborted)return A();o.add($),_?.addEventListener("abort",A,{once:!0}),$()})}return{add:y=>E([y])[0],addMany:E,restore:L,retry(y){let _=r.get(y);if(_?.handedOff||f(),!(!_||_.item.status==="ready"||_.item.status==="uploading"||_.item.status==="processing"||_.item.status==="pending")){if(!_.item.file||_.upload&&Date.parse(_.upload.expires_at)<=Date.now())throw Tb();_.item={..._.item,status:"pending",error:void 0},S()}},async remove(y){let _=r.get(y);if(!_)return;_.removed=!0,_.generation++,r.delete(y);let R=_.upload?.attachment_id??_.item.attachment?.attachment_id;R&&_.abort?.abort(),m(),S(),R&&g(_,R)},abort:D,submit(y){if(!a){for(let _ of y){let R=r.get(_);R&&(R.handedOff=!0)}m()}},reclaim(y){if(!a){for(let _ of y){let R=r.get(_);R&&(R.handedOff=!1)}m()}},whenReady:w,forget(y=d().map(_=>_.item.id)){for(let _ of y){let R=r.get(_);R&&(R.generation++,R.abort?.abort(),r.delete(_))}m(),S()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let _=y.upload?.attachment_id??y.item.attachment?.attachment_id;_&&e&&Ht(e,_).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(y){return s.add(y),()=>{s.delete(y)}}}}function Eb(e){return{attachments:{upload:(...t)=>Kn(e,...t),delete:(...t)=>Ht(e,...t),createController:t=>sf(e,t)},get:t=>kt(e,t),detail:()=>jn(e),skills:{create:(...t)=>ia(e,...t)},audit:t=>Rd(e,t),update:t=>Bn(e,t),archive:()=>Un(e),llmCatalog:()=>Ln(e),modelPicker:()=>$n(e),modelAccess:()=>rr(e),setModelAccess:t=>sr(e,t),sandboxHealth:()=>Nn(e),onboardingComplete:(...t)=>oa(e,...t)}}function Ib(e){return{sessions:{list:t=>Tt(e,t),listPage:t=>Al(e,t),create:t=>Et(e,t),ensureWarm:()=>Ll(e),claimWarm:t=>$l(e,t)},review:{list:t=>rd(e,t),summary:()=>sd(e),get:t=>od(e,t),submit:t=>id(e,t),act:(...t)=>ad(e,...t),bulkAct:t=>cd(e,t)},approvals:{list:t=>ja(e,t),resolve:(...t)=>$a(e,...t),sessionsNeedingInput:t=>La(e,t)}}}function Mb(e){return{files:{list:t=>Jc(e,t),listDirectory:t=>Qc(e,t),read:(t,n)=>Zc(e,t,n),search:(...t)=>Xc(e,...t),archive:(...t)=>el(e,...t),archiveRequest:(...t)=>tl(e,...t),history:(...t)=>cl(e,...t)},git:{commits:()=>ol(e),commit:t=>il(e,t),commitDiff:t=>al(e,t),branches:()=>sl(e),versionDiff:(...t)=>ll(e,...t),inviteCollaborator:(...t)=>Ji(e,...t)},changeRequests:{list:(...t)=>ul(e,...t),get:t=>pl(e,t),update:(...t)=>Sl(e,...t),diff:t=>dl(e,t),mergePreview:t=>gl(e,t),open:(...t)=>ml(e,...t),merge:(...t)=>fl(e,...t),close:(...t)=>yl(e,...t),reopen:(...t)=>hl(e,...t),requestChanges:(...t)=>_l(e,...t)},...Ib(e)}}function Ob(e){return{policies:{list:()=>Uc(e),set:(...t)=>Fc(e,...t)},reminders:{list:()=>yd(e),updateMany:(...t)=>md(e,...t),removeMany:(...t)=>fd(e,...t)},triggers:{list:()=>ou(e),eventApps:()=>du(e),eventTypes:(...t)=>pu(e,...t),create:(...t)=>iu(e,...t),update:(...t)=>au(e,...t),remove:(...t)=>cu(e,...t),fire:(...t)=>uu(e,...t),setActivation:(...t)=>lu(e,...t)},...Mb(e)}}function Db(e,t){return{connectors:{...ko(e),list:()=>Sc(e),config:(...n)=>Rc(e,...n),create:(...n)=>Ec(e,...n),remove:(...n)=>Mc(e,...n),sync:()=>Pc(e),auth:{discover:(...n)=>Ic(e,...n)},setName:(...n)=>Cc(e,...n),setCredentialMode:(...n)=>xc(e,...n),setAuthorizationStrategy:(...n)=>wc(e,...n),setCredential:(...n)=>jc(e,...n),deleteCredential:(...n)=>Lc(e,...n),setSensitive:(...n)=>vc(e,...n),connections:t,policies:{get:(...n)=>Ac(e,...n),set:(...n)=>kc(e,...n)},connect:(...n)=>Tc(e,...n),finalize:(...n)=>$c(e,...n),discover:{list:(...n)=>bs(e,...n),sections:(...n)=>Oc(e,...n),detail:(...n)=>Ss(e,...n)}},...Ob(e)}}function jb(e){return{gateway:{logs:t=>up(e,t),log:t=>pp(e,t),overview:t=>dp(e,t),series:t=>gp(e,t),breakdown:t=>mp(e,t),sessions:t=>fp(e,t),errors:t=>yp(e,t),budgets:()=>hp(e),setBudget:t=>_p(e,t),deleteBudget:t=>bp(e,t),keys:()=>Sp(e),createKey:t=>Pp(e,t),revokeKey:t=>xp(e,t),routing:{get:()=>ip(e),set:t=>ap(e,t),reset:()=>cp(e),preview:t=>lp(e,t)},playground:(t,n,r)=>wp(e,t,n,r)}}}function Lb(e){return{modelDefaults:{get:()=>yu(e),set:t=>hu(e,t),clear:t=>_u(e,t)},setDefaultAgent:t=>Pu(e,t),sandbox:{list:()=>Yc(e),snapshots:()=>qc(e),rebuildSnapshot:t=>Gc(e,t),fixWithAgent:()=>Wc(e),createTemplate:t=>Kc(e,t),updateTemplate:(...t)=>Vc(e,...t),removeTemplate:t=>Hc(e,t),buildTemplate:t=>zc(e,t),setProvider:t=>sa(e,t)},setAgentScope:(...t)=>bu(e,...t)}}function $b(e){return{channels:{slack:{installation:()=>Ku(e),connect:t=>Vu(e,t),mode:()=>Hu(e),completeInstall:t=>zu(e,t),manifest:()=>Ju(e),disconnect:()=>Qu(e),getFile:t=>Xu(e,t),uploadFile:t=>Zu(e,t)},teams:{completeInstall:t=>Yu(e,t)},email:{installation:t=>tp(e,t),mode:()=>np(e),connect:t=>rp(e,t),disconnect:t=>sp(e,t),updatePolicy:(...t)=>op(e,...t)}},updateFeatureFlag:(...t)=>na(e,...t),updateExperimentalFeature:(...t)=>ra(e,...t),...Lb(e)}}async function of(e){let t=e?.fetch??C().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??C().backendUrl,r=await t(`${It(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new x(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var MM=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function OM(e,t){let n=o=>{let i=MM.exec(o.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),s=n(t);if(!r||!s)return null;for(let o=0;o<3;o++)if(r[o]!==s[o])return r[o]<s[o]?-1:1;return 0}function DM(){return gt()}var Bb=null,Ub=!1;function jM(e){let t=Bb;Bb=e,!(Ub||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(Ub=!0,console.warn("[beeuni] createBeeuni() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedBeeuni() from @beeuni/sdk/server.")))}function Fb(e,t){t?.global!==!1&&jM(e),Xr(e,t);let n=y_(e),{auth:r,accounts:s,iam:o,accountInvites:i}=p_(),{billing:a,sandboxShares:c}=c_(),{projects:p,github:d,connectStatus:g,marketplace:m}=o_();function f(h){let S=Rb(h);return{...Eb(h),...vb(h),...kb(h),...Db(h,S),...jb(h),...$b(h),connector:E=>nf(h,E),session:E=>tf(h,E,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,capture:a_,projects:p,connectors:ko(),connector:h=>nf(void 0,h),project:f,session:(h,S)=>tf(h,S,e,n),github:d,billing:a,sandboxShares:c,connectStatus:g,marketplace:m,notifications:{registerDeviceToken:Ag,unregisterDeviceToken:kg,list:Rg,markRead:Cg,preferences:Tg,updatePreferences:Eg,webPushPublicKey:Ig,registerWebPushSubscription:Mg,unregisterWebPushSubscription:Og},mobileClientPolicy:of,validateToken:zi,runtime:DM}}function Nb(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<16;r++)t[r]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(r=>r.toString(16).padStart(2,"0"));return`${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n.slice(10).join("")}`}function qb(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function yn(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function Gb(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function Wb(e){if(yn(e).length>0)return{state:e};let t=e.pending[0];if(!t)return{state:e};let n={...t,attempts:t.attempts+1};return{state:{...e,pending:[n,...e.pending.slice(1)],inFlightId:n.id,inFlightIds:[n.id]},claimed:n}}function Kb(e){let t=yn(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function Vb(e,t){let n=yn(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function Hb(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function zb(e,t){return yn(e).includes(t)?e:e.pending.some(n=>n.id===t)?{...e,pending:e.pending.filter(n=>n.id!==t)}:e.failed.some(n=>n.id===t)?{...e,failed:e.failed.filter(n=>n.id!==t)}:e}function Yb(e,t,n){return yn(e).includes(t)||!e.pending.some(r=>r.id===t)?e:{...e,pending:e.pending.map(r=>r.id===t?{...r,text:n}:r)}}function Jb(e,t,n){let r=yn(e);if(r.includes(t))return e;let s=e.pending.findIndex(p=>p.id===t);if(s===-1)return e;let o=r.length,i=Math.min(Math.max(n,o),e.pending.length-1);if(i===s)return e;let a=[...e.pending],[c]=a.splice(s,1);return a.splice(i,0,c),{...e,pending:a}}var af={thinking:!1,toolDetails:!0,assistantMetadata:!0};function LM(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function $M(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=t%60;return`${n}m ${r.toFixed(0)}s`}function BM(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
22
22
 
23
23
  `;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
24
24
  >
@@ -51,15 +51,15 @@ ${s}
51
51
  ${e.state.error}
52
52
  \`\`\`
53
53
  `),n+=`
54
- `,n}return""}function PC(e,t){if(!t)return`## Assistant
54
+ `,n}return""}function UM(e,t){if(!t)return`## Assistant
55
55
 
56
- `;let n=e.agent?hC(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=bC(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
56
+ `;let n=e.agent?LM(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=$M(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
57
57
 
58
58
  `:`## ${n}
59
59
 
60
- `}function SC(e,t,n){let r="";e.role==="user"?r+=`## User
60
+ `}function FM(e,t,n){let r="";e.role==="user"?r+=`## User
61
61
 
62
- `:r+=PC(e,n.assistantMetadata);for(let s of t)r+=_C(s,n);return r}function Ih(e,t,n=Ig){let r=`# ${e.title||"Untitled Session"}
62
+ `:r+=UM(e,n.assistantMetadata);for(let s of t)r+=BM(s,n);return r}function Qb(e,t,n=af){let r=`# ${e.title||"Untitled Session"}
63
63
 
64
64
  `;r+=`**Session ID:** \`${e.id}\`
65
65
  `,r+=`**Created:** ${new Date(e.time.created).toLocaleString()}
@@ -67,30 +67,32 @@ ${e.state.error}
67
67
 
68
68
  `,r+=`---
69
69
 
70
- `;for(let s of t)r+=SC(s.info,s.parts,n),r+=`---
70
+ `;for(let s of t)r+=FM(s.info,s.parts,n),r+=`---
71
71
 
72
- `;return r}function Th(e,t){return`session-${e}.md`}var Tg="An error occurred";var xC=["message","error","detail","error_description","msg","errors","data"];function Eg(e){let t=e.trim();for(let n=0;n<4;n++){let r=t.replace(/^(?:\d{3}\s+)?(?:[A-Za-z_$][\w$]*)?Error:\s*/,"").trim();if(r===t)break;t=r}return t}function Kt(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function wC(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=Kt(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function vC(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=AC(e,t);if(n)return n;let r=RC(e,t);return r?r.slice(0,200):void 0}function Dh(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function Eh(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function AC(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!Dh(t.charCodeAt(s))){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return;let i=e.indexOf("<",o+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(o+1,i).trim();if(a)return a}n=o+1}}var kC=["script","style"];function RC(e,t){let n=[],r=0;for(;r<e.length;){let s=e.indexOf("<",r);if(s===-1){n.push(e.slice(r));break}n.push(e.slice(r,s));let o=kC.find(i=>t.startsWith(`<${i}`,s)&&Dh(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:Eh(e,i);continue}r=Eh(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function CC(e){if(!e.startsWith("JSON parsing failed: Text:"))return;let t=e.match(/"model"\s*:\s*"([^"\\]{1,120})"/)?.[1]?.trim();return t?`The response from ${t} could not be read.`:"The model response could not be read."}function IC(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function Mh(e,t,n){if(typeof e=="string")return Ts(e,t,n);if(e&&typeof e=="object")return Es(e,t,n)}function Ts(e,t,n=new WeakSet){let r=Eg(e);if(!r)return;if(t>=4)return r;let s=CC(r);if(s)return s;let o=Kt(r);if(o!==void 0)return typeof o=="string"?Ts(o,t+1,n):o&&typeof o=="object"?Es(o,t+1,n):String(o);let i=jh(r);if(i){let a=Kt(i);if(a&&typeof a=="object"){let u=Es(a,t+1,n);if(u)return u}}if(r.includes("{")){let a=wC(r);if(a)return Ts(a,t+1,n)??a}return vC(r)??r}function Es(e,t,n=new WeakSet){if(t>=4||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let i of e){let a=Mh(i,t,n);if(a)return a}return}let r=e;for(let i of xC){let a=Mh(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return IC(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function pe(e){return e?typeof e=="string"?Ts(e,0)??Tg:typeof e=="object"?Es(e,0)??Tg:String(e):Tg}function Mg(e){let t=TC(e)?.trim();if(!t)return;let n=pe(e);if(!(t===n||Eg(t)===n))return t}function TC(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:s}=n,o=[r,s].filter((i,a,u)=>typeof i=="string"&&i.trim()!==""&&u.indexOf(i)===a);if(o.length>0)return o.join(`
72
+ `;return r}function Xb(e,t){return`session-${e}.md`}var cf="An error occurred";var NM=["message","error","detail","error_description","msg","errors","data"];function lf(e){let t=e.trim();for(let n=0;n<4;n++){let r=t.replace(/^(?:\d{3}\s+)?(?:[A-Za-z_$][\w$]*)?Error:\s*/,"").trim();if(r===t)break;t=r}return t}function hn(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function qM(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=hn(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function GM(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=WM(e,t);if(n)return n;let r=VM(e,t);return r?r.slice(0,200):void 0}function nS(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function Zb(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function WM(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!nS(t.charCodeAt(s))){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return;let i=e.indexOf("<",o+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(o+1,i).trim();if(a)return a}n=o+1}}var KM=["script","style"];function VM(e,t){let n=[],r=0;for(;r<e.length;){let s=e.indexOf("<",r);if(s===-1){n.push(e.slice(r));break}n.push(e.slice(r,s));let o=KM.find(i=>t.startsWith(`<${i}`,s)&&nS(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:Zb(e,i);continue}r=Zb(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function HM(e){if(!e.startsWith("JSON parsing failed: Text:"))return;let t=e.match(/"model"\s*:\s*"([^"\\]{1,120})"/)?.[1]?.trim();return t?`The response from ${t} could not be read.`:"The model response could not be read."}function zM(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function eS(e,t,n){if(typeof e=="string")return Ro(e,t,n);if(e&&typeof e=="object")return Co(e,t,n)}function Ro(e,t,n=new WeakSet){let r=lf(e);if(!r)return;if(t>=4)return r;let s=HM(r);if(s)return s;let o=hn(r);if(o!==void 0)return typeof o=="string"?Ro(o,t+1,n):o&&typeof o=="object"?Co(o,t+1,n):String(o);let i=rS(r);if(i){let a=hn(i);if(a&&typeof a=="object"){let c=Co(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=qM(r);if(a)return Ro(a,t+1,n)??a}return GM(r)??r}function Co(e,t,n=new WeakSet){if(t>=4||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let i of e){let a=eS(i,t,n);if(a)return a}return}let r=e;for(let i of NM){let a=eS(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return zM(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function _e(e){return e?typeof e=="string"?Ro(e,0)??cf:typeof e=="object"?Co(e,0)??cf:String(e):cf}function Rr(e){let t=YM(e)?.trim();if(!t)return;let n=_e(e);if(!(t===n||lf(t)===n))return t}function YM(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:s}=n,o=[r,s].filter((i,a,c)=>typeof i=="string"&&i.trim()!==""&&c.indexOf(i)===a);if(o.length>0)return o.join(`
73
73
 
74
- `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function jh(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function EC(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(typeof t.message=="string"&&t.message)return t.message;if(typeof t.error=="string"&&t.error)return t.error;let n=t.data;if(typeof n?.message=="string")return n.message;let r=t.error;if(typeof r?.message=="string")return r.message}function MC(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n;!Number.isInteger(r.attempt)||r.attempt<1||typeof r.provider!="string"||!r.provider||typeof r.route_model!="string"||!r.route_model||typeof r.resolved_model!="string"||!r.resolved_model||typeof r.stage!="string"||!r.stage||typeof r.code!="string"&&!(typeof r.code=="number"&&Number.isFinite(r.code))||typeof r.message!="string"||!r.message||r.status!==void 0&&(!Number.isInteger(r.status)||r.status<100||r.status>599)||t.push({attempt:r.attempt,provider:r.provider,routeModel:r.route_model,resolvedModel:r.resolved_model,stage:r.stage,...typeof r.status=="number"?{status:r.status}:{},code:r.code,message:r.message})}return t.length>0?t:void 0}function Oh(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,s=typeof e.upstream_status=="number"?e.upstream_status:void 0,o=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=MC(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,u=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&s===void 0&&!o&&!i?void 0:{message:typeof e.message=="string"&&e.message||EC(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:i,...a?{requestedModel:a}:{},...u?{resolvedModel:u}:{}}}function ge(e){if(e==null)return;if(typeof e=="string"){let a=Eg(e),u=Kt(a)??Kt(jh(a));return u!==void 0?ge(u):void 0}if(typeof e!="object")return;let t=e,n=Oh(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let s=t.error;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=Oh(s);if(a)return a}let o=t.data;if(o&&typeof o.responseBody=="string"){let a=Kt(o.responseBody);if(a!==void 0){let u=ge(a);if(u)return u}}if(o&&typeof o.message=="string"){let a=ge(o.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let u=ge(a);if(u)return u}}return n}var $h={};function H(e,t){for(let n of t)$h[n]=e}H("read",["read"]);H("list",["list","ls"]);H("glob",["glob"]);H("grep",["grep"]);H("write",["write"]);H("edit",["edit","multiedit","morph_edit"]);H("apply_patch",["apply_patch","patch"]);H("bash",["bash"]);H("web_search",["web_search","websearch","image_search"]);H("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);H("media",["image_gen","video_gen"]);H("show",["show","show_user","presentation_gen"]);H("task",["task"]);H("delegate",["agent_spawn","agent_task","agent_task_create","agent_task_start","task_create","task_start","session_spawn","session_start_background","agent_message","agent_task_message","task_message","agent_task_update","task_update","session_message","agent_status","agent_task_list","agent_task_get","task_list","task_get","agent_stop","agent_task_cancel","task_cancel","agent_task_approve","task_approve","task_done","task_delete"]);H("todowrite",["todowrite","todo_write","todoread"]);H("question",["question","ask"]);H("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);H("connectors",["connector_get","connector_list","connector_setup","beeuni_connector_call","beeuni_connectors","beeuni_connectors_connectors","beeuni_connectors_discover","beeuni_connectors_describe","beeuni_connectors_call","beeuni_connector_describe","beeuni_connector_discover"]);H("automations",["triggers"]);H("skill",["skill"]);H("context",["prune","distill","compress","context_info"]);H("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var OC=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function te(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=$h[t];if(n)return n;for(let[r,s]of OC)if(t.startsWith(r))return s;return"other"}function De(e){for(let t of[e?.filePath,e?.file_path,e?.path])if(typeof t=="string"&&t)return t}var DC=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function jC(){return new RegExp(`(^|\\s)([-+]?)(${DC.join("|")}):("[^"]*"|\\S+)`,"gi")}function $C(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function UC(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function FC(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function LC(e){return FC(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function Uh(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Vn(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(jC(),(s,o,i,a,u)=>{if(!i&&a.toLowerCase()==="site"){let p=LC(u);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace($C(),"$1").replace(UC(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${Uh(n)}`:r:n.length>0?Uh(n):t}var BC=/\s/,NC=/\w/;function se(e){return e!==void 0&&BC.test(e)}function zn(e){return e===`
75
- `||e==="\r"||e==="\u2028"||e==="\u2029"}function Og(e){return e!==void 0&&NC.test(e)}function mt(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(qC(n.charCodeAt(0))):n;return t}function qC(e){if(e<128)return e>=97&&e<=122?e-32:e;let t=String.fromCharCode(e).toUpperCase();if(t.length!==1)return e;let n=t.charCodeAt(0);return n<128?e:n}function je(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function Fh(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return je(e.slice(t))}function Yn(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let s=e.indexOf(n,r+t.length);return s===-1?null:e.slice(r+t.length,s)}function Dg(e,t){let n=Yn(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
74
+ `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function rS(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function JM(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(typeof t.message=="string"&&t.message)return t.message;if(typeof t.error=="string"&&t.error)return t.error;let n=t.data;if(typeof n?.message=="string")return n.message;let r=t.error;if(typeof r?.message=="string")return r.message}function QM(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n;!Number.isInteger(r.attempt)||r.attempt<1||typeof r.provider!="string"||!r.provider||typeof r.route_model!="string"||!r.route_model||typeof r.resolved_model!="string"||!r.resolved_model||typeof r.stage!="string"||!r.stage||typeof r.code!="string"&&!(typeof r.code=="number"&&Number.isFinite(r.code))||typeof r.message!="string"||!r.message||r.status!==void 0&&(!Number.isInteger(r.status)||r.status<100||r.status>599)||t.push({attempt:r.attempt,provider:r.provider,routeModel:r.route_model,resolvedModel:r.resolved_model,stage:r.stage,...typeof r.status=="number"?{status:r.status}:{},code:r.code,message:r.message})}return t.length>0?t:void 0}function tS(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,s=typeof e.upstream_status=="number"?e.upstream_status:void 0,o=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=QM(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,c=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&s===void 0&&!o&&!i?void 0:{message:typeof e.message=="string"&&e.message||JM(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function we(e){if(e==null)return;if(typeof e=="string"){let a=lf(e),c=hn(a)??hn(rS(a));return c!==void 0?we(c):void 0}if(typeof e!="object")return;let t=e,n=tS(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let s=t.error;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=tS(s);if(a)return a}let o=t.data;if(o&&typeof o.responseBody=="string"){let a=hn(o.responseBody);if(a!==void 0){let c=we(a);if(c)return c}}if(o&&typeof o.message=="string"){let a=we(o.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let c=we(a);if(c)return c}}return n}var sS={};function z(e,t){for(let n of t)sS[n]=e}z("read",["read"]);z("list",["list","ls"]);z("glob",["glob"]);z("grep",["grep"]);z("write",["write"]);z("edit",["edit","multiedit","morph_edit","MultiEdit","NotebookEdit"]);z("apply_patch",["apply_patch","patch"]);z("bash",["bash"]);z("script",["codemode"]);z("web_search",["web_search","websearch","image_search"]);z("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);z("media",["image_gen","video_gen"]);z("show",["show","show_user","presentation_gen"]);z("task",["task"]);z("delegate",["agent_spawn","agent_task","agent_task_create","agent_task_start","task_create","task_start","session_spawn","session_start_background","agent_message","agent_task_message","task_message","agent_task_update","task_update","session_message","agent_status","agent_task_list","agent_task_get","task_list","task_get","agent_stop","agent_task_cancel","task_cancel","agent_task_approve","task_approve","task_done","task_delete"]);z("todowrite",["todowrite","todo_write","todoread"]);z("question",["question","ask"]);z("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);z("connectors",["connector_get","connector_list","connector_setup","beeuni_connector_call","beeuni_connectors","beeuni_connectors_connectors","beeuni_connectors_discover","beeuni_connectors_describe","beeuni_connectors_call","beeuni_connector_describe","beeuni_connector_discover"]);z("automations",["triggers"]);z("skill",["skill"]);z("context",["prune","distill","compress","context_info"]);z("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var XM=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function le(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=sS[t];if(n)return n;for(let[r,s]of XM)if(t.startsWith(r))return s;return"other"}function et(e){for(let t of[e?.filePath,e?.file_path,e?.path,e?.notebook_path])if(typeof t=="string"&&t)return t}var ZM=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function eO(){return new RegExp(`(^|\\s)([-+]?)(${ZM.join("|")}):("[^"]*"|\\S+)`,"gi")}function tO(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function nO(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function rO(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function sO(e){return rO(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function oS(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Cr(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(eO(),(s,o,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=sO(c);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(tO(),"$1").replace(nO(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${oS(n)}`:r:n.length>0?oS(n):t}var oO=/\s/,iO=/\w/;function be(e){return e!==void 0&&oO.test(e)}function Tr(e){return e===`
75
+ `||e==="\r"||e==="\u2028"||e==="\u2029"}function uf(e){return e!==void 0&&iO.test(e)}function $t(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(aO(n.charCodeAt(0))):n;return t}function aO(e){if(e<128)return e>=97&&e<=122?e-32:e;let t=String.fromCharCode(e).toUpperCase();if(t.length!==1)return e;let n=t.charCodeAt(0);return n<128?e:n}function tt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function iS(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return tt(e.slice(t))}function Er(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let s=e.indexOf(n,r+t.length);return s===-1?null:e.slice(r+t.length,s)}function pf(e,t){let n=Er(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
76
76
  `)&&(n=n.slice(1)),n.endsWith(`
77
- `)&&(n=n.slice(0,-1)),n)}function jg(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let s=e.indexOf(">",r+1+t.length);return s===-1?null:{open:r,end:s}}function Lh(e,t){let n=jg(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function Bh(e,t){let n=jg(e,t);if(!n)return null;let r=e.indexOf(`</${t}>`,n.end+1);return r===-1?null:e.slice(n.end+1,r)}function Nh(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=jg(e,t,s);if(!o)break;let i=e.indexOf(n,o.end+1);if(i===-1)break;r+=e.slice(s,o.open),s=i+n.length}return r+e.slice(s)}function qh(e,t,n){let r=[];for(let s of e.split(/[\n\r\u2028\u2029]/)){let o=0;for(;;){let i=s.indexOf(t,o);if(i===-1)break;let a=s.indexOf(n,i+t.length);if(a===-1)break;r.push(s.slice(i+t.length,a)),o=a+n.length}}return r}function Qn(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&se(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function Gh(e,t,n){let r=mt(t),s=mt(n);for(let o of mt(e).split(/[\n\r\u2028\u2029]/)){let i=o.indexOf(r);if(i!==-1&&o.lastIndexOf(s)>=i+r.length)return!0}return!1}function Wh(e,t){let n=mt(e),r=t.map(mt),s=e.length,o=u=>{let p=u;for(;p<s&&se(e[p]);)p++;return p},i=u=>{for(let p=u;p<s;p++)if(zn(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let u=o(a);if(u>=s)return null;let p=r.find(d=>n.startsWith(d,u));if(p!==void 0){let d=o(u+p.length);if(e[d]===":"){let g=o(d+1);if(g<s){let m=g;for(;m<s&&!zn(e[m]);)m++;for(;m>g+1&&se(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!zn(e[m]))return e[m];return null}}a=i(u)}return null}function Kh(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=se(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!se(e[a-1]))continue;let u=a+1;if(se(e[u])){for(;u<t&&se(e[u]);)u++;Og(e[u])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(zn(e[a])?1:0);let o=(a,u)=>s[u]===s[a],i=a=>{let u=a+1;for(;se(e[u]);)u++;let p=u;for(;p<t&&Og(e[p]);)p++;return e.slice(u,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let u=a+7;for(;u<t&&/[a-z0-9]/.test(e[u]);)u++;if(u===a+7||e[u]!=="*"||e[u+1]!=="*")continue;let p=u+2,d=p;for(;d<t&&se(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(o(d,m))return{id:e.slice(a+2,u),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!zn(e[g]))return{id:e.slice(a+2,u),title:e[g],status:i(d)}}}}return null}function Hh(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&se(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&se(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!Og(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&se(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function Vh(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let u=a+n.length;if(o<u&&(o=e.indexOf("]",u)),o===-1)break;let p=o;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(s,a)+(t?" ":e.slice(u,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function zh(e){return Vh(e,!0)}function Yh(e){return Vh(e,!1)}function GC(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Qh(e,t){let n=mt(e),r=mt(t),s=e.length,o=i=>{let a=i;for(;a<s&&se(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=o(i+r.length);if(e[a]!==":")continue;let u=o(a+1);for(let p=u;p<s;){if(!se(e[p])){p++;continue}let d=o(p);if(GC(e,d))return e.slice(u,p);p=d}return e.slice(u)}return null}var Jh=new Set(["read","glob","grep","list"]);function V(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function WC(e){return Jh.has(te(e))}function KC(e){let t=0,n=0,r=0;for(let s of e){let o=te(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function $g(e){if(!e)return"";let t=je(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ms(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Os(e){let n=(e.state??{}).input??{};switch(V(e.tool)){case"read":case"edit":case"write":case"morph_edit":{let o=n.filePath??n.file_path??n.path;return o?$g(String(o)):""}case"glob":return n.pattern?String(n.pattern):"";case"grep":{let o=n.pattern??n.query,i=n.path??n.include;return o&&i?`"${Ms(String(o),40)}" in ${$g(String(i))}`:o?`"${Ms(String(o),60)}"`:""}case"list":return n.path?$g(String(n.path)):"";case"bash":return Ms(String(n.command??""),80);default:break}let s=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let o of s){let i=n[o];if(typeof i=="string"&&i.length>0)return Ms(o==="query"&&Vn(i)||i,60)}return""}var Xh={read:"Read",search:"Search",list:"List",shell:"Shell",edit:"Edit",write:"Write",fetch:"Fetch",webSearch:"Web Search",scrape:"Scrape",applyPatch:"Apply Patch",task:"Task",worker:"Worker",workspace:"Workspace"};function HC(e,t={}){let n={...Xh,...t},r=V(e.tool),s=Os(e);switch(r){case"read":return{title:n.read,subtitle:s};case"glob":case"grep":return{title:n.search,subtitle:s};case"list":return{title:n.list,subtitle:s};case"bash":return{title:n.shell,subtitle:s};case"edit":case"morph_edit":return{title:n.edit,subtitle:s};case"write":return{title:n.write,subtitle:s};case"webfetch":case"web_fetch":return{title:n.fetch,subtitle:s};case"websearch":case"web_search":return{title:n.webSearch,subtitle:s};case"scrape":case"scrape_webpage":return{title:n.scrape,subtitle:s};case"apply_patch":return{title:n.applyPatch,subtitle:s};case"task":return{title:n.task,subtitle:s};case"session_spawn":case"session_start_background":return{title:n.worker,subtitle:s};case"project_select":case"project_list":return{title:n.workspace,subtitle:s};default:return{title:r.replace(/_/g," ").replace(/\b\w/g,i=>i.toUpperCase()),subtitle:s}}}function _e(e){return e.type==="text"}function Pe(e){return e.type==="reasoning"}function X(e){return e.type==="tool"}function Fg(e){return e.type==="file"}function VC(e){return e.type==="agent"}function zC(e){return e.type==="compaction"}function YC(e){return e.type==="snapshot"}function QC(e){return e.type==="patch"}function JC(e){return e.type==="step-start"||e.type==="step-finish"}function XC(e){if(_e(e)||Pe(e))return e.text}function ZC(e){if(!Fg(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function eI(e){let t=[],n=[];for(let r of e)Fg(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function tI(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function nI(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var rI=new Set(["todoread","context_info"]);function Zh(e){return!rI.has(e.tool)}var sI=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function Lg(e){let t=e.tool||"";if(t.startsWith("oc-"))return;let n=te(t);if(n==="task"||n==="delegate"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r;if(n==="task"&&e.state?.status==="error")return e.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return oI(t,e.state)}function oI(e,t){let n=V(e);if(sI.has(n)){let r=t?.title?.match(/\bses_[a-zA-Z0-9]+/);return r?r[0]:t?.output?.match(/\bses_[a-zA-Z0-9]+/)?.[0]}if(n==="session_spawn"||n==="session_start_background")return t?.output?.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/)?.[1]}function iI(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return pe(n.error)}}function aI(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)X(r)&&Zh(r)&&t.push(r);return t}function cI(e,t={}){switch(V(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:nb(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"BeeuniWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"apply_patch":return{icon:"file-pen",title:"Patch",subtitle:t.files?.length?`${t.files.length} file${t.files.length>1?"s":""}`:void 0};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"prune":return{icon:"scissors",title:"DCP Prune",subtitle:t.reason};case"distill":return{icon:"scissors",title:"DCP Distill"};case"compress":return{icon:"scissors",title:"DCP Compress",subtitle:t.topic};case"context_info":return{icon:"scissors",title:"Context Info"};case"session_read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session_list_spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":return{icon:"folder",title:"Projects"};case"project_get":case"project_update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":return{icon:"clock",title:"List Triggers"};case"trigger_get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":return{icon:"layers",title:"Agent Status"};case"agent_task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":return{icon:"trash-2",title:"Delete Task",subtitle:t.id};case"pty_spawn":return{icon:"terminal",title:"Spawn",subtitle:t.title||t.command};case"pty_read":return{icon:"terminal",title:"Terminal Output",subtitle:t.id};case"pty_write":case"pty_input":return{icon:"terminal",title:"Terminal Input",subtitle:t.id};case"pty_kill":return{icon:"terminal",title:"Kill Process",subtitle:t.id};default:return uI(e,t)}}function uI(e,t){switch(te(e)){case"read":return{icon:"glasses",title:"Read",subtitle:eb(De(t))};case"list":return{icon:"list",title:"List",subtitle:tb(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":return{icon:"file-pen",title:"Edit",subtitle:Ug(De(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Ug(De(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function eb(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Ug(e){if(!e)return;let t=e.split("/"),n=t[t.length-1]||e;if(t.length<=1)return n;let r=t[t.length-2];return r?`${n} /${r}`:n}function tb(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function lI(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function Jn(e,t=120){if(typeof e!="string")return"";let n=e.split(`
78
- `).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function nb(e){let t=Jn(e.description);if(t)return t;let n=Jn(e.title,80);if(n)return n;let r=Jn(e.message);if(r)return r;let s=Jn(e.prompt);if(s)return s;let o=Jn(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function pI(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function dI(e,t){return e.find(n=>n.tool?.callID===t)}function gI(e,t){return e.find(n=>n.tool?.callID===t)}var mI=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function fI(e){return e?e.replace(mI,""):""}var yI={bash:"Shell",pty_spawn:"Spawn Terminal",pty_read:"Terminal Output",pty_write:"Terminal Input",pty_input:"Terminal Input",pty_kill:"Kill Process",read:"Read File",list:"List Directory",ls:"List Directory",write:"Write File",edit:"Edit File",multiedit:"Edit File",morph_edit:"Edit File",apply_patch:"Apply Patch",patch:"Apply Patch",grep:"Search Code",glob:"Find Files",image_search:"Image Search",session_search:"Search Sessions",webfetch:"Fetch Page",scrape_webpage:"Scrape Page",websearch:"Web Search",web_search:"Web Search",image_gen:"Generate Image",video_gen:"Generate Video",task:"Delegate to Agent",todowrite:"Plan Tasks",todoread:"Read Plan",question:"Ask Question",presentation_gen:"Presentation",show:"Show Output",show_user:"Show Output",prune:"Prune Context",distill:"Distill Context",compress:"Compress Context",context_info:"Context Info"},hI={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function bI(e){return e.replace(/^oc[-_]/,"")}function Bg(e){return bI(e).replace(/-/g,"_")}function Ng(e){return Bg(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Ds(e){return{label:yI[Bg(e)]??Ng(e),category:hI[te(e)]}}var _I=256*1024;function PI(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function SI(e){if(e===void 0)return{};if(e.length>_I)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function xI(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,s=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!s))return s?pe(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var Z=e=>typeof e=="string"?e:void 0,js=e=>typeof e=="number"?e:void 0,$s=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function qg(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var wI=new Set(["add","update","delete","move"]);function vI(e,t,n){if(e==="apply_patch"){let u=(Array.isArray(n.files)?n.files:[]).flatMap(p=>{let d=$s(p),g=d&&(Z(d.relativePath)||Z(d.filePath));if(!d||!g)return[];let m=Z(d.type);return[qg({path:g,type:m&&wI.has(m)?m:void 0,before:Z(d.before),after:Z(d.after),patch:Z(d.patch)??Z(d.diff),additions:js(d.additions),deletions:js(d.deletions),movePath:Z(d.movePath)})]});return u.length?u:void 0}let r=De(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[qg({path:r,after:Z(t.content)})];if(e!=="edit")return;let s=$s(n.filediff),o=s?void 0:Z(n.patch),i=o?AI(o):void 0;return[qg({path:r,before:Z(s?.before)??Z(t.oldString),after:Z(s?.after)??Z(t.newString),patch:o,additions:js(s?.additions)??i?.additions,deletions:js(s?.deletions)??i?.deletions})]}function AI(e){let t=0,n=0;for(let r of e.split(`
79
- `))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function kI(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function rb(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=SI(r),i=PI(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=xI(s);m&&(i="error",a=m)}let u=te(e),p=t.input??{},d="metadata"in t&&$s(t.metadata)||{},g=$s(d.diagnostics);return{name:e,kind:u,title:n||Ds(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:vI(u,p,d),diff:Z(d.patch)??Z(d.diff),diagnostics:g,answers:u==="question"?kI(d):void 0,childSessionId:Lg({tool:e,state:t})}}function RI(e){return rb(e.tool,e.state)}function CI(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function II(e){return{kind:"reasoning",id:e.id,text:e.text}}function TI(e){return{kind:"tool",id:e.id,tool:rb(e.tool,e.state)}}function EI(e){let t=e.mime;return{kind:"file",id:e.id,filename:e.filename,mime:t,url:e.url,isImage:t.startsWith("image/"),isPdf:t==="application/pdf"}}function MI(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function OI(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function DI(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function jI(e){return{kind:"agent",id:e.id,name:e.name}}function $I(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:pe(e.error),createdAt:e.time.created}}function UI(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function FI(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function LI(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Gg(e){switch(e.type){case"text":return CI(e);case"reasoning":return II(e);case"tool":return TI(e);case"file":return EI(e);case"subtask":return MI(e);case"patch":return OI(e);case"snapshot":return DI(e);case"agent":return jI(e);case"retry":return $I(e);case"compaction":return UI(e);case"step-start":return FI(e);case"step-finish":return LI(e);default:return{kind:"unknown",raw:e}}}function BI(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=ge(e);return{name:t,message:n?.message||pe(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function NI(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function sb(e){let t=e.parts.map(Gg),n=e.info.role==="assistant"?e.info.error:void 0,r=BI(n),s=!r&&!t.some(NI);return{parts:t,error:r,isEmpty:s}}var Wg=Ee+BigInt(1),ob=Wg/BigInt(2);function Us(e){return BigInt(Math.trunc(e))*Et}function Kg(e,t){let r=t-(t&Ee)+e;return r-t>ob?r-=Wg:t-r>ob&&(r+=Wg),r}function ib(e,t){let n=pt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return Kg(n,t);let s=Us(r),o=Kg(n,s);return(o>s?o-s:s-o)<=We?o:s}function ab(e){return pt(e)===null?1:0}function cb(e,t){return e<t?-1:e>t?1:0}function qI(e,t){return ub(e,t,Us(Date.now()))}function GI(e){let t=null;for(let n of e){let r=n.info.time?.created;typeof r=="number"&&(t===null||r>t)&&(t=r)}return Us(t??Date.now())}function ub(e,t,n){let r=ab(e.info.id),s=ab(t.info.id);if(r!==s)return r-s;if(r===0){let a=ib(e,n),u=ib(t,n);return a!==u?a<u?-1:1:cb(e.info.id,t.info.id)}let o=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return o===null&&i===null?0:o===null?1:i===null?-1:o!==i?o<i?-1:1:cb(e.info.id,t.info.id)}function WI(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=GI(e),s=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:ub(d,g,r)}),o=[],i=new Map;for(let d of s)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};o.push(g),i.set(d.info.id,g)}let a=null,u=[],p=[];for(let d of s){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=u[u.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):u.push({userMessage:HI(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=o[0]??u[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;o.push({userMessage:g,assistantMessages:m})}}return u.length>0?[...u,...o]:o}var Xn=new Map,KI=256;function HI(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=Xn.get(s);if(o)return o;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(Xn.size>=KI){let a=Xn.keys().next().value;a!==void 0&&Xn.delete(a)}return Xn.set(s,i),i}function VI(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function zI(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(_e(n)&&n.text?.trim())return n}}function YI(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function QI(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!X(o))continue;let i=o,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:o,message:s})}return r}function JI(e){let t=new Map;for(let n of e){if(!n.parentID)continue;let r=t.get(n.parentID);r?r.push(n.id):t.set(n.parentID,[n.id])}return t}function XI(e){let t=e-6e4;return(n,r)=>{let s=n.time.updated??n.time.created,o=r.time.updated??r.time.created,i=s>t,a=o>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:o-s}}function lb(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let s of n)r.push(s),r.push(...lb(e,s));return r}function pb(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function ZI(e){if(!e?.length)return!1;for(let t=e.length-1;t>=0;t--){let n=e[t].info;if(n.role==="assistant")return!n.time?.completed&&pb(n.error)}return!1}function Fs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Hg(e){let t=e.trim();return t.length>500?!1:!!(/^Error:\s/i.test(t)||/^([\w._-]+Error|[\w._-]+Exception):\s/i.test(t)||/Traceback \(most recent call last\)/i.test(t)||/^\s*\[\s*\{[\s\S]*"message"\s*:/.test(t))}function eT(e){return!!e&&(Hg(e)||gb(e)!==null)}function Vg(e){let t=db.get(e);if(t&&t.state===e.state)return t.outcome;let n=tT(e);return db.set(e,{state:e.state,outcome:n}),n}var db=new WeakMap;function tT(e){let t=e.state;if(t.status==="error")return"failed";if(t.status!=="completed")return"ok";let n=typeof t.output=="string"?t.output.trim():"";if(!n)return"ok";if(Hg(n))return"failed";let r=nT(n);return r===void 0?"ok":rT(r)?"failed":sT(r)}function nT(e){try{return JSON.parse(e)}catch{return}}function rT(e){return Fs(e)&&e.success===!1&&typeof e.error=="string"}function sT(e){let t=Fs(e)?e.results:void 0;if(!Array.isArray(t)||t.length===0)return"ok";let n=t.filter(r=>r!==null&&typeof r=="object"&&r.success===!1).length;return n===0?"ok":n===t.length?"failed":"partial"}function gb(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Fs(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},s=Qn(r.errorSummary);if(s===null)return r;try{let o=JSON.parse(s);typeof o.message=="string"&&o.message.trim()&&(r.nestedMessage=o.message.trim()),typeof o.status=="number"&&(r.status=o.status),typeof o.error=="boolean"&&(r.nestedError=o.error)}catch{}return r}function oT(e){return Hh(e).replace(/\s+/g," ").trim()||e.trim()}function iT(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Fs(n))return null;let r=n.success,s=n.error,o=n.hint;if(r!==!1||typeof s!="string")return null;let i=[];i.push(s.trim());let a=Qn(s);if(a!==null)try{let p=JSON.parse(a).message;typeof p=="string"&&p.trim()&&i.push(`Details: ${p.trim()}`)}catch{}return typeof o=="string"&&o.trim()&&i.push(`Hint: ${o.trim()}`),i.join(`
80
-
81
- `)}var mb=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),aT={read:{verb:"Read",running:"Reading",objectKeys:["filePath","path","file"]},write:{verb:"Wrote",running:"Writing",objectKeys:["filePath","path","file"]},edit:{verb:"Edited",running:"Editing",objectKeys:["filePath","path","file"]},apply_patch:{verb:"Edited",running:"Editing",objectKeys:["filePath","path"]},bash:{verb:"Ran",running:"Running",objectKeys:["command"]},glob:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},grep:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},list:{verb:"Listed",running:"Listing",objectKeys:["path"]},web_search:{verb:"Searched",running:"Searching",objectKeys:["query"]},websearch:{verb:"Searched",running:"Searching",objectKeys:["query"]},webfetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},web_fetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},scrape:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},scrape_webpage:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},task:{verb:"Delegated",running:"Delegating",objectKeys:["description"]},memory:{verb:"Remembered",running:"Remembering"},get_mem:{verb:"Recalled",running:"Recalling"},memory_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},mem_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},ltm_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},dcp_compress:{verb:"Compacted",running:"Compacting"},dcp_distill:{verb:"Distilled",running:"Distilling"},dcp_prune:{verb:"Pruned",running:"Pruning"},compress:{verb:"Compacted",running:"Compacting"},distill:{verb:"Distilled",running:"Distilling"},prune:{verb:"Pruned",running:"Pruning"},context_info:{verb:"Checked context",running:"Checking context"}};function cT(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Vn(t)||t}function uT(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let s=n[r];if(typeof s=="string"&&s.trim())return cT(r,s.trim())}}function zg(e){if(Pe(e))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!X(e))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let t=le(e.tool),n=aT[t],r=e.state?.input;return n?{verb:n.verb,running:n.running,object:uT(r,n.objectKeys),tier:mb.has(t)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:t,tier:"primary"}}function lT(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(zg(o).tier==="plumbing"){r=!0;continue}if(Pe(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,X(o)&&Vg(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function Yg(e){return`${e} ${e===1?"step":"steps"}`}function pT(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${Yg(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${Yg(n)}`:s===0?`${Yg(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function dT(e){let t=!1,n=!1,r=!1,s=null,o=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),s==null&&d.error!=null&&(s=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},u=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");u&&(t=!0),e.userMessage&&o(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)o(p.info),i(p.parts);return u&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function gT(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function mT(e,t=2e3){let n=(e??"").trim();try{let r=JSON.parse(n);if(typeof r=="string")try{r=JSON.parse(r)}catch{}r&&typeof r=="object"&&(n=JSON.stringify(r,null,2))}catch{}return n.length>t?{text:n.slice(0,t).trimEnd(),truncatedChars:n.length-t}:{text:n,truncatedChars:0}}function fT(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=zh(n),n=Yh(n),n=n.replace(/[#*_`>]+/g," "),n=n.replace(/\s+/g," ").trim(),n=n.replace(/\b(\w{2,})(?:\s+\1\b)+/gi,"$1"),n.length>t?n.slice(0,t).trimEnd()+"\u2026":n}function yT(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let s=r.error.trim(),o;for(let i=0;i<3;i++){let a=Qn(s);if(a===null)break;let u;try{u=JSON.parse(a)}catch{break}if(typeof u.status=="number"&&(o=u.status),typeof u.message=="string"&&u.message.trim())s=u.message.trim();else if(typeof u.error=="string"&&u.error.trim())s=u.error.trim();else break}return{message:s,status:o}}function Zn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Ls(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,u,p)=>{!/^https?:\/\//i.test(u)||r.has(u)||n.length>=t||(r.add(u),n.push({title:a.trim()||u,url:u,snippet:p?.trim()||void 0}))},o=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=o.exec(e))!==null;)if(s(Zn(i[1]),Zn(i[2]),i[3]?Zn(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(s(Zn(i[2]),Zn(i[1])),n.length>=t)return n}return n}function fb(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{return JSON.parse(n)}catch{}return null}}function Bs(e){return e.filter(t=>t.title&&t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function Qg(e){if(!e)return[];let t=fb(e,!0);if(t?.success===!1)return[];if(Array.isArray(t?.results)&&t.results.length>0){let n=t.results[0];if(n&&typeof n.query=="string"){let r=[];for(let s of t.results)typeof s.query=="string"&&r.push({query:s.query,answer:s.answer||void 0,sources:Array.isArray(s.results)?Bs(s.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=Bs(t.results);if(r.length>0)return[{query:t.query||"",answer:t.answer||void 0,sources:r}]}}if(t?.query&&typeof t.query=="string")return[{query:t.query,answer:t.answer||void 0,sources:Array.isArray(t.results)?Bs(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=Bs(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let s of n){let o=s.match(/^Title:\s*(.+)/m),i=s.match(/^URL:\s*(.+)/m),a=s.match(/^Author:\s*(.+)/m),u=s.match(/^Published Date:\s*(.+)/m),p=s.match(/^Text:\s*([\s\S]*?)$/m);o&&i&&r.push({title:o[1].trim(),url:i[1].trim(),snippet:p?.[1]?.trim()||void 0,author:a?.[1]?.trim()||void 0,publishedDate:u?.[1]?.trim()||void 0})}if(r.length>0)return[{query:"",sources:r}]}if(typeof e=="string"){let n=Ls(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function Ns(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function hT(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Ns(e)}}function bT(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function _T(e){if(!e)return!1;let t=e.slice(0,600).toLowerCase();return t.includes("<!doctype html")||t.includes("<html")?!0:/<\/(body|head|div|p|span|table)>/i.test(e.slice(0,3e3))}function yb(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let s=r.trim();/^https?:\/\//i.test(s)&&n.push(s)}return n}return[]}function hb(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=Qh(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function PT(e,t){let n=bb(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?hb(r,yb(t)):[]}function bb(e){if(!e)return null;let t=fb(e);if(!t)return null;if(t.results&&Array.isArray(t.results))return{total:t.total||t.results.length,successful:t.successful??t.results.filter(n=>n.success!==!1).length,failed:t.failed??t.results.filter(n=>n.success===!1).length,results:t.results.map(n=>({url:n.url||"",success:n.success!==!1,title:n.title||void 0,content:n.content||n.text||n.snippet||void 0,error:n.error||void 0}))};if(typeof e=="string"){let n=Ls(e);if(n.length>0)return{total:n.length,successful:n.length,failed:0,results:n.map(r=>({url:r.url,success:!0,title:r.title||void 0,content:r.snippet||void 0}))}}return null}function ST(e){if(typeof e!="string"||!e.trim())return null;try{let t=new URL(e.trim());return t.protocol==="http:"||t.protocol==="https:"?t.toString():null}catch{return null}}var xT={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function qs(e){return xT[te(e)]}function tr(e){let t=V(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var wT={run:"Terminal",memory:"Memory"};function vT(e){let t=qs(e);return(t==="hidden"?void 0:wT[t])??tr(e)}function er(e,t,n){return e===1?t:n}function Jg(e){return e.length===0?"":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function Sb(e){return e.length?Os(e[0]):""}function Se(e){return(e.state??{}).input??{}}var AT={agent_spawn:"spawn",agent_task:"spawn",agent_task_create:"spawn",agent_task_start:"spawn",task:"spawn",task_create:"spawn",task_start:"spawn",session_spawn:"spawn",session_start_background:"spawn",agent_message:"message",agent_task_message:"message",task_message:"message",session_message:"message",agent_status:"status",agent_task_list:"status",agent_task_get:"status",task_list:"status",task_get:"status",agent_stop:"stop",agent_task_cancel:"stop",task_cancel:"stop",agent_task_approve:"done",task_approve:"done",task_done:"done",task_delete:"delete"};function kT(e){let t=V(e.tool);if(t==="agent_task_update"||t==="task_update")switch(Se(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return AT[t]??"message"}function _b(e){switch(e){case"create":return"create";case"update":return"update";case"delete":return"delete";case"test":return"test";case"pause":case"resume":return"control";case"list":case"get":return"read";default:return"unknown"}}function RT(e){let t=V(e.tool);if(t==="triggers"){let r=Se(e).action||"list";return _b(r)}let n=t.match(/^trigger_(.+)$/);return _b(n?n[1]:"list")}var CT={connector_setup:"connect",connector_get:"read",connector_list:"read",beeuni_connector_discover:"read",beeuni_connector_describe:"read",beeuni_connectors:"read",beeuni_connectors_connectors:"read",beeuni_connectors_discover:"read",beeuni_connectors_describe:"read",beeuni_connector_call:"call",beeuni_connectors_call:"call"};function IT(e){return CT[V(e.tool)]??"read"}var TT={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function ET(e){return TT[V(e.tool)]??"open"}function Ht(e){return e.every(t=>t===e[0])}var MT={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function OT(e){if(V(e.tool)!=="memory")return"read";let n=Se(e).command;return n&&MT[n]||"unknown"}var DT={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},jT={create_slide:"Added a slide to a presentation",list_slides:"Checked a presentation's slides",list_presentations:"Checked your presentations",delete_slide:"Deleted a slide from a presentation",delete_presentation:"Deleted a presentation",validate_slide:"Checked a slide",export_pdf:"Exported a presentation to PDF",export_pptx:"Exported a presentation to PPTX",preview:"Previewed a presentation",serve:"Previewed a presentation"};function $T(e){let t=je(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function UT(e){let t=Se(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return FT(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return $T(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=ST(o);return i?Ns(i):"a link"}return""}function FT(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function LT(e){let t=Se(e).action;return t&&DT[t]||"Worked on an image"}function BT(e){let t=Se(e).action;return t&&jT[t]||"Worked on a presentation"}function NT(e){return e.slice(0,e.indexOf(":"))}var qT={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},GT={create_slide:"presentation:create_slide",list_slides:"presentation:list_slides",list_presentations:"presentation:list_presentations",delete_slide:"presentation:delete_slide",delete_presentation:"presentation:delete_presentation",validate_slide:"presentation:validate_slide",export_pdf:"presentation:export_pdf",export_pptx:"presentation:export_pptx",preview:"presentation:preview",serve:"presentation:preview"};function WT(e){let t=V(e.tool);if(t==="image_gen"){let n=Se(e).action;return n&&qT[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=Se(e).action;return n&&GT[n]||"presentation:unknown"}return"shown:result"}var KT=new Set(["create_slide","export_pdf","export_pptx"]);function HT(e){let t=V(e.tool);if(t==="image_gen")return"image";if(t==="video_gen")return"video";if(t==="presentation_gen"){let n=Se(e).action;return n?KT.has(n)?"presentation":null:"presentation"}return null}var VT={"image:generate":e=>`Made ${e} images`,"image:edit":e=>`Edited ${e} images`,"image:upscale":e=>`Upscaled ${e} images`,"image:remove_bg":e=>`Removed backgrounds from ${e} images`,"image:unknown":e=>`Worked on ${e} images`,"video:create":e=>`Made ${e} videos`,"presentation:create_slide":e=>`Added ${e} slides`,"presentation:delete_slide":e=>`Deleted ${e} slides`,"presentation:delete_presentation":e=>`Deleted ${e} presentations`,"presentation:list_slides":()=>"Checked a presentation's slides","presentation:list_presentations":()=>"Checked your presentations","presentation:validate_slide":()=>"Checked slides","presentation:export_pdf":e=>`Exported ${e} presentations to PDF`,"presentation:export_pptx":e=>`Exported ${e} presentations to PPTX`,"presentation:preview":e=>`Previewed ${e} presentations`,"presentation:unknown":e=>`Worked on ${e} presentations`,"shown:result":e=>`Showed you ${e} results`},Pb={image:"image",video:"video",presentation:"presentation",shown:"result"};function zT(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[NT(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${er(s,Pb[r],`${Pb[r]}s`)}`)}),`Worked on ${Jg(n)}`}function Xg(e,t){let n=t.length,r=Sb(t);switch(e){case"explore":{let s=t.filter(o=>V(o.tool)==="read").length;return s===n?`Read ${n} ${er(n,"file","files")}`:s===0?"Looked through your files":`Looked through your files \xB7 ${s} read`}case"edit":{let s=new Set(t.map(i=>De(Se(i))).filter(Boolean)).size||n,o=t.every(i=>V(i.tool)==="write")?"Wrote":"Updated";return s===1?r?`${o} ${r}`:`${o} a file`:`${o} ${s} files`}case"run":return n===1?"Ran a command":`Ran ${n} commands`;case"web":{let s=u=>{let p=V(u.tool);return p==="web_search"||p==="websearch"||p==="image_search"},o=t.filter(s).length;if(o===n)return`Searched the web \xB7 ${n} ${er(n,"query","queries")}`;if(o===0)return`Read ${n} ${er(n,"page","pages")}`;let i=new Set;for(let u of t)if(s(u)){let p=u.state?.output;for(let d of Qg(p).flatMap(g=>g.sources))d.url&&i.add(d.url)}else{let p=u.state?.input?.url;typeof p=="string"&&p&&i.add(p)}let a=i.size||n;return`Searched and read ${a} ${er(a,"source","sources")}`}case"create":{if(n===1){let o=t[0],i=V(o.tool);if(i==="image_gen")return LT(o);if(i==="video_gen")return"Made a video";if(i==="presentation_gen")return BT(o);let a=UT(o);return a?`Showed you ${a}`:"Showed you the result"}let s=t.map(WT);return Ht(s)?VT[s[0]](n):zT(s)}case"plan":return n===1?"Planned the work":`Planned the work \xB7 ${n} steps`;case"delegate":{let s=t.map(kT);if(Ht(s))switch(s[0]){case"spawn":return n===1?"Asked a helper agent":`Worked with ${n} helper agents`;case"message":return n===1?"Sent instructions to a helper agent":`Sent instructions to ${n} helper agents`;case"status":return"Checked on a helper agent";case"stop":return n===1?"Stopped a helper agent":`Stopped ${n} helper agents`;case"done":return n===1?"A helper agent finished a task":`Helper agents finished ${n} tasks`;case"delete":return n===1?"Removed a task":`Removed ${n} tasks`}return n===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${n} steps`}case"sessions":return"Checked earlier work";case"memory":{let s=t.map(OT);if(Ht(s))switch(s[0]){case"write":return n===1?"Wrote to its memory":`Wrote to its memory \xB7 ${n} updates`;case"delete":return n===1?"Deleted from its memory":`Deleted ${n} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let s=t.map(IT);if(Ht(s))switch(s[0]){case"connect":return n===1?r?`Connected to ${r}`:"Connected a connector":`Connected ${n} connectors`;case"call":return n===1?"Used a connector":`Made ${n} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let s=t.map(RT);if(Ht(s))switch(s[0]){case"create":return n===1?"Set up an automation":`Set up ${n} automations`;case"update":return n===1?"Updated an automation":`Updated ${n} automations`;case"delete":return n===1?"Deleted an automation":`Deleted ${n} automations`;case"control":return n===1?"Adjusted an automation":`Adjusted ${n} automations`;case"test":return n===1?"Tested an automation":`Tested ${n} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let s=t.map(ET);if(Ht(s))switch(s[0]){case"delete":return n===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${n} projects \u2014 deletion isn't allowed`;case"create":return n===1?r?`Created ${r}`:"Created a project":`Created ${n} projects`;case"update":return n===1?r?`Updated ${r}`:"Updated your project":`Updated ${n} projects`;case"open":return n===1?r?`Opened ${r}`:"Opened your project":`Opened ${n} projects`}return r?`Worked in ${r}`:"Worked in your project"}case"skills":return n===1?r?`Used the ${r} skill`:"Used a skill":`Used ${n} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(n===1)return`Used ${tr(t[0].tool)}`;let s=Array.from(new Set(t.map(o=>tr(o.tool))));return s.length===1?`Used ${s[0]} \xB7 ${n} times`:`Used ${Jg(s)}`}}}function Zg(e,t){let n=Sb(t);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(t.length===1){let r=V(t[0].tool)==="write"?"write":"update";return n?`Couldn't ${r} ${n}`:`Couldn't ${r} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let r=t.filter(i=>i.state?.status==="error"),s=r.length?r:t,o=Array.from(new Set(s.map(i=>tr(i.tool))));return`Couldn't finish using ${Jg(o)}`}}}function YT(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function QT(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let s=r.state.time;typeof s?.start=="number"&&(t=Math.min(t,s.start)),typeof s?.end=="number"&&(n=Math.max(n,s.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function xb(e,t){let n=YT(t);return{id:t[0].callID,family:e,label:n==="error"?Zg(e,t):Xg(e,t),parts:t,status:n,durationMs:n==="running"?void 0:QT(t)}}function em(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(xb(n,r)),n=null,r=[]};for(let o of e){let i=qs(o.tool);if(i!=="hidden"&&!ts(o)){if(Nd(o.tool)){s(),t.push(xb(i,[o]));continue}i!==n&&(s(),n=i),r.push(o)}}return s(),t}function wb(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function JT(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:u}=r,p=typeof a=="number"&&typeof u=="number"&&u>a?u-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of em(s))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});s=[]}};for(let a of e)if(t(a)!=="plumbing"){if(Pe(a)){let u=a.text?.trim();if(!u)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(u);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=wb(a);continue}if(o(),X(a)){s.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}o(),i();for(let a=0;a<n.length-1;a++){let u=n[a];u.kind==="thought"&&(u.running=!1)}return n}var XT=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function ZT(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]*)`/g,"$1").replace(/^#{1,6}\s*/gm,"").replace(/\*\*([^*]*)\*\*/g,"$1").replace(/(^|\s)[*_]([^*_]+)[*_]/g,"$1$2").replace(/^\s*[-*+]\s+/gm,"").replace(/\s+/g," ").trim()}function eE(e){let t=e.flatMap(s=>{let o=ZT(s);return o?[o]:[]}).join(" ").trim();return t?XT.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function Cb(e){return e?.info?.time??{}}function tE(e){let t=Cb(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Gs=6e4,nE=10080*Gs,vb=1440;function Ab(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function rE(e,t){let n=t.getTime()-e.getTime(),r=n/Gs,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<vb)return s(Math.round(r/60),"hour");let o=(n-(Ab(t)-Ab(e)))/Gs;return s(Math.round(o/vb),"day")}function Ib(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}var kb=new Map;function sE(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=kb.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),kb.set(r,s)),s}function Ws(e,t,n){return sE(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?oE(r.value,n):r.value).join("")}function oE(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function Rb(e,t){return Ws(e,{year:"numeric"},t)}function iE(e,t,n={}){let r=Ib(e);if(!r)return"";let s=i=>Ws(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return s(!0);let o=Math.max(0,t-r.getTime());return o<Gs?"just now":o<nE?rE(r,new Date(t)):s(Rb(r,n)!==Rb(new Date(t),n))}function aE(e,t={}){let n=Ib(e);if(!n)return"";let r=Ws(n,{month:"long",day:"numeric",year:"numeric"},t),s=Ws(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function cE(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!qd(o)){if(_e(o)){s(),n.push({kind:"text",part:o});continue}if(X(o)&&(Gd(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function uE(e){let t=le(e);return t==="show"||t==="show_user"}function lE(e,t={}){let n=[],r=[],s=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(o=>o.part)}),r=[]};for(let o of e){if(o.kind==="standalone"&&uE(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var pE=["title","description","path","url","content","language","aspect_ratio","attachment"];function Tb(e,t){if(!t||typeof t!="object")return null;let n=t;if(Rn(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of pE){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function dE(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function gE(e){let t=[];for(let n of e){let r=n.state,s=r.input??{};if(r.status==="error"){let a=typeof s.title=="string"&&s.title?s.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let o=dE(s.items),i=o?o.map(a=>Tb(n.callID,a)).filter(a=>!!a):[Tb(n.callID,s)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function tm(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var mE=e=>e.time?.completed;function fE(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function yE(e,t){let n=e.userMessage.info.id;return t.pendingTurnIds.has(n)||e.assistantMessages.length===0&&t.pendingPromptIds.has(n)}function hE(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(r.userMessage.info.id));if(t)return t.userMessage.info.id;let n=e.turns.findIndex(r=>yE(r,e));return n<=0?null:e.turns[n-1].userMessage.info.id}function bE(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function _E(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function PE(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:tm({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function SE(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].userMessage.info.id;if(t(r))return e[n].assistantMessages.length===0?r:null}return null}function xE(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),s=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(u=>u.userMessage.info.id)}),o=e.hintMessageId??null;if(o){if(n>=0&&t[n].userMessage.info.id===o)return s(n);let a=r.indexOf(o);if(a>=0)return s(n+1+a)}if(n>=0){let a=t[n],u=a.assistantMessages[a.assistantMessages.length-1];if(!mE(u.info)&&!u.info.error)return s(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return s(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:s(n)}function Eb(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>_e(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return X(s)&&s.tool==="bash"}function wE(e){if(Eb(e))return e.assistantMessages[0].parts[0]}function vE(e,t){for(let n=t.length-1;n>=0;n--)if(t[n].info.role==="user")return t[n].info.id===e;return!1}function AE(e,t){return!t||!e?!1:e.type!=="idle"}function kE(e,t){return!e&&!!t}function RE(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ge(n.error)?.message||pe(n.error)}}function CE(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Mg(n.error)}}function IE(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ge(n.error)}}function nm(e){if(e){if(X(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(Pe(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(_e(e))return"Gathering thoughts..."}}function TE(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,s=X(r)?r:void 0;if(s&&(s.tool==="task"||s.tool==="agent_task"||s.tool==="agent-task"||s.tool==="task_create"||s.tool==="task-create"||s.tool==="task_start"||s.tool==="task-start")&&s.state.status==="running"&&t&&t.length>0){for(let i=t.length-1;i>=0;i--){let a=t[i];if(a.info.role==="assistant")for(let u=a.parts.length-1;u>=0;u--){let p=nm(a.parts[u]);if(p)return p}}return"Handing off to an agent..."}let o=nm(r);if(o)return o}return"Figuring out what\u2019s next..."}function EE(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}var rm=1.2;function Mb(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),s=e.cache?.read??0,o=e.cache?.write??0,i=Math.max(0,n-s-o),u=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*u.inputPer1M;return p+=r/1e6*u.outputPer1M,s>0&&(p+=s/1e6*(u.cacheReadPer1M??u.inputPer1M)),o>0&&(p+=o/1e6*(u.cacheWritePer1M??u.inputPer1M)),p}function sm(e,t){return e==="codex"||e==="openai-codex"||e==="beeuni"&&!!t?.startsWith("codex/")}function Ob(e,t,n,r){if(sm(t,n))return 0;let s=e.cost||0;if(s>0)return s;if(!r||!t||!n)return 0;let o=r(t,n);return o?Mb(e.tokens,o):0}function Db(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function ME(e,t){let n=0,r=0,s=0,o=0,i=0,a=0,u=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){u=!0;let g=p,{providerID:m,modelID:f}=Db(d.info);n+=Ob(g,m,f,t),r+=g.tokens?.input||0,s+=g.tokens?.output||0,o+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!u){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=jb(g,t),f=g.tokens&&sm(g.providerID,g.modelID);if(m<=0&&!f)continue;u=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,s+=h.output??0,o+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(u)return{cost:n*rm,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function jb(e,t){if(sm(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?Mb({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function OE(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=Db(s),a=0,u=!1;for(let p of r.parts)p.type==="step-finish"&&(u=!0,a+=Ob(p,o,i,t));u||(a+=jb(s,t)),n+=a}return n*rm}function DE(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function jE(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function $E(e){if(!e||e.type!=="retry")return;let t=e,n=pe(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:ge(t.message)}}function UE(e){if(!(!e||e.type!=="retry"))return pe(e.message)}function FE(e){return(e.info.summary?.diffs?.length??0)>0}function LE(e){if(!e)return"";let t=e;return t=t.replace(/^##\s*Worker Result\s*\n/i,""),t=t.replace(/^\*\*Agent:\*\*.*\n?/m,""),t=t.replace(/^\*\*Task:\*\*.*\n?/m,""),t=t.replace(/^\*\*Status:\*\*.*\n?/m,""),t=t.replace(/^\*\*Session:\*\*.*\n?/m,""),t=t.replace(/^\*\*Duration:\*\*.*\n?/m,""),t=Nh(t,"beeuni_goal_system"),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created and started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created:.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* failed to start.*$/gm,""),t=t.replace(/^Message sent to task.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* approved.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* cancelled.*$/gm,""),t=t.replace(/Worker session: ses_[a-zA-Z0-9]+/g,""),t=t.replace(/^---\s*\n/gm,""),t=t.trim(),t||""}function BE(e){return e?e.split(`
82
- `).filter(n=>n.trim()).length<=3:!1}function NE(e){if(!e)return null;let n=e.split(`
83
- `).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function qE(e){if(!e)return[];let t=[],n=e.split(`
84
- `).filter(r=>r.trim());for(let r of n){let s=Kh(r);if(s){let o=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...s,sessionId:o?.[0]})}}return t}var Qe={write:{verb:"Wrote",running:"Writing",failed:"Couldn't write"},edit:{verb:"Edited",running:"Editing",failed:"Couldn't update"},delete:{verb:"Deleted",running:"Deleting",failed:"Couldn't delete"},rename:{verb:"Renamed",running:"Renaming",failed:"Couldn't rename"},change:{verb:"Changed",running:"Changing",failed:"Couldn't apply"},read:{verb:"Read",running:"Reading",failed:"Couldn't read"},list:{verb:"Listed",running:"Listing",failed:"Couldn't list"}};function GE(e,t){let n=Qe[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function WE(e,t){return t?"failed":e?"running":"done"}var KE={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function HE(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.beeuni\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function VE(e,t){if(!e)return null;let n=e.indexOf(`
85
- `),r=n===-1?e:e.slice(0,n),s=n===-1?"":e.slice(n+1);if(Gh(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
77
+ `)&&(n=n.slice(0,-1)),n)}function df(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let s=e.indexOf(">",r+1+t.length);return s===-1?null:{open:r,end:s}}function aS(e,t){let n=df(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function cS(e,t){let n=df(e,t);if(!n)return null;let r=e.indexOf(`</${t}>`,n.end+1);return r===-1?null:e.slice(n.end+1,r)}function lS(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=df(e,t,s);if(!o)break;let i=e.indexOf(n,o.end+1);if(i===-1)break;r+=e.slice(s,o.open),s=i+n.length}return r+e.slice(s)}function uS(e,t,n){let r=[];for(let s of e.split(/[\n\r\u2028\u2029]/)){let o=0;for(;;){let i=s.indexOf(t,o);if(i===-1)break;let a=s.indexOf(n,i+t.length);if(a===-1)break;r.push(s.slice(i+t.length,a)),o=a+n.length}}return r}function Ir(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&be(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function pS(e,t,n){let r=$t(t),s=$t(n);for(let o of $t(e).split(/[\n\r\u2028\u2029]/)){let i=o.indexOf(r);if(i!==-1&&o.lastIndexOf(s)>=i+r.length)return!0}return!1}function dS(e,t){let n=$t(e),r=t.map($t),s=e.length,o=c=>{let p=c;for(;p<s&&be(e[p]);)p++;return p},i=c=>{for(let p=c;p<s;p++)if(Tr(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let c=o(a);if(c>=s)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=o(c+p.length);if(e[d]===":"){let g=o(d+1);if(g<s){let m=g;for(;m<s&&!Tr(e[m]);)m++;for(;m>g+1&&be(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!Tr(e[m]))return e[m];return null}}a=i(c)}return null}function gS(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=be(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!be(e[a-1]))continue;let c=a+1;if(be(e[c])){for(;c<t&&be(e[c]);)c++;uf(e[c])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(Tr(e[a])?1:0);let o=(a,c)=>s[c]===s[a],i=a=>{let c=a+1;for(;be(e[c]);)c++;let p=c;for(;p<t&&uf(e[p]);)p++;return e.slice(c,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let c=a+7;for(;c<t&&/[a-z0-9]/.test(e[c]);)c++;if(c===a+7||e[c]!=="*"||e[c+1]!=="*")continue;let p=c+2,d=p;for(;d<t&&be(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(o(d,m))return{id:e.slice(a+2,c),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Tr(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function mS(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&be(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&be(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!uf(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&be(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function fS(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(o<c&&(o=e.indexOf("]",c)),o===-1)break;let p=o;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(s,a)+(t?" ":e.slice(c,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function yS(e){return fS(e,!0)}function hS(e){return fS(e,!1)}function cO(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function _S(e,t){let n=$t(e),r=$t(t),s=e.length,o=i=>{let a=i;for(;a<s&&be(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=o(i+r.length);if(e[a]!==":")continue;let c=o(a+1);for(let p=c;p<s;){if(!be(e[p])){p++;continue}let d=o(p);if(cO(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var bS=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function lO(e){return bS.has(le(e))}function uO(e){let t=0,n=0,r=0;for(let s of e){let o=le(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function gf(e){if(!e)return"";let t=tt(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function To(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Eo(e){let t=He(e),r=(t.state??{}).input??{};switch(ee(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=r.filePath??r.file_path??r.path;return i?gf(String(i)):""}case"glob":return r.pattern?String(r.pattern):"";case"grep":{let i=r.pattern??r.query,a=r.path??r.include;return i&&a?`"${To(String(i),40)}" in ${gf(String(a))}`:i?`"${To(String(i),60)}"`:""}case"list":return r.path?gf(String(r.path)):"";case"bash":return To(String(r.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let i of o){let a=r[i];if(typeof a=="string"&&a.length>0)return To(i==="query"&&Cr(a)||a,60)}return""}var SS={read:"Read",search:"Search",list:"List",shell:"Shell",edit:"Edit",write:"Write",fetch:"Fetch",webSearch:"Web Search",scrape:"Scrape",applyPatch:"Apply Patch",task:"Task",worker:"Worker",workspace:"Workspace"};function pO(e,t={}){let n=ye(e)?ae(e):e,r={...SS,...t},s=ee(n.tool),o=Eo(n);switch(s){case"read":return{title:r.read,subtitle:o};case"glob":case"grep":return{title:r.search,subtitle:o};case"list":return{title:r.list,subtitle:o};case"bash":return{title:r.shell,subtitle:o};case"edit":case"morph_edit":return{title:r.edit,subtitle:o};case"write":return{title:r.write,subtitle:o};case"webfetch":case"web_fetch":return{title:r.fetch,subtitle:o};case"websearch":case"web_search":return{title:r.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:r.scrape,subtitle:o};case"apply_patch":return{title:r.applyPatch,subtitle:o};case"task":return{title:r.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:r.worker,subtitle:o};case"project_select":case"project_list":return{title:r.workspace,subtitle:o};default:return{title:s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase()),subtitle:o}}}function De(e){return e.type==="text"}function Ae(e){return e.type==="reasoning"}function te(e){return e.type==="tool"}function ff(e){return e.type==="file"}function dO(e){return e.type==="agent"}function gO(e){return e.type==="compaction"}function mO(e){return e.type==="snapshot"}function fO(e){return e.type==="patch"}function yO(e){return e.type==="step-start"||e.type==="step-finish"}function hO(e){if(De(e)||Ae(e))return e.text}function _O(e){if(!ff(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function bO(e){let t=[],n=[];for(let r of e)ff(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function SO(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function PO(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var xO=new Set(["todoread","context_info"]);function _n(e){return!xO.has(ye(e)?e.name:e.tool)}var wO=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function Or(e){let t=ye(e)?ae(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=le(n);if(r==="task"||r==="delegate"){let s=t.state?.metadata?.sessionId;if(typeof s=="string"&&s)return s;if(r==="task"&&t.state?.status==="error")return t.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return vO(n,t.state)}function vO(e,t){let n=ee(e);if(wO.has(n)){let r=t?.title?.match(/\bses_[a-zA-Z0-9]+/);return r?r[0]:t?.output?.match(/\bses_[a-zA-Z0-9]+/)?.[0]}if(n==="session_spawn"||n==="session_start_background")return t?.output?.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/)?.[1]}function AO(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return _e(n.error)}}function kO(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)te(r)&&_n(r)&&t.push(r);return t}function RO(e,t={}){switch(ee(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:wS(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"BeeuniWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"apply_patch":return{icon:"file-pen",title:"Patch",subtitle:t.files?.length?`${t.files.length} file${t.files.length>1?"s":""}`:void 0};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"prune":return{icon:"scissors",title:"DCP Prune",subtitle:t.reason};case"distill":return{icon:"scissors",title:"DCP Distill"};case"compress":return{icon:"scissors",title:"DCP Compress",subtitle:t.topic};case"context_info":return{icon:"scissors",title:"Context Info"};case"session_read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session_list_spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":return{icon:"folder",title:"Projects"};case"project_get":case"project_update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":return{icon:"clock",title:"List Triggers"};case"trigger_get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":return{icon:"layers",title:"Agent Status"};case"agent_task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":return{icon:"trash-2",title:"Delete Task",subtitle:t.id};case"pty_spawn":return{icon:"terminal",title:"Spawn",subtitle:t.title||t.command};case"pty_read":return{icon:"terminal",title:"Terminal Output",subtitle:t.id};case"pty_write":case"pty_input":return{icon:"terminal",title:"Terminal Input",subtitle:t.id};case"pty_kill":return{icon:"terminal",title:"Kill Process",subtitle:t.id};default:return CO(e,t)}}function CO(e,t){switch(le(e)){case"read":return{icon:"glasses",title:"Read",subtitle:PS(et(t))};case"list":return{icon:"list",title:"List",subtitle:xS(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":return{icon:"file-pen",title:"Edit",subtitle:mf(et(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:mf(et(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function PS(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function mf(e){if(!e)return;let t=e.split("/"),n=t[t.length-1]||e;if(t.length<=1)return n;let r=t[t.length-2];return r?`${n} /${r}`:n}function xS(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function TO(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function Mr(e,t=120){if(typeof e!="string")return"";let n=e.split(`
78
+ `).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function wS(e){let t=Mr(e.description);if(t)return t;let n=Mr(e.title,80);if(n)return n;let r=Mr(e.message);if(r)return r;let s=Mr(e.prompt);if(s)return s;let o=Mr(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function EO(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function IO(e,t){return e.find(n=>n.tool?.callID===t)}function MO(e,t){return e.find(n=>n.tool?.callID===t)}var OO=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function DO(e){return e?e.replace(OO,""):""}function Io(e){let t=vS(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let s=r&&typeof r=="object"?vS(r):void 0;return s?[s]:[]})}function vS(e){let t=e?.oldString??e?.old_string??e?.oldText,n=e?.newString??e?.new_string??e?.newText;return typeof t=="string"&&typeof n=="string"?[t,n]:void 0}var jO={bash:"Shell",pty_spawn:"Spawn Terminal",pty_read:"Terminal Output",pty_write:"Terminal Input",pty_input:"Terminal Input",pty_kill:"Kill Process",read:"Read File",list:"List Directory",ls:"List Directory",write:"Write File",edit:"Edit File",multiedit:"Edit File",morph_edit:"Edit File",apply_patch:"Apply Patch",patch:"Apply Patch",grep:"Search Code",glob:"Find Files",image_search:"Image Search",session_search:"Search Sessions",webfetch:"Fetch Page",scrape_webpage:"Scrape Page",websearch:"Web Search",web_search:"Web Search",image_gen:"Generate Image",video_gen:"Generate Video",task:"Delegate to Agent",todowrite:"Plan Tasks",todoread:"Read Plan",question:"Ask Question",presentation_gen:"Presentation",show:"Show Output",show_user:"Show Output",prune:"Prune Context",distill:"Distill Context",compress:"Compress Context",context_info:"Context Info"},LO={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",script:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function $O(e){return e.replace(/^oc[-_]/,"")}function yf(e){return $O(e).replace(/-/g,"_")}function hf(e){return yf(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Mo(e){return{label:jO[yf(e)]??hf(e),category:LO[le(e)]}}var BO=256*1024;function UO(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function FO(e){if(e===void 0)return{};if(e.length>BO)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function NO(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,s=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!s))return s?_e(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var ge=e=>typeof e=="string"?e:void 0,Oo=e=>typeof e=="number"?e:void 0,Do=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function _f(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var qO=new Set(["add","update","delete","move"]);function GO(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=Do(d),m=g&&(ge(g.relativePath)||ge(g.filePath));if(!g||!m)return[];let f=ge(g.type);return[_f({path:m,type:f&&qO.has(f)?f:void 0,before:ge(g.before),after:ge(g.after),patch:ge(g.patch)??ge(g.diff),additions:Oo(g.additions),deletions:Oo(g.deletions),movePath:ge(g.movePath)})]});return p.length?p:void 0}let r=et(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[_f({path:r,after:ge(t.content)})];if(e!=="edit")return;let s=Do(n.filediff),o=s?void 0:ge(n.patch),i=o?WO(o):void 0,a=s||o?[]:Io(t);return[_f({path:r,before:ge(s?.before)??(a.length?a.map(([c])=>c).join(`
79
+ `):void 0),after:ge(s?.after)??(a.length?a.map(([,c])=>c).join(`
80
+ `):ge(t.new_source)),patch:o,additions:Oo(s?.additions)??i?.additions,deletions:Oo(s?.deletions)??i?.deletions})]}function WO(e){let t=0,n=0;for(let r of e.split(`
81
+ `))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function KO(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function AS(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=FO(r),i=UO(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=NO(s);m&&(i="error",a=m)}let c=le(e),p=t.input??{},d="metadata"in t&&Do(t.metadata)||{},g=Do(d.diagnostics);return{name:e,kind:c,title:n||Mo(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:GO(c,p,d),diff:ge(d.patch)??ge(d.diff),diagnostics:g,answers:c==="question"?KO(d):void 0,childSessionId:Or({tool:e,state:t})}}function bf(e){let t=ye(e)?ae(e):e;return AS(t.tool,t.state)}function VO(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function HO(e){return{kind:"reasoning",id:e.id,text:e.text}}function zO(e){return{kind:"tool",id:e.id,tool:AS(e.tool,e.state)}}function YO(e){let t=e.mime;return{kind:"file",id:e.id,filename:e.filename,mime:t,url:e.url,isImage:t.startsWith("image/"),isPdf:t==="application/pdf"}}function JO(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function QO(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function XO(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function ZO(e){return{kind:"agent",id:e.id,name:e.name}}function eD(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:_e(e.error),createdAt:e.time.created}}function tD(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function nD(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function rD(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Sf(e){switch(e.type){case"text":return VO(e);case"reasoning":return HO(e);case"tool":return zO(e);case"file":return YO(e);case"subtask":return JO(e);case"patch":return QO(e);case"snapshot":return XO(e);case"agent":return ZO(e);case"retry":return eD(e);case"compaction":return tD(e);case"step-start":return nD(e);case"step-finish":return rD(e);default:return{kind:"unknown",raw:e}}}function sD(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=we(e);return{name:t,message:n?.message||_e(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function oD(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function jo(e){let t=e.parts.map(Sf),n=e.info.role==="assistant"?e.info.error:void 0,r=sD(n),s=!r&&!t.some(oD);return{parts:t,error:r,isEmpty:s}}var Pf=Qe+BigInt(1),kS=Pf/BigInt(2);function Lo(e){return BigInt(Math.trunc(e))*nn}function xf(e,t){let r=t-(t&Qe)+e;return r-t>kS?r-=Pf:t-r>kS&&(r+=Pf),r}function RS(e,t){let n=Dt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return xf(n,t);let s=Lo(r),o=xf(n,s);return(o>s?o-s:s-o)<=pt?o:s}function CS(e){return Dt(e)===null?1:0}function TS(e,t){return e<t?-1:e>t?1:0}function iD(e,t){return ES(e,t,Lo(Date.now()))}function aD(e){let t=null;for(let n of e){let r=n.info.time?.created;typeof r=="number"&&(t===null||r>t)&&(t=r)}return Lo(t??Date.now())}function ES(e,t,n){let r=CS(e.info.id),s=CS(t.info.id);if(r!==s)return r-s;if(r===0){let a=RS(e,n),c=RS(t,n);return a!==c?a<c?-1:1:TS(e.info.id,t.info.id)}let o=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return o===null&&i===null?0:o===null?1:i===null?-1:o!==i?o<i?-1:1:TS(e.info.id,t.info.id)}function cD(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=aD(e),s=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:ES(d,g,r)}),o=[],i=new Map;for(let d of s)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};o.push(g),i.set(d.info.id,g)}let a=null,c=[],p=[];for(let d of s){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=c[c.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):c.push({userMessage:uD(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=o[0]??c[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;o.push({userMessage:g,assistantMessages:m})}}return c.length>0?[...c,...o]:o}var Dr=new Map,lD=256;function uD(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=Dr.get(s);if(o)return o;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(Dr.size>=lD){let a=Dr.keys().next().value;a!==void 0&&Dr.delete(a)}return Dr.set(s,i),i}function pD(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function dD(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(De(n)&&n.text?.trim())return n}}function gD(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function mD(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!te(o))continue;let i=o,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:o,message:s})}return r}function fD(e){let t=new Map;for(let n of e){if(!n.parentID)continue;let r=t.get(n.parentID);r?r.push(n.id):t.set(n.parentID,[n.id])}return t}function yD(e){let t=e-6e4;return(n,r)=>{let s=n.time.updated??n.time.created,o=r.time.updated??r.time.created,i=s>t,a=o>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:o-s}}function IS(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let s of n)r.push(s),r.push(...IS(e,s));return r}function MS(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function wf(e){if(!e?.length)return!1;for(let t=e.length-1;t>=0;t--){let n=e[t].info;if(n.role==="assistant")return!n.time?.completed&&MS(n.error)}return!1}function $o(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vf(e){let t=e.trim();return t.length>500?!1:!!(/^Error:\s/i.test(t)||/^([\w._-]+Error|[\w._-]+Exception):\s/i.test(t)||/Traceback \(most recent call last\)/i.test(t)||/^\s*\[\s*\{[\s\S]*"message"\s*:/.test(t))}function hD(e){return!!e&&(vf(e)||DS(e)!==null)}function Bo(e){let t=ye(e)?ae(e):e,n=OS.get(t);if(n&&n.state===t.state)return n.outcome;let r=_D(t);return OS.set(t,{state:t.state,outcome:r}),r}var OS=new WeakMap;function _D(e){let t=e.state;if(t.status==="error")return"failed";if(t.status!=="completed")return"ok";let n=typeof t.output=="string"?t.output.trim():"";if(!n)return"ok";if(vf(n))return"failed";let r=bD(n);return r===void 0?"ok":SD(r)?"failed":PD(r)}function bD(e){try{return JSON.parse(e)}catch{return}}function SD(e){return $o(e)&&e.success===!1&&typeof e.error=="string"}function PD(e){let t=$o(e)?e.results:void 0;if(!Array.isArray(t)||t.length===0)return"ok";let n=t.filter(r=>r!==null&&typeof r=="object"&&r.success===!1).length;return n===0?"ok":n===t.length?"failed":"partial"}function DS(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!$o(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},s=Ir(r.errorSummary);if(s===null)return r;try{let o=JSON.parse(s);typeof o.message=="string"&&o.message.trim()&&(r.nestedMessage=o.message.trim()),typeof o.status=="number"&&(r.status=o.status),typeof o.error=="boolean"&&(r.nestedError=o.error)}catch{}return r}function xD(e){return mS(e).replace(/\s+/g," ").trim()||e.trim()}function wD(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!$o(n))return null;let r=n.success,s=n.error,o=n.hint;if(r!==!1||typeof s!="string")return null;let i=[];i.push(s.trim());let a=Ir(s);if(a!==null)try{let p=JSON.parse(a).message;typeof p=="string"&&p.trim()&&i.push(`Details: ${p.trim()}`)}catch{}return typeof o=="string"&&o.trim()&&i.push(`Hint: ${o.trim()}`),i.join(`
82
+
83
+ `)}function vD(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function AD(e,t=2e3){let n=(e??"").trim();try{let r=JSON.parse(n);if(typeof r=="string")try{r=JSON.parse(r)}catch{}r&&typeof r=="object"&&(n=JSON.stringify(r,null,2))}catch{}return n.length>t?{text:n.slice(0,t).trimEnd(),truncatedChars:n.length-t}:{text:n,truncatedChars:0}}function kD(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=yS(n),n=hS(n),n=n.replace(/[#*_`>]+/g," "),n=n.replace(/\s+/g," ").trim(),n=n.replace(/\b(\w{2,})(?:\s+\1\b)+/gi,"$1"),n.length>t?n.slice(0,t).trimEnd()+"\u2026":n}function RD(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let s=r.error.trim(),o;for(let i=0;i<3;i++){let a=Ir(s);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(o=c.status),typeof c.message=="string"&&c.message.trim())s=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())s=c.error.trim();else break}return{message:s,status:o}}function jr(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Uo(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},o=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=o.exec(e))!==null;)if(s(jr(i[1]),jr(i[2]),i[3]?jr(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(s(jr(i[2]),jr(i[1])),n.length>=t)return n}return n}function jS(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{return JSON.parse(n)}catch{}return null}}function Fo(e){return e.filter(t=>t.title&&t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function Af(e){if(!e)return[];let t=jS(e,!0);if(t?.success===!1)return[];if(Array.isArray(t?.results)&&t.results.length>0){let n=t.results[0];if(n&&typeof n.query=="string"){let r=[];for(let s of t.results)typeof s.query=="string"&&r.push({query:s.query,answer:s.answer||void 0,sources:Array.isArray(s.results)?Fo(s.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=Fo(t.results);if(r.length>0)return[{query:t.query||"",answer:t.answer||void 0,sources:r}]}}if(t?.query&&typeof t.query=="string")return[{query:t.query,answer:t.answer||void 0,sources:Array.isArray(t.results)?Fo(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=Fo(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let s of n){let o=s.match(/^Title:\s*(.+)/m),i=s.match(/^URL:\s*(.+)/m),a=s.match(/^Author:\s*(.+)/m),c=s.match(/^Published Date:\s*(.+)/m),p=s.match(/^Text:\s*([\s\S]*?)$/m);o&&i&&r.push({title:o[1].trim(),url:i[1].trim(),snippet:p?.[1]?.trim()||void 0,author:a?.[1]?.trim()||void 0,publishedDate:c?.[1]?.trim()||void 0})}if(r.length>0)return[{query:"",sources:r}]}if(typeof e=="string"){let n=Uo(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function No(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function CD(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return No(e)}}function TD(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function ED(e){if(!e)return!1;let t=e.slice(0,600).toLowerCase();return t.includes("<!doctype html")||t.includes("<html")?!0:/<\/(body|head|div|p|span|table)>/i.test(e.slice(0,3e3))}function LS(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let s=r.trim();/^https?:\/\//i.test(s)&&n.push(s)}return n}return[]}function $S(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=_S(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function ID(e,t){let n=BS(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?$S(r,LS(t)):[]}function BS(e){if(!e)return null;let t=jS(e);if(!t)return null;if(t.results&&Array.isArray(t.results))return{total:t.total||t.results.length,successful:t.successful??t.results.filter(n=>n.success!==!1).length,failed:t.failed??t.results.filter(n=>n.success===!1).length,results:t.results.map(n=>({url:n.url||"",success:n.success!==!1,title:n.title||void 0,content:n.content||n.text||n.snippet||void 0,error:n.error||void 0}))};if(typeof e=="string"){let n=Uo(e);if(n.length>0)return{total:n.length,successful:n.length,failed:0,results:n.map(r=>({url:r.url,success:!0,title:r.title||void 0,content:r.snippet||void 0}))}}return null}function MD(e){if(typeof e!="string"||!e.trim())return null;try{let t=new URL(e.trim());return t.protocol==="http:"||t.protocol==="https:"?t.toString():null}catch{return null}}var OD={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",script:"script",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function Sn(e){return OD[le(e)]}function $r(e){let t=ee(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var DD={run:"Terminal",memory:"Memory"};function jD(e){let t=Sn(e);return(t==="hidden"?void 0:DD[t])??$r(e)}function Lr(e,t,n){return e===1?t:n}function kf(e){return e.length===0?"":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function NS(e){return e.length?Eo(e[0]):""}function je(e){return(e.state??{}).input??{}}var LD={agent_spawn:"spawn",agent_task:"spawn",agent_task_create:"spawn",agent_task_start:"spawn",task:"spawn",task_create:"spawn",task_start:"spawn",session_spawn:"spawn",session_start_background:"spawn",agent_message:"message",agent_task_message:"message",task_message:"message",session_message:"message",agent_status:"status",agent_task_list:"status",agent_task_get:"status",task_list:"status",task_get:"status",agent_stop:"stop",agent_task_cancel:"stop",task_cancel:"stop",agent_task_approve:"done",task_approve:"done",task_done:"done",task_delete:"delete"};function $D(e){let t=ee(e.tool);if(t==="agent_task_update"||t==="task_update")switch(je(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return LD[t]??"message"}function US(e){switch(e){case"create":return"create";case"update":return"update";case"delete":return"delete";case"test":return"test";case"pause":case"resume":return"control";case"list":case"get":return"read";default:return"unknown"}}function BD(e){let t=ee(e.tool);if(t==="triggers"){let r=je(e).action||"list";return US(r)}let n=t.match(/^trigger_(.+)$/);return US(n?n[1]:"list")}var UD={connector_setup:"connect",connector_get:"read",connector_list:"read",beeuni_connector_discover:"read",beeuni_connector_describe:"read",beeuni_connectors:"read",beeuni_connectors_connectors:"read",beeuni_connectors_discover:"read",beeuni_connectors_describe:"read",beeuni_connector_call:"call",beeuni_connectors_call:"call"};function FD(e){return UD[ee(e.tool)]??"read"}var ND={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function qD(e){return ND[ee(e.tool)]??"open"}function bn(e){return e.every(t=>t===e[0])}var GD={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function WD(e){if(ee(e.tool)!=="memory")return"read";let n=je(e).command;return n&&GD[n]||"unknown"}var KD={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},VD={create_slide:"Added a slide to a presentation",list_slides:"Checked a presentation's slides",list_presentations:"Checked your presentations",delete_slide:"Deleted a slide from a presentation",delete_presentation:"Deleted a presentation",validate_slide:"Checked a slide",export_pdf:"Exported a presentation to PDF",export_pptx:"Exported a presentation to PPTX",preview:"Previewed a presentation",serve:"Previewed a presentation"};function HD(e){let t=tt(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function zD(e){let t=je(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return YD(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return HD(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=MD(o);return i?No(i):"a link"}return""}function YD(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function JD(e){let t=je(e).action;return t&&KD[t]||"Worked on an image"}function QD(e){let t=je(e).action;return t&&VD[t]||"Worked on a presentation"}function XD(e){return e.slice(0,e.indexOf(":"))}var ZD={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},ej={create_slide:"presentation:create_slide",list_slides:"presentation:list_slides",list_presentations:"presentation:list_presentations",delete_slide:"presentation:delete_slide",delete_presentation:"presentation:delete_presentation",validate_slide:"presentation:validate_slide",export_pdf:"presentation:export_pdf",export_pptx:"presentation:export_pptx",preview:"presentation:preview",serve:"presentation:preview"};function tj(e){let t=ee(e.tool);if(t==="image_gen"){let n=je(e).action;return n&&ZD[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=je(e).action;return n&&ej[n]||"presentation:unknown"}return"shown:result"}var nj=new Set(["create_slide","export_pdf","export_pptx"]);function rj(e){let t=He(e),n=ee(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=je(t).action;return r?nj.has(r)?"presentation":null:"presentation"}return null}var sj={"image:generate":e=>`Made ${e} images`,"image:edit":e=>`Edited ${e} images`,"image:upscale":e=>`Upscaled ${e} images`,"image:remove_bg":e=>`Removed backgrounds from ${e} images`,"image:unknown":e=>`Worked on ${e} images`,"video:create":e=>`Made ${e} videos`,"presentation:create_slide":e=>`Added ${e} slides`,"presentation:delete_slide":e=>`Deleted ${e} slides`,"presentation:delete_presentation":e=>`Deleted ${e} presentations`,"presentation:list_slides":()=>"Checked a presentation's slides","presentation:list_presentations":()=>"Checked your presentations","presentation:validate_slide":()=>"Checked slides","presentation:export_pdf":e=>`Exported ${e} presentations to PDF`,"presentation:export_pptx":e=>`Exported ${e} presentations to PPTX`,"presentation:preview":e=>`Previewed ${e} presentations`,"presentation:unknown":e=>`Worked on ${e} presentations`,"shown:result":e=>`Showed you ${e} results`},FS={image:"image",video:"video",presentation:"presentation",shown:"result"};function oj(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[XD(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Lr(s,FS[r],`${FS[r]}s`)}`)}),`Worked on ${kf(n)}`}function Br(e,t){let n=t.map(He),r=n.length,s=NS(n);switch(e){case"explore":{let o=n.filter(i=>ee(i.tool)==="read").length;return o===r?`Read ${r} ${Lr(r,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(n.map(a=>et(je(a))).filter(Boolean)).size||r,i=n.every(a=>ee(a.tool)==="write")?"Wrote":"Updated";return o===1?s?`${i} ${s}`:`${i} a file`:`${i} ${o} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"script":return r===1?"Ran a script":`Ran ${r} scripts`;case"web":{let o=p=>{let d=ee(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(o).length;if(i===r)return`Searched the web \xB7 ${r} ${Lr(r,"query","queries")}`;if(i===0)return`Read ${r} ${Lr(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of Af(d).flatMap(m=>m.sources))g.url&&a.add(g.url)}else{let d=p.state?.input?.url;typeof d=="string"&&d&&a.add(d)}let c=a.size||r;return`Searched and read ${c} ${Lr(c,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return JD(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return QD(i);let c=zD(i);return c?`Showed you ${c}`:"Showed you the result"}let o=n.map(tj);return bn(o)?sj[o[0]](r):oj(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map($D);if(bn(o))switch(o[0]){case"spawn":return r===1?"Asked a helper agent":`Worked with ${r} helper agents`;case"message":return r===1?"Sent instructions to a helper agent":`Sent instructions to ${r} helper agents`;case"status":return"Checked on a helper agent";case"stop":return r===1?"Stopped a helper agent":`Stopped ${r} helper agents`;case"done":return r===1?"A helper agent finished a task":`Helper agents finished ${r} tasks`;case"delete":return r===1?"Removed a task":`Removed ${r} tasks`}return r===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${r} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=n.map(WD);if(bn(o))switch(o[0]){case"write":return r===1?"Wrote to its memory":`Wrote to its memory \xB7 ${r} updates`;case"delete":return r===1?"Deleted from its memory":`Deleted ${r} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=n.map(FD);if(bn(o))switch(o[0]){case"connect":return r===1?s?`Connected to ${s}`:"Connected a connector":`Connected ${r} connectors`;case"call":return r===1?"Used a connector":`Made ${r} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=n.map(BD);if(bn(o))switch(o[0]){case"create":return r===1?"Set up an automation":`Set up ${r} automations`;case"update":return r===1?"Updated an automation":`Updated ${r} automations`;case"delete":return r===1?"Deleted an automation":`Deleted ${r} automations`;case"control":return r===1?"Adjusted an automation":`Adjusted ${r} automations`;case"test":return r===1?"Tested an automation":`Tested ${r} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=n.map(qD);if(bn(o))switch(o[0]){case"delete":return r===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${r} projects \u2014 deletion isn't allowed`;case"create":return r===1?s?`Created ${s}`:"Created a project":`Created ${r} projects`;case"update":return r===1?s?`Updated ${s}`:"Updated your project":`Updated ${r} projects`;case"open":return r===1?s?`Opened ${s}`:"Opened your project":`Opened ${r} projects`}return s?`Worked in ${s}`:"Worked in your project"}case"skills":return r===1?s?`Used the ${s} skill`:"Used a skill":`Used ${r} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(r===1)return`Used ${$r(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>$r(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${kf(o)}`}}}function Rf(e,t){let n=t.map(He),r=NS(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let s=ee(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${s} ${r}`:`Couldn't ${s} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let s=n.filter(a=>a.state?.status==="error"),o=s.length?s:n,i=Array.from(new Set(o.map(a=>$r(a.tool))));return`Couldn't finish using ${kf(i)}`}}}var qS=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),ij={read:{verb:"Read",running:"Reading",objectKeys:["filePath","path","file"]},write:{verb:"Wrote",running:"Writing",objectKeys:["filePath","path","file"]},edit:{verb:"Edited",running:"Editing",objectKeys:["filePath","path","file"]},apply_patch:{verb:"Edited",running:"Editing",objectKeys:["filePath","path"]},bash:{verb:"Ran",running:"Running",objectKeys:["command"]},glob:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},grep:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},list:{verb:"Listed",running:"Listing",objectKeys:["path"]},web_search:{verb:"Searched",running:"Searching",objectKeys:["query"]},websearch:{verb:"Searched",running:"Searching",objectKeys:["query"]},webfetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},web_fetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},scrape:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},scrape_webpage:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},task:{verb:"Delegated",running:"Delegating",objectKeys:["description"]},memory:{verb:"Remembered",running:"Remembering"},get_mem:{verb:"Recalled",running:"Recalling"},memory_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},mem_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},ltm_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},dcp_compress:{verb:"Compacted",running:"Compacting"},dcp_distill:{verb:"Distilled",running:"Distilling"},dcp_prune:{verb:"Pruned",running:"Pruning"},compress:{verb:"Compacted",running:"Compacting"},distill:{verb:"Distilled",running:"Distilling"},prune:{verb:"Pruned",running:"Pruning"},context_info:{verb:"Checked context",running:"Checking context"}};function aj(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Cr(t)||t}function cj(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let s=n[r];if(typeof s=="string"&&s.trim())return aj(r,s.trim())}}function Pn(e){let t=ye(e)?ae(e):e;if(Ae(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!te(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=he(t.tool),r=ij[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:cj(s,r.objectKeys),tier:qS.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function qo(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(Pn(o).tier==="plumbing"){r=!0;continue}if(Ae(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,te(o)&&Bo(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function Cf(e){return`${e} ${e===1?"step":"steps"}`}function GS(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${Cf(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${Cf(n)}`:s===0?`${Cf(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function Tf(e){let t=new Map,n=0;for(let s of e){if(!te(s)||Pn(s).tier==="plumbing")continue;let o=Sn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),Bo(s)!=="ok"&&(n+=1))}if(t.size===0)return GS(qo(e),!1);let r=[...t].map(([s,o],i)=>{let a=Br(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function lj(e){let t=!1,n=!1,r=!1,s=null,o=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),s==null&&d.error!=null&&(s=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(t=!0),e.userMessage&&o(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)o(p.info),i(p.parts);return c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function uj(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function pj(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let s=r.state.time;typeof s?.start=="number"&&(t=Math.min(t,s.start)),typeof s?.end=="number"&&(n=Math.max(n,s.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function WS(e,t){let n=t.map(He),r=uj(n);return{id:n[0].callID,family:e,label:r==="error"?Rf(e,n):Br(e,n),parts:t,status:r,durationMs:r==="running"?void 0:pj(n)}}function Ef(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(WS(n,r)),n=null,r=[]};for(let o of e){let i=He(o),a=Sn(i.tool);if(a!=="hidden"&&!zs(i)){if(Gg(i.tool)){s(),t.push(WS(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function Go(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function If(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of Ef(s))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});s=[]}};for(let a of e)if(t(a)!=="plumbing"){if(Ae(a)){let c=a.text?.trim();if(!c)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(c);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=Go(a);continue}if(o(),te(a)){s.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}o(),i();for(let a=0;a<n.length-1;a++){let c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var dj=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function gj(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]*)`/g,"$1").replace(/^#{1,6}\s*/gm,"").replace(/\*\*([^*]*)\*\*/g,"$1").replace(/(^|\s)[*_]([^*_]+)[*_]/g,"$1$2").replace(/^\s*[-*+]\s+/gm,"").replace(/\s+/g," ").trim()}function mj(e){let t=e.flatMap(s=>{let o=gj(s);return o?[o]:[]}).join(" ").trim();return t?dj.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function YS(e){return e?.info?.time??{}}function fj(e){let t=YS(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Wo=6e4,yj=10080*Wo,KS=1440;function VS(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function hj(e,t){let n=t.getTime()-e.getTime(),r=n/Wo,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<KS)return s(Math.round(r/60),"hour");let o=(n-(VS(t)-VS(e)))/Wo;return s(Math.round(o/KS),"day")}function JS(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}var HS=new Map;function _j(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=HS.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),HS.set(r,s)),s}function Ko(e,t,n){return _j(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?bj(r.value,n):r.value).join("")}function bj(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function zS(e,t){return Ko(e,{year:"numeric"},t)}function Sj(e,t,n={}){let r=JS(e);if(!r)return"";let s=i=>Ko(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return s(!0);let o=Math.max(0,t-r.getTime());return o<Wo?"just now":o<yj?hj(r,new Date(t)):s(zS(r,n)!==zS(new Date(t),n))}function Pj(e,t={}){let n=JS(e);if(!n)return"";let r=Ko(n,{month:"long",day:"numeric",year:"numeric"},t),s=Ko(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function Mf(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!Wg(o)){if(De(o)){s(),n.push({kind:"text",part:o});continue}if(te(o)&&(Kg(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function xj(e){let t=he(e);return t==="show"||t==="show_user"}function Of(e,t={}){let n=[],r=[],s=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(o=>o.part)}),r=[]};for(let o of e){if(o.kind==="standalone"&&xj(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var wj=["title","description","path","url","content","language","aspect_ratio","attachment"];function QS(e,t){if(!t||typeof t!="object")return null;let n=t;if(or(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of wj){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function vj(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function Df(e){let t=[];for(let n of e){let r=n.state,s=r.input??{};if(r.status==="error"){let a=typeof s.title=="string"&&s.title?s.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let o=vj(s.items),i=o?o.map(a=>QS(n.callID,a)).filter(a=>!!a):[QS(n.callID,s)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function jf(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Ur=e=>"id"in e?e.id:e.userMessage.info.id,XS=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,Aj=e=>e.time?.completed;function kj(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function Rj(e,t){let n=Ur(e);return t.pendingTurnIds.has(n)||XS(e)===0&&t.pendingPromptIds.has(n)}function Cj(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Ur(r)));if(t)return Ur(t);let n=e.turns.findIndex(r=>Rj(r,e));return n<=0?null:Ur(e.turns[n-1])}function Tj(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function Ej(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function Ij(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:jf({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function Mj(e,t){for(let n=e.length-1;n>=0;n--){let r=Ur(e[n]);if(t(r))return XS(e[n])===0?r:null}return null}function Lf(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),s=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(c=>c.userMessage.info.id)}),o=e.hintMessageId??null;if(o){if(n>=0&&t[n].userMessage.info.id===o)return s(n);let a=r.indexOf(o);if(a>=0)return s(n+1+a)}if(n>=0){let a=t[n],c=a.assistantMessages[a.assistantMessages.length-1];if(!Aj(c.info)&&!c.info.error)return s(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return s(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:s(n)}function Oj(e,t){for(let n=t.length-1;n>=0;n--)if(t[n].info.role==="user")return t[n].info.id===e;return!1}function Dj(e,t){return!t||!e?!1:e.type!=="idle"}function jj(e,t){return!e&&!!t}function Lj(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return we(n.error)?.message||_e(n.error)}}function $j(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Rr(n.error)}}function Bj(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return we(n.error)}}function $f(e){if(e){if(te(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(Ae(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(De(e))return"Gathering thoughts..."}}function Bf(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,s=te(r)?r:void 0;if(s&&(s.tool==="task"||s.tool==="agent_task"||s.tool==="agent-task"||s.tool==="task_create"||s.tool==="task-create"||s.tool==="task_start"||s.tool==="task-start")&&s.state.status==="running"&&t&&t.length>0){for(let i=t.length-1;i>=0;i--){let a=t[i];if(a.info.role==="assistant")for(let c=a.parts.length-1;c>=0;c--){let p=$f(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let o=$f(r);if(o)return o}return"Figuring out what\u2019s next..."}function Uf(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}function Ff(e){let t={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},n=!1,r=i=>{n=!0,t.input+=i.input??0,t.output+=i.output??0,t.reasoning+=i.reasoning??0,t.cacheRead+=i.cache?.read??0,t.cacheWrite+=i.cache?.write??0},s=new Set;for(let{part:i,message:a}of e){if(i.type!=="step-finish")continue;let c=i.tokens;c&&(s.add(a.info.id),r(c))}let o=new Set;for(let{message:i}of e){if(i.info.role!=="assistant"||s.has(i.info.id)||o.has(i.info.id))continue;o.add(i.info.id);let a=i.info.tokens;a&&r(a)}return n?t:void 0}function Uj(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function Fj(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function Nj(e){if(!e||e.type!=="retry")return;let t=e,n=_e(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:we(t.message)}}function qj(e){if(!(!e||e.type!=="retry"))return _e(e.message)}function Gj(e){return(e.info.summary?.diffs?.length??0)>0}function ZS(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=he(e.part.tool);return t==="show"||t==="show_user"}function Wj(e){return e.kind==="text"&&!e.part.text?.trim()}function Nf(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(ZS(o)||Wj(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):ZS(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function Kj(e){let t=e==null?"":Uf(e);return t?`Worked for ${t}`:"Worked"}function eP(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>De(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return te(s)&&s.tool==="bash"}function Vj(e){if(eP(e))return e.assistantMessages[0].parts[0]}function Hj(e){if(!e)return"";let t=e;return t=t.replace(/^##\s*Worker Result\s*\n/i,""),t=t.replace(/^\*\*Agent:\*\*.*\n?/m,""),t=t.replace(/^\*\*Task:\*\*.*\n?/m,""),t=t.replace(/^\*\*Status:\*\*.*\n?/m,""),t=t.replace(/^\*\*Session:\*\*.*\n?/m,""),t=t.replace(/^\*\*Duration:\*\*.*\n?/m,""),t=lS(t,"beeuni_goal_system"),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created and started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created:.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* failed to start.*$/gm,""),t=t.replace(/^Message sent to task.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* approved.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* cancelled.*$/gm,""),t=t.replace(/Worker session: ses_[a-zA-Z0-9]+/g,""),t=t.replace(/^---\s*\n/gm,""),t=t.trim(),t||""}function zj(e){return e?e.split(`
84
+ `).filter(n=>n.trim()).length<=3:!1}function Yj(e){if(!e)return null;let n=e.split(`
85
+ `).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function Jj(e){if(!e)return[];let t=[],n=e.split(`
86
+ `).filter(r=>r.trim());for(let r of n){let s=gS(r);if(s){let o=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...s,sessionId:o?.[0]})}}return t}var ht={write:{verb:"Wrote",running:"Writing",failed:"Couldn't write"},edit:{verb:"Edited",running:"Editing",failed:"Couldn't update"},delete:{verb:"Deleted",running:"Deleting",failed:"Couldn't delete"},rename:{verb:"Renamed",running:"Renaming",failed:"Couldn't rename"},change:{verb:"Changed",running:"Changing",failed:"Couldn't apply"},read:{verb:"Read",running:"Reading",failed:"Couldn't read"},list:{verb:"Listed",running:"Listing",failed:"Couldn't list"}};function Qj(e,t){let n=ht[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function Xj(e,t){return t?"failed":e?"running":"done"}var Zj={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function eL(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.beeuni\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function tL(e,t){if(!e)return null;let n=e.indexOf(`
87
+ `),r=n===-1?e:e.slice(0,n),s=n===-1?"":e.slice(n+1);if(pS(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
86
88
  `).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
87
89
  `)};if(/files and directories/i.test(r)){let o=t.replace(/\/$/,""),i=[];for(let a of s.split(`
88
- `)){if(!a.trim())continue;let u=a.indexOf(" ");if(u===-1)continue;let p=a.slice(0,u).trim(),d=a.slice(u+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var zE={add:{...Qe.write,icon:"create"},delete:{...Qe.delete,icon:"delete"},move:{...Qe.rename,icon:"edit"},update:{...Qe.edit,icon:"edit"}},$b={...Qe.change,icon:"edit"};function YE(e){if(e.length===0)return $b;let t=Ub(e[0]);for(let n=1;n<e.length;n++)if(Ub(e[n])!==t)return $b;return zE[t]}function Ub(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function QE(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.startsWith("Error:")?{success:!1,action:"unknown",error:e.replace(/^Error:\s*/,"")}:null}}function JE(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],s;for(;(s=n.exec(e))!==null;)r.push(s[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(o,i)=>r[i]?[r[i]]:[])}function XE(e){if(!e)return null;let t=Yn(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=Dg(e,"content");if(r!==null){let o=r.split(`
90
+ `)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var nL={add:{...ht.write,icon:"create"},delete:{...ht.delete,icon:"delete"},move:{...ht.rename,icon:"edit"},update:{...ht.edit,icon:"edit"}},tP={...ht.change,icon:"edit"};function rL(e){if(e.length===0)return tP;let t=nP(e[0]);for(let n=1;n<e.length;n++)if(nP(e[n])!==t)return tP;return nL[t]}function nP(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function sL(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.startsWith("Error:")?{success:!1,action:"unknown",error:e.replace(/^Error:\s*/,"")}:null}}function qf(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],s;for(;(s=n.exec(e))!==null;)r.push(s[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(o,i)=>r[i]?[r[i]]:[])}function oL(e){if(!e)return null;let t=Er(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=pf(e,"content");if(r!==null){let o=r.split(`
89
91
  `).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
90
- `);return{path:n,type:"file",content:o}}let s=Dg(e,"entries");if(s!==null){let o=s.split(`
91
- `).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function ZE(e){let t=Bh(e,"skill_content");return t!==null?t.trim():e}function Fb(e){let t=Yn(e,"<skill_files>","</skill_files>");return t===null?[]:qh(t,"<file>","</file>").map(n=>n.trim())}function eM(e){let t=Lh(e,"skill_content");if(t===null)return"";for(let n of["dir","directory","path","base","baseDir","base_dir"]){let r=t.match(new RegExp(`\\b${n}\\s*=\\s*["']([^"']+)["']`,"i"));if(r?.[1]?.trim())return r[1].trim()}return""}function tM(e){return Wh(e,["Base directory","Directory","Skill directory"])?.trim()??""}function Lb(e){return je(eM(e)||tM(e))}function nM(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return je(n.trim())}return""}var rM="skills";function sM(e){let t=Fh(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(s=>s.trim());if(n.some(s=>s===".."||s==="."))return"";let r=n.at(-1)??"";return r?`${rM}/${r}`:""}function oM(e,t,n){let s=je(t?.trim()??"")||Lb(e)||sM(n),o=Fb(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(o){if(o.startsWith("/"))return o;if(s)return`${s}/${o}`}return s?`${s}/SKILL.md`:null}var iM=4e3;function nr(e,t=iM){return e.length>t?`${e.slice(0,t)}
92
- \u2026`:e}function Bb(e){if(e!==void 0)try{return nr(JSON.stringify(e,null,2))}catch{return}}function K(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function aM(e){let t=K(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=ft(e.outputParsed);if(!n)return{kind:"web-search",query:t};let s=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(o=>{let i=ft(o)??{};return{title:K(i.title)??"",url:K(i.url,i.link)??"",snippet:K(i.snippet,i.description,i.source)}});return{kind:"web-search",query:K(n.query)??t,results:s.length>0?s:void 0,answer:K(n.answer)}}var cM=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function im(e){let t=e.match(cM);return t?Number(t[1]):void 0}function uM(e,t,n){let r="",s=0;for(;;){let o=e.indexOf(t,s);if(o===-1)return r+e.slice(s);let i=e.indexOf(n,o+t.length);if(i===-1)return r+e.slice(s);r+=e.slice(s,o),s=i+n.length}}var lM=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function pM(e){let t=-1;for(let n of lM){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var dM=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function gM(e){return e.replace(dM,"")}function mM(e){let t=K(e.input?.command)??"",n=e.output??"",r=im(n),o=gM(pM(uM(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:o||void 0,exitCode:r}}function am(e){return K(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function fM(e){let t=e.status==="error"?e.error:e.output&&nr(e.output)||void 0;return{kind:"file-read",path:am(e),preview:t}}function yM(e){let t=K(e.input?.content),n=e.status==="error"?e.error:nr(t??e.output??"")||void 0;return{kind:"file-write",path:am(e),preview:n}}var hM=256*1024;function bM(e,t){if(e.length+t.length>hM)return;let n=e.split(`
92
+ `);return{path:n,type:"file",content:o}}let s=pf(e,"entries");if(s!==null){let o=s.split(`
93
+ `).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function iL(e){let t=cS(e,"skill_content");return t!==null?t.trim():e}function rP(e){let t=Er(e,"<skill_files>","</skill_files>");return t===null?[]:uS(t,"<file>","</file>").map(n=>n.trim())}function aL(e){let t=aS(e,"skill_content");if(t===null)return"";for(let n of["dir","directory","path","base","baseDir","base_dir"]){let r=t.match(new RegExp(`\\b${n}\\s*=\\s*["']([^"']+)["']`,"i"));if(r?.[1]?.trim())return r[1].trim()}return""}function cL(e){return dS(e,["Base directory","Directory","Skill directory"])?.trim()??""}function sP(e){return tt(aL(e)||cL(e))}function lL(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return tt(n.trim())}return""}var uL="skills";function pL(e){let t=iS(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(s=>s.trim());if(n.some(s=>s===".."||s==="."))return"";let r=n.at(-1)??"";return r?`${uL}/${r}`:""}function dL(e,t,n){let s=tt(t?.trim()??"")||sP(e)||pL(n),o=rP(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(o){if(o.startsWith("/"))return o;if(s)return`${s}/${o}`}return s?`${s}/SKILL.md`:null}var gL=4e3;function Fr(e,t=gL){return e.length>t?`${e.slice(0,t)}
94
+ \u2026`:e}function oP(e){if(e!==void 0)try{return Fr(JSON.stringify(e,null,2))}catch{return}}function re(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function xn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function mL(e){let t=re(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=xn(e.outputParsed);if(!n)return{kind:"web-search",query:t};let s=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(o=>{let i=xn(o)??{};return{title:re(i.title)??"",url:re(i.url,i.link)??"",snippet:re(i.snippet,i.description,i.source)}});return{kind:"web-search",query:re(n.query)??t,results:s.length>0?s:void 0,answer:re(n.answer)}}var fL=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Wf(e){let t=e.match(fL);return t?Number(t[1]):void 0}function yL(e,t,n){let r="",s=0;for(;;){let o=e.indexOf(t,s);if(o===-1)return r+e.slice(s);let i=e.indexOf(n,o+t.length);if(i===-1)return r+e.slice(s);r+=e.slice(s,o),s=i+n.length}}var hL=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function _L(e){let t=-1;for(let n of hL){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var bL=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function SL(e){return e.replace(bL,"")}function PL(e){let t=re(e.input?.command)??"",n=e.output??"",r=Wf(n),o=SL(_L(yL(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:o||void 0,exitCode:r}}function Kf(e){return re(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function xL(e){let t=e.status==="error"?e.error:e.output&&Fr(e.output)||void 0;return{kind:"file-read",path:Kf(e),preview:t}}function wL(e){let t=re(e.input?.content),n=e.status==="error"?e.error:Fr(t??e.output??"")||void 0;return{kind:"file-write",path:Kf(e),preview:n}}var vL=256*1024;function AL(e,t){if(e.length+t.length>vL)return;let n=e.split(`
93
95
  `),r=t.split(`
94
- `),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let u=0;u<s;u++)a.push({type:"unchanged",text:n[u]});for(let u=s;u<o;u++)a.push({type:"removed",text:n[u]});for(let u=s;u<i;u++)a.push({type:"added",text:r[u]});for(let u=o;u<n.length;u++)a.push({type:"unchanged",text:n[u]});return a}function _M(e){let t=K(e?.oldString),n=K(e?.newString);return t!==void 0&&n!==void 0?[[t,n]]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(s=>{let o=ft(s),i=o&&K(o.oldText),a=o&&K(o.newText);return i!==void 0&&a!==void 0?[[i,a]]:[]})}function PM(e){let t=_M(e.input),n=t.map(([s,o])=>bM(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:am(e),diff:r}}var qb=/^Found\s+(\d+)\s+match/i,SM=/^(\/[^:]+?):\s*/,Nb=/Line\s+(\d+):/g;function xM(e){let t=e.trim(),n=t.match(qb),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let s=[];for(let o of r.split(/\n\n+/)){let i=o.trim();if(!i)continue;let a=i.match(SM);if(!a)continue;let u=a[1],p=i.slice(a[0].length),d=[],g;for(Nb.lastIndex=0;(g=Nb.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,f).trim();s.push({path:u,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return s}function wM(e){return e.trim().split(`
95
- `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function vM(e){let t=K(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=qb.test(e.output.trim())?xM(e.output):wM(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function AM(e){let t=K(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=K(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function om(e){let t=ft(e)??{};return{content:K(t.content)??"",status:K(t.status)??"pending",priority:K(t.priority)}}function kM(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(om)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(om)};let n=ft(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(om)}:{kind:"todo",items:[]}}function RM(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=ft(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let u=ft(a),p=u&&K(u.label);return p?[{label:p,description:u?K(u.description):void 0}]:[]});return{question:K(s.question)??"",header:K(s.header),options:i}})}}function CM(e){let n=e.input&&Object.keys(e.input).length>0?Bb(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?nr(e.outputParsed):Bb(e.outputParsed):e.outputText!==void 0?r=nr(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function Gb(e){switch(te(e.name)){case"web_search":return aM(e);case"bash":return mM(e);case"read":return fM(e);case"write":return yM(e);case"edit":return PM(e);case"grep":case"glob":return vM(e);case"task":return AM(e);case"todowrite":return kM(e);case"question":return RM(e);default:return CM(e)}}var IM=new Set(["AbortError","MessageAbortedError"]),TM=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],EM=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function Wb(e){let t=e.toLowerCase();return EM.some(n=>t.includes(n))?!1:TM.some(n=>t.includes(n))}function MM(e){let t=e.data,n=t&&typeof t=="object"?t.message:void 0;return typeof n=="string"?n:typeof e.message=="string"?e.message:void 0}function rr(e){if(typeof e=="string")return Wb(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&IM.has(n))return!0;let r=MM(t);return typeof r=="string"?Wb(r):!1}var Kb=["user","runtime-disposed","orphan-finalized","wake"],OM=["orphan-finalized","wake"];function DM(e){if(!e||typeof e!="object")return;let t=e.data;if(!t||typeof t!="object")return;let n=t.reason;if(!(typeof n!="string"||!n))return Kb.includes(n)?n:void 0}var sr="beeuni-active-instance",Hb=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function Vb(e){return Hb.some(t=>e===t||e.startsWith(`${t}/`))}function Vt(e){let t=e.match(/^\/instances\/([^/]+)(?:\/(.*))?$/);if(!t)return null;let n=decodeURIComponent(t[1]),r=t[2]??"";return{instanceId:n,innerPath:r?`/${r}`:""}}function jM(e){let t=Vt(e);return!!t&&t.innerPath===""}function $M(e){let t=Vt(e);return!t||!t.innerPath?e:t.innerPath}function zb(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=Vt(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return Vb(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function Yb(e){return e?Vt(e)?.instanceId??null:null}function UM(){return typeof window>"u"?null:Yb(window.location.pathname)||Qb()}function Qb(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${sr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function FM(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${sr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${sr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${sr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function LM(e,t){return t?zb(t,e):e}function BM(e){let t=Vt(e);return t?t.innerPath||"/dashboard":e}function ir(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e??"")}function cm(e){let t=ir(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}var NM=cm;function Ks(e){let t=cm(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var qM=Ks;function Jb(e){return Ks(e)!==null}var GM=Jb,WM=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],KM=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],HM=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function Xb(e){return HM.test(ir(e))}function zt(e){let t=ir(e);return t?Xb(t)||WM.some(n=>n.test(t)):!1}var VM=/server url not ready|sandbox is still loading/i;function zM(e){return VM.test(ir(e))||zt(e)}var or=class extends Error{constructor(t){let n=t?.trim();super(n&&zt(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function Zb(e){let t=Ks(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${a}`,detail:o?`${i?`${i}: `:""}${o}`:void 0}}let n=ir(e);return zt(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var YM=Zb;function um(e){if(!e.external_id){if(e.base_url)return e.base_url;throw new Error(`Cannot build sandbox URL: missing external_id for ${e.provider} sandbox "${e.sandbox_id}"`)}return`${qe()}/p/${e.external_id}/${Te.BEEUNI_MASTER}`}function QM(e,t){return e.external_id?`${qe()}/p/${e.external_id}/${t}`:null}async function JM(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function e_(e){let t=await ct();if(t)return{sandbox:t.sandbox,created:!1};let r=(await st())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await at(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await Le(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Jd(r,s,o),created:!0}}async function XM(){return(await ct().catch(()=>null))?.sandbox??null}async function ZM(e){return{sandbox:(await e_(e)).sandbox}}async function eO(e){let t=In(e);return t?(await ct(t).catch(()=>null))?.sandbox??null:null}async function tO(e,t){throw await ct(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function nO(e){let t=In(e);return(await Xd().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function rO(){return null}async function sO(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await ct(e);if(!t)throw new Error("Project session sandbox not found");await Pn(t.project.project_id,t.session.session_id)}async function oO(e){if(!e)throw new Error("No sandbox selected to stop");let t=await ct(e);if(!t)throw new Error("Project session sandbox not found");await Sn(t.project.project_id,t.session.session_id)}async function iO(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function aO(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function lm(e,t,n){let r=um(e),s=await E(`${ee(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function cO(e,t){return lm(e,`/beeuni/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function uO(e,t,n,r="member"){await lm(e,`/beeuni/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function lO(e,t,n){await lm(e,`/beeuni/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var pm="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function pO(e){throw F("getInvite",pm)}async function dO(e){throw F("acceptInvite",pm)}async function gO(e){throw F("declineInvite",pm)}async function mO(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function fO(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function yO(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function hO(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function bO(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function _O(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var t_=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function PO(e){return t_.includes(e)}async function SO(e){return{phase:"idle",progress:0,message:"Sandbox image updates are managed by project-session provisioning.",targetVersion:null,previousVersion:null,currentVersion:e?.version??null,error:null,startedAt:null,updatedAt:null}}async function xO(e){let t=e?`?channel=${e}`:"",r=await(await ke(`${qe()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await n_(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function n_(e){let t=e?`?channel=${e}`:"";return(await(await ke(`${qe()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function wO(){return(await ke(`${qe()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function vO(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function AO(e){}async function kO(e){}async function RO(e){return{serverTypes:[],location:e||"hel1"}}async function CO(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function IO(e){throw F("deleteInstance")}async function TO(e,t){}async function EO(){throw F("claimComputer")}async function MO(e){return null}function OO(e,t){throw F("getSandboxProvisionStreamUrl")}var ar=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function r_(e,t){let n=new Headers(e.headers);return n.set("Accept","application/json"),t&&n.set("Content-Type","application/json"),e.accessToken&&n.set("Authorization",`Bearer ${e.accessToken}`),n}async function s_(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function o_(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function z(e,t,n){let r=n?.body!==void 0,s=await fetch(`${Tn(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:r_(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await s_(s);if(!s.ok)throw new ar(o_(s,o),s.status,o);return o}function DO(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString();return n?`?${n}`:""}function jO(e,t){return z(`/marketplace/items${DO(t)}`,e)}function $O(e){return z("/marketplace/marketplaces",e)}function UO(e,t){return z(`/marketplace/items/${encodeURIComponent(e)}`,t)}function FO(e,t,n){return z(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function LO(e,t){return z("/access/check-email",t,{method:"POST",body:{email:e}})}function BO(e,t){return z("/access/request-access",t,{method:"POST",body:e})}function NO(e){return z("/auth/logout",e,{method:"POST",body:{}})}function qO(e,t){return z(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function GO(e,t){return z("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function WO(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function KO(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function HO(e,t,n={}){return z(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function VO(e,t){return z(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function zO(e,t,n,r){return z(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function YO(e,t){return z(`/p/public-share/${encodeURIComponent(e)}`,t)}function QO(e,t,n){return z(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function JO(e){return z("/system/maintenance",e)}function XO(e,t){return z("/system/maintenance",t,{method:"PUT",body:e})}function ZO(e){return z("/user-roles",e)}function eD(e,t){return z("/system/demo-request",t,{method:"POST",body:e})}async function tD(e,t,n){let r=await fetch(`${Tn(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${kt(t)}`,{headers:r_(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await s_(r);throw new ar(o_(r,s),r.status,s)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function nD(e,t){throw F("openStressTestStream")}function rD(e,t){throw F("buildPublicTemplateUrl")}async function sD(e,t,n){throw F("getPublicTemplate")}var oD="beeuni:connect-link:";function dm(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);t=Math.imul(t^s,16777619)>>>0,n=Math.imul(n^s,1540483477)>>>0}return`${oD}${t.toString(36)}${n.toString(36)}`}function iD(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(dm(i));if(!a)return;let u=JSON.parse(a);if(Date.parse(u.expires_at)<=Date.now()){t.removeItem(dm(i));return}return u}catch{return}},o=(i,a)=>{if(t)try{t.setItem(dm(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let u=s(i);return u&&r.set(i,u),u},load(i){let a=n.get(i);if(a)return a;let u=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,u),u}}}var i_="Could not start the connect flow.";async function aD(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:i_}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:i_};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var a_=3e3,c_=5e3,u_=5*6e4;function cD(e,t){let n=e===0?a_:c_;return t+n>u_?null:n}function uD(e){let t=e.project_name?.trim();return{app:e.name?.trim()||e.app?.trim()||e.slug,project:t&&t!=="this project"?t:null}}async function lD(){let e=await c.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function pD(e={}){let t=await c.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function dD(e){let t=await c.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function gD(e){let t=await c.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function mD(){let e=await c.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var vW="1";var fD="beeuni.query-cache";function p_(e){return!!e&&typeof e.then=="function"}function l_(e){return p_(e)?e:Promise.resolve()}function yD(e){if(e[0]!=="kx")return!1;let t=e[1];if(t==="accounts")return e.length===3&&typeof e[2]=="string"&&e[2]!=="anonymous";if(t==="projects")return e.length===3;if(t!=="project"||typeof e[2]!="string")return!1;let n=e[3];if(e.length===4)return n==="summary"||n==="detail";if(n!=="sessions")return!1;if(e.length===6)return e[4]==="list-paged";if(e.length===7&&e[4]==="list-paged"){let r=e[6];return typeof r=="object"&&r!==null&&!r.q}return e.length===7&&e[4]==="list-children"?e[6]==="":e.length===5&&e[4]!=="list"&&e[4]!=="list-paged"}function hD(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:u=fD,now:p=()=>Date.now()}=e,d=`${u}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),x=()=>{try{return l_(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},D=(w,P)=>{if(!P)return 0;let A;try{A=JSON.parse(P)}catch{return x(),0}if(!A||A.v!==s||A.user!==n||!Array.isArray(A.queries)||p()-A.at>o)return x(),0;let I=0;for(let T of A.queries){if(!T||!Array.isArray(T.k)||T.d===void 0||typeof T.t!="number"||p()-T.t>o||!r(T.k))continue;let B=w.getQueryState(T.k);B&&B.data!==void 0&&B.dataUpdatedAt>=T.t||(w.setQueryData(T.k,T.d,{updatedAt:T.t}),w.invalidateQueries?.({queryKey:T.k,exact:!0,refetchType:"none"}),I+=1)}return I},j=w=>w.getQueryCache().getAll().filter(P=>P.state.data!==void 0&&r(P.queryKey)).map(P=>({k:P.queryKey,d:P.state.data,t:P.state.dataUpdatedAt})).sort((P,A)=>A.t-P.t),L=(w,P)=>{let A=[],I=0;for(let T of w){let B=JSON.stringify(T).length+1;I+B>P||(A.push(T),I+=B)}return A},y=async w=>{let P=L(j(w),i);for(;;){let A={v:s,user:n,at:p(),queries:P};try{await l_(t.setItem(d,JSON.stringify(A)));return}catch{if(P.length===0)return;P=P.slice(0,Math.floor(P.length/2))}}},_=()=>{f!==null&&(clearTimeout(f),f=null)},S=()=>{_();let w=g;return!w||!m||(m=!1,h=h.then(()=>y(w)).catch(()=>{})),h},M=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,S()},a))};return{storageKey:d,restore(w){let P;try{P=t.getItem(d)}catch{return 0}return p_(P)?P.then(A=>D(w,A)).catch(()=>0):D(w,P)},persist(w){g=w,m=!0;let P=w.getQueryCache().subscribe(A=>{A.type!=="updated"&&A.type!=="removed"&&A.type!=="added"||r(A.query.queryKey)&&M()});return()=>{P(),g===w&&(g=null,_())}},flush(){return S()},async clear(){_(),g=null,m=!1,await h,await x()}}}function bD(){let e;try{e=globalThis.localStorage}catch{e=void 0}if(!e)return null;let t=e;return{getItem:n=>{try{return t.getItem(n)}catch{return null}},setItem:(n,r)=>t.setItem(n,r),removeItem:n=>{try{t.removeItem(n)}catch{}}}}var d_="/beeuni/part/";function g_(e){return typeof e=="string"&&e.startsWith(d_)}async function _D(e){if(!g_(e))throw new Error(`not an attachment part reference: ${e}`);let t=Me();if(!t)throw new Error("runtime url not bound");let n=await E(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function m_(e){try{let t=new URL(e);if(/^\/proxy\/\d+(?:\/|$)/.test(t.pathname))return`${t.origin}/v1/p/auth`;let n=t.pathname.indexOf("/p/");return n!==-1?`${t.origin}${t.pathname.slice(0,n)}/p/auth`:`${t.origin}/v1/p/auth`}catch{return null}}function PD(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.has(n.origin)}catch{return!1}}function gm(e,t){return PD(e,t)?(t?m_(t):null)??m_(e):null}function cr(e){try{let{hostname:t}=new URL(e);return/^p\d+-[^.]+\./.test(t)||/^(?:dev|staging|prod|preview)-p\d+-[a-z0-9-]+\./i.test(t)}catch{return!1}}function mm(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var SD=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function xD(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wD(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let s=(t.slice(n+3).split("/")[0]??"").toLowerCase(),o=`${r}://${s}`.split("{port}").map(i=>i.split("{sandbox}").map(xD).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function vD(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function f_(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function AD(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:SD.test(n.hostname)?t.backendUrls.some(r=>{let s=vD(r);return s!==null&&f_(s)===f_(n)}):t.templates.some(r=>wD(n.origin,r))}async function y_(e,t={}){if(!cr(e))return!1;let n=k().backendUrl;n&&await Ge(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return AD(e,{templates:Gf(),backendUrls:r})}async function h_(e,t={}){let n=gm(e,t.serverUrl||k().backendUrl||void 0);if(!n)return!1;let r=await xt();if(!r)return!1;try{return(await fetch(n,{method:"POST",credentials:"include",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).ok}catch{return!1}}async function kD(e,t={}){if(cr(e)){if(!await y_(e,t))return e;let n=await xt();return n?mm(e,n):e}return await h_(e,t),e}var RD=3e3;function b_(e){return!Number.isFinite(e)||e<100||e>599?"unknown":e===502||e===503||e===504?"unreachable":e===401||e===403?"unknown":"reachable"}async function CD(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return b_(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function ID(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function TD(e,t){throw F("buildPresentationTemplatePdfUrl")}function ED(e,t){throw F("buildPresentationTemplateImageUrl")}function __(e,t){return`${ID(e)}/presentation/convert-to-${t}`}async function MD(e,t,n,r){let s=__(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),u=!1;for(;;){let p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(u||(u=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,x)=>{let D=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(D),x(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let h=JSON.parse(m);f=String(h.error||h.detail||h.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function OD(e){return e.activityFresh||e.runtimeReady?"live":e.unreachable||e.stalled?"unreachable":e.sandbox==="stopped"||e.sandbox==="archived"||e.sandbox==="provisioning"||e.sandbox==="queued"||e.sandbox==="branching"?"waking":e.sandbox==="completed"?"unknown":e.sandbox==="failed"?"unreachable":e.sandbox==="running"?"connecting":"unknown"}function DD(e){return e==="unreachable"}function jD(e){return!e||e.status===0?"unknown":e.ok&&xg(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var P_=1e4,$D={connection:"unknown",faultSinceMs:null};function UD(e,t,n,r=P_){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let s=e.faultSinceMs??n;return n-s>=r?{connection:t,faultSinceMs:s}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:s}}function S_({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<Hs,u=!!t&&i-t.atMs<Ys;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:u,abortFloor:u?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=Vs,streamFresh:!!s&&i-s.atMs<=Yt,inboxFresh:!!n&&i-n.atMs<=zs,activityFresh:!!o&&i-o.atMs<=Yt}}function Qt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function fm(e,t,n){if(!t)return!1;let r=Qt(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=Qt(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function FD(e,t,n,r){let{activity:s,server:o}=e,{serverFresh:i,abortFloor:a,activityFresh:u}=t;return u&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!fm(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function LD(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,u=i?s.turns.filter(g=>!fm(g,n,s)):[],p=u.find(g=>g.state==="active")??u[0],d=!!o&&!(o.type==="idle"&&o.origin==="local");return p&&s.atMs>=a&&(!d||s.atMs>=o.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:Qt(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function BD(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:u,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...u&&o.type!=="idle"&&(!p||o.atMs>s.atMs)&&o.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&s.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function ND(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:u,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,x=u&&!n&&s.atMs>=p,D=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(x&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:Qt(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(D)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let j=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:a};return{state:"idle",source:j.source,turnId:null,since:j.atMs,serverOpenTurnToken:r}}function x_(e){let t=S_(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=FD(e,t,s,o);if(i)return i;let{result:a,openTurn:u}=LD(e,t,s,o);return a??BD(e,t,o)??ND(e,t,u,o)}var Hs=6e4,Vs=45e3,Yt=45e3,zs=1e4,qD=3e3,Ys=15e3;function GD(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function WD(e){let t=0;for(let n of e)(n.state==="queued"||n.state==="delivering"||n.state==="waiting"&&n.reason!=="held")&&(t+=1);return t}function KD(e){return x_(e)}function HD(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,u=[null,t?t.atMs+Hs:null,n?n.atMs+Ys:null,r?r.atMs+zs:null,s?s.atMs+Vs:null,o?o.atMs+Yt:null,i?i.atMs+Yt:null],p=null;for(let d of u)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function w_(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(o=>o.message_id===t),r=e.last_ended,s=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!s?.message||rr({name:s.name??void 0,message:s.message})?null:s}var VD="SandboxMemoryGuard";function zD(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=w_(e,t);if(r?.message){if(r.name!==VD)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],u=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:u}}let s=e.recent_failures?.find(a=>a.message_id===t);if(!s)return null;let o=s.ended_at?Date.parse(s.ended_at):Number.NaN;return Number.isFinite(o)&&typeof e.atMs=="number"&&e.atMs-o<2500?null:{kind:"unexplained"}}var YD=6e4;function QD(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function JD(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var v_=9e4;function XD(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+v_}var ZD=75e3,ej=2,tj=2e4;function ym(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function nj(e){return e.filter(t=>t!=null).join("|")}function rj(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function sj(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...ym(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...ym(),settled:!0};let i=e.lastProgressAtMs,a=i===null,u=t.progress!==e.fingerprint,p=i===null||u?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!u&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return g;let f=rj(e.attempts,s);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var oj={"retry-start":"retrying",restart:"restarting"};function ij(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${oj[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function aj(e){return e===1?"once":e===2?"twice":`${e} times`}function cj(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(s=>s.step==="restart").length,n=e.attempts.some(s=>s.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${aj(t)}`),`Tried: ${r.join(", then ")}.`}var uj={"needs-you":{label:"Needs you",tone:"actionable",description:"Waiting for your review"},starting:{label:"Starting",tone:"progress",description:"Its computer is starting"},running:{label:"Running",tone:"live",description:"Its computer is up"},done:{label:"Done",tone:"muted",description:"Finished"},stopped:{label:"Stopped",tone:"muted",description:"Asleep. Opening it wakes its computer"},failed:{label:"Failed",tone:"danger",description:"Its computer didn't start"},legacy:{label:"Legacy",tone:"muted",description:"Imported. Open it to restore"}};function A_(e){return!!(e.metadata??{}).legacy_migration}function lj(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return"running";case"completed":case"stopped":return A_(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function pj(e){switch(e){case"waking":return{label:"Waking computer",tone:"progress"};case"connecting":return{label:"Connecting",tone:"progress"};case"unreachable":return{label:"Can't reach computer",tone:"danger"};default:return null}}var dj={unreachable:"Lost contact with this session's computer. Messages you send are queued until it reconnects.",unreachableMidTurn:"Lost contact with this session's computer while a turn is still open. Messages you send stay queued until it answers.",stalled:"Waking this session's computer is taking longer than usual. Messages you send are queued.",starting:"Starting this session's computer. Your message sends automatically.",idle:"This session's computer is asleep. Your next message wakes it up and is delivered.",waking:"Waking this session's computer. Messages you send are queued and go out automatically."};function gj(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function Qs(e){return e.runtime_sessions??e.opencode_sessions??[]}function k_(e){let t=Qs(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function mj(e){let t=k_(e);return t?Qs(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function fj(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>Qs(r).some(s=>s.id===t))??null)}var yj=new Set;function R_(e){for(let t of[...yj])try{t(e)}catch{}}var hj=12e4,Js=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},bj=1e3,_j=15e3,C_=100,Pj=50,Sj=10;function I_(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let i=new URLSearchParams({limit:String(r)});s&&i.set("before",s);let a=await e.getToken?.(),u=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!u.ok)throw u.status===503?new or(`session ${u.status}`):new b(`Session synchronization failed: ${u.status}`,{status:u.status});return{messages:await u.json(),nextCursor:u.headers.get("x-next-cursor")||void 0}}}function T_(e){return xj(I_(e))}function E_(e){return new hm({...e,loadPage:I_(e)})}async function xj(e){let t=[],n=new Set,r;do{let i=await e({limit:C_,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])o.has(a.info.id)||(o.add(a.info.id),s.push(a));return s}var wj={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},hm=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??wj,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??hj,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof Js;if(!r&&rr(n))return;if(r||this.update({freshness:zt(n)?"loading":"error"}),n instanceof b&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(bj*2**this.retryAttempt,_j);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?Pj:C_,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,s=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",s,{once:!0});let o,i=new Promise((u,p)=>{o=this.startTimer(()=>{let d=new Js(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(u){a=Promise.reject(u)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(o),n.removeEventListener("abort",s)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let i=[...t.messages],a=new Set(this.knownUserMessageIds),u=new Set(s?[s]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<Sj&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(u.has(p))throw new Error(`Session history cursor repeated: ${p}`);u.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw o?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,o?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,i=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};function M_(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function O_(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function vj(e){throw F("buildTunnelEventStreamUrl")}function Aj(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:u,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(y,_){o?.(y,_);let S=d.get(y);if(S)for(let M of S)try{M(_)}catch{}}async function x(){if(m)return;let y=new AbortController;g=y,p&&(p.aborted?y.abort():p.addEventListener("abort",()=>y.abort(),{once:!0}));let _=y.signal;try{let S={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(S["Content-Type"]="application/json"),f&&(S["Last-Event-ID"]=f);let M=await fetch(t,{method:r,headers:S,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:_,credentials:"include"});if(!M.ok)throw new Error(`SSE connection failed: ${M.status} ${M.statusText}`);if(!M.body)throw new Error("SSE response has no body");i?.();let w=M.body.getReader(),P=new TextDecoder,A="",I="message",T=[],B=N=>{if(N===""){T.length>0&&h(I,T.join(`
96
- `)),I="message",T=[];return}if(N.startsWith(":"))return;let q=N.indexOf(":"),de=q===-1?N:N.slice(0,q),ue=q===-1?"":N.slice(q+1);ue.startsWith(" ")&&(ue=ue.slice(1)),de==="event"?I=ue.trim()||"message":de==="data"?T.push(ue):de==="id"&&!ue.includes("\0")&&(f=ue)},$=N=>{let q="";!N&&A.endsWith("\r")&&(q="\r",A=A.slice(0,-1));let de=A.split(/\r\n|\n|\r/);A=(de.pop()??"")+q;for(let ue of de)B(ue)};for(;!m;){let{done:N,value:q}=await w.read();if(N)break;A+=P.decode(q,{stream:!0}),$(!1)}m||(A+=P.decode(),$(!0),u?.())}catch(S){if(m||S instanceof DOMException&&S.name==="AbortError")return;a?.(S instanceof Error?S:new Error(String(S)))}}function D(){m=!0,g?.abort(),g=null,d.clear()}function j(y,_){let S=d.get(y)??new Set;S.add(_),d.set(y,S)}function L(y,_){d.get(y)?.delete(_)}return{connect:x,close:D,addEventListener:j,removeEventListener:L}}function kj(e,t){throw F("createTunnelEventStream")}var D_="/_beeuni/viewer",Xs=6e4,Jt=new Map;function j_(){Jt.clear(),ur.clear()}async function Rj(e,t){let n;try{n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}})}catch{return null}if(n.status===401||n.status===404||!n.ok)return null;let r=await n.json().catch(()=>null);return r&&typeof r.user_id=="string"?r:null}async function bm(e={}){let t=e.path??D_,n=e.fetch??((o,i)=>fetch(o,i)),r=Jt.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=Rj(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-Xs:Date.now()+Xs;return Jt.set(t,{session:o,expiresAt:a}),o});return Jt.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function $_(e={}){let t=e.path??D_;return Object.assign(async()=>(await bm(e))?.access_token??null,{invalidate:n=>{let r=Jt.get(t);r&&!r.inflight&&r.session?.access_token===n&&Jt.delete(t)}})}var ur=new Map;async function Cj(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let o=await n.json().catch(()=>null);o?.error==="app_not_linked"&&console.warn(`[beeuni] ${String(o.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let s=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return ur.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-Xs:Date.now()+Xs}),r.token}catch{return null}}function _m(e={}){let t=e.path??"/_beeuni/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((s,o)=>fetch(s,o));return async(s={})=>{let o=ur.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=Cj(n,r).then(a=>(a===null&&ur.delete(n),a));return ur.set(n,i),i}}function U_(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("beeuniBinding needs the App origin: pass { origin } outside a browser.");return{url:`${ee(n)}/_beeuni/apps/${encodeURIComponent(e)}`,token:_m({audience:e,fetch:t.fetch})}}var Je=class extends Error{code;constructor(t,n){super(n),this.name="BeeuniMemberError",this.code=t}},ce=e=>typeof e=="string"&&e.length>0?e:null;function F_(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Zs(e){if(!e||typeof e!="object")return null;let t=e,n=ce(t.sub)??ce(t.subject)??ce(t.user_id)??ce(t.userId);return n?{userId:n,email:ce(t.email),name:ce(t.name),picture:ce(t.picture)??ce(t.pictureUrl),groups:F_(t.groups),groupIds:F_(t.group_ids??t.groupIds),role:ce(t.role),accountId:ce(t.account_id)??ce(t.accountId),projectId:ce(t.project_id)??ce(t.projectId)}:null}function B_(e,t={}){let n=Zs(e);if(!n)throw new Je("unauthenticated","Sign in with Beeuni to continue.");let{groups:r,roles:s}=t;if(r&&!r.some(o=>n.groups.includes(o)||n.groupIds.includes(o)))throw new Je("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new Je("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var Ij=60,Pm=new Map;function N_(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function L_(e){return JSON.parse(new TextDecoder().decode(N_(e)))}async function Tj(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),s=e.slice(n+1),o=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(s),i=>i.charCodeAt(0))):decodeURIComponent(s);return JSON.parse(o)}if(/^https?:\/\//.test(e)){let n=Pm.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>Pm.delete(e)),Pm.set(e,n)),n}return JSON.parse(e)}async function q_(e,t={}){let n=y=>{throw new Je("unauthenticated",`Beeuni sign-in token refused: ${y}.`)},r=t.jwks??Ne("BEEUNI_AUTH_JWKS"),s=t.issuer??Ne("BEEUNI_AUTH_ISSUER"),o=t.audience??Ne("BEEUNI_AUTH_AUDIENCE");if(!r)return n("no key set configured (BEEUNI_AUTH_JWKS)");if(o!==!1&&!o)return n("no audience configured (BEEUNI_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,u,p]=i,d,g;try{d=L_(a),g=L_(u)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await Tj(r,t.fetch??((y,_)=>fetch(y,_)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(y=>y.kty==="EC"&&(d.kid===void 0||y.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${u}`),x;try{x=N_(p)}catch{return n("malformed")}let D=!1;for(let y of f)try{let{kid:_,alg:S,use:M,key_ops:w,...P}=y,A=await crypto.subtle.importKey("jwk",P,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},A,x,h)){D=!0;break}}catch{}if(!D)return n("bad signature");let j=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+Ij<j)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let y=g.aud;if(!(y===o||Array.isArray(y)&&y.includes(o)))return n("wrong audience")}let L=Zs(g);return L||n("no subject")}function Sm(e){let t=e.agents.map(Ej),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function Ej(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function xm(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>rs(n?{...r,mode:null}:r))}function G_(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let o=e.selectedAgent?.trim();return o?{selected:o,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=xm(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(o=>o.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let s=e.defaultAgent?.trim();return s&&n.some(o=>o.name===s)?{selected:s,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var W_=Sm;function K_(e){return e.providerID==="beeuni"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function wm(e){return{providerID:"beeuni",modelID:e}}function H_(e,t){let n=e.startsWith("beeuni/")?e.slice(7):e;if(!t){let r=n.indexOf("/");if(r>0&&r<n.length-1)return{providerID:n.slice(0,r),modelID:n.slice(r+1)}}return wm(n)}var vm=[{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"v0",env:["V0_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"kimi-for-coding",env:["KIMI_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]}];function Am(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function Oj(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"beeuni":e.id.slice(0,t)}function V_(e,t){let n=new Map;for(let r of e){let s=t(r),o=n.get(s);o?o.push(r):n.set(s,[r])}return n}function oe(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function z_(e){return e.reduce((t,n)=>{let r=Am(n)??0,s=Am(t)??0;return r!==s?r>s?n:t:oe(n.id)>oe(t.id)?n:t})}function km(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of V_(e,Oj)){let a=[...V_(o,p=>p.family||p.id).values()].map(z_),u=a.filter(p=>{let d=Am(p);return d!==null&&Math.abs(n-d)<r});for(let p of u.length>0?u:[z_(a)])s.add(p.id)}return s}function eo(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>oe(r.id)>0)?n.filter(r=>oe(r.id)>0):n}function lr(e){let t;for(let n of eo(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&oe(n.id)>oe(t.id))&&(t=n)}return t}var Dj={"amazon-bedrock":{methods:[{label:"Bearer token",envVars:["AWS_BEARER_TOKEN_BEDROCK","AWS_REGION"]}]},google:{methods:[{envVars:["GOOGLE_GENERATIVE_AI_API_KEY"]},{envVars:["GOOGLE_API_KEY"]},{envVars:["GEMINI_API_KEY"]}]}};function Y_(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var jj=(()=>{let e=new Map;for(let{id:n,env:r}of vm)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let s=[...r].sort((o,i)=>o.length-i.length||o.localeCompare(i));t.set(n,r.find(o=>Y_(o)===n)??s[0])}return t})();function Q_(e){let t=Dj[e.id];if(t)return t;let n=e.env??[],r=n.length===1?jj.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[Y_(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function Rm(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var $j=["low","medium","high"];function J_(e){if(!e)return{temperature:!1,topP:!1};let t=e.reasoning_options?.find(a=>a.type==="effort"),n=e.reasoning_options?.find(a=>a.type==="budget_tokens"),r=t?.values?.length?{values:t.values}:n?{values:[...$j]}:void 0,s=e.temperature===!0,o=e.limit?.output,i=typeof o=="number"&&o>0?{ceiling:o}:void 0;return{reasoningEffort:r,temperature:s,topP:s,maxOutputTokens:i}}var X_=vm;var Uj=[{id:"gpt-6-astra",name:"GPT-6 Astra",upstreamModelId:"openai/gpt-6-astra",transport:"openrouter",pricingRef:"openrouter/openai/gpt-6-astra",pricing:{inputPerMillion:10,cachedInputPerMillion:1,cacheWritePerMillion:12.5,outputPerMillion:50,contextOver200k:{contextThreshold:272e3,inputPerMillion:20,cachedInputPerMillion:2,cacheWritePerMillion:25,outputPerMillion:75}},tier:"flagship",vision:!0,limit:{context:105e4,output:128e3},openrouterProvider:{order:["openai"],allow_fallbacks:!0}},{id:"gpt-6-sol",name:"GPT-6 Sol",upstreamModelId:"openai/gpt-6-sol",transport:"openrouter",pricingRef:"openrouter/openai/gpt-6-sol",pricing:{inputPerMillion:2.2,cachedInputPerMillion:.22,cacheWritePerMillion:2.75,outputPerMillion:11,contextOver200k:{contextThreshold:272e3,inputPerMillion:4.4,cachedInputPerMillion:.44,cacheWritePerMillion:5.5,outputPerMillion:16.5}},tier:"balanced",vision:!0,limit:{context:105e4,output:128e3},openrouterProvider:{only:["azure/us"],allow_fallbacks:!1,zdr:!0,data_collection:"deny"}}],qK=new Map(Uj.map(e=>[e.id,e]));var Z_=["gpt-6-astra","gpt-6-sol"],eP="gpt-6-astra",tP="gpt-6-sol";var rP=X_.map(e=>({id:e.id,authRequirement:Q_(e)})),pr=new Set(["beeuni"]),Cm=new Set(["beeuni"]);function Xt(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,s=Array.isArray(r)?r:[];return s.length===0?{...e,all:[],connected:[]}:{...e,all:s,connected:s.map(o=>o.id)}}function Fj(e){if(!e)return!1;let t=Xt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(s=>r.includes(s.id)&&s.models&&Object.keys(s.models).length>0)}function Lj(e){let t=Xt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(s=>!Cm.has(s.id)),connected:r.filter(s=>!Cm.has(s))}}function Bj(e,t,n){let r=Xt(e),s=Array.isArray(r.all)?r.all:[],o=new Set(s.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)o.has(a.id)&&Rm(a.authRequirement,u=>t.has(u))&&i.add(a.id);return o.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var Nj=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function qj(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var Im="opencode";function Gj(e){return e.cost?.input===0&&e.cost?.output===0}function nP(e){return e===Im?Number.MAX_SAFE_INTEGER:Nj.get(e)??Number.MAX_SAFE_INTEGER-1}function Wj(e,t){let n=Hj(t),r={},s=(e.providers??[]).map(o=>{let i=(o.models??[]).filter(a=>a.status!=="deprecated");return o.id===Im&&!n.has(Im)?{...o,models:i.filter(Gj),keyless:!0}:{...o,models:i,keyless:!1}}).filter(o=>(o.keyless||n.has(o.id))&&!Cm.has(o.id)&&(o.models?.length??0)>0).sort((o,i)=>nP(o.id)-nP(i.id)).map(o=>{let i=[...o.models].sort((u,p)=>(p.released??"").localeCompare(u.released??"")||oe(p.id)-oe(u.id)),a=lr(i)?.id??i[0]?.id;return a&&(r[o.id]=a),{id:o.id,name:o.name,source:o.keyless?"api":"env",models:Object.fromEntries(i.map(u=>{let p=qj(u);return[u.id,{id:u.id,name:u.name,...u.released?{release_date:u.released}:{},...u.family?{family:u.family}:{},...u.reasoning!==void 0?{reasoning:u.reasoning}:{},...u.reasoning_options?{reasoning_options:u.reasoning_options}:{},...u.tool_call!==void 0?{tool_call:u.tool_call}:{},...u.attachment!==void 0?{attachment:u.attachment}:{},...u.modalities?{modalities:u.modalities}:{},...u.limit?{limit:u.limit}:{},...u.cost?{cost:u.cost}:{},...u.description?{description:u.description}:{},...u.open_weights!==void 0?{open_weights:u.open_weights}:{},...u.last_updated?{last_updated:u.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:s,connected:s.map(o=>o.id),default:r}}function Kj(e,t){if(!e)return t;if(!t)return e;let n=Xt(e),r=Xt(t),s=new Map;for(let d of Array.isArray(r.all)?r.all:[])s.set(d.id,d);let o=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])o.push(s.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(o.push(d),i.add(d.id));let a=[],u=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])u.has(d)||(a.push(d),u.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=s.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:o,connected:a,default:p}}function Hj(e){let t=new Set;for(let n of rP)Rm(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function Vj(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="beeuni/auto").map(([r,s])=>{if(s.variants&&Object.keys(s.variants).length>0)return[r,s];let o=J_({id:r,name:s.name,reasoning:s.reasoning,reasoning_options:s.reasoning_options}).reasoningEffort?.values;return o?.length?[r,{...s,variants:Object.fromEntries(o.map(i=>[i,{}]))}]:[r,s]})),n=Object.keys(t)[0];return{default:n?{beeuni:n}:{},connected:["beeuni"],all:[{id:"beeuni",name:"Beeuni",source:"gateway",models:t}]}}function zj(e,t){return Lj(Bj(Xt(e),t,rP))}function sP(e){if(e.gatewayEnabled)return e.modelPicker?Vj(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?zj(e.runtimeProviders,t):void 0;return Kj(e.llmCatalogProviders?Wj(e.llmCatalogProviders,t):void 0,Fj(n)?n:void 0)}function Yj(e){return"capabilities"in e&&e.capabilities!=null}function to(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function oP(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],s=Array.isArray(e.connected)?e.connected:[],o=[];for(let i of r)if(s.includes(i.id)&&!(n==="gateway"?!pr.has(i.id):pr.has(i.id)))for(let[a,u]of Object.entries(i.models)){if(a==="auto"||a==="beeuni/auto")continue;let p;if(Yj(u)){let d=u.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=u.modalities?.input;p={reasoning:u.reasoning??!1,vision:d?d.includes("image"):u.attachment,toolcall:u.tool_call??!1}}o.push({id:K_({providerID:i.id,modelID:a}),providerID:i.id,providerName:u.provider_name??i.name,modelID:a,modelName:(u.name||a).replace("(latest)","").trim(),variants:u.variants,capabilities:p,contextWindow:u.limit?.context,releaseDate:u.release_date,family:u.family,cost:u.cost?{input:u.cost.input??0,output:u.cost.output??0}:void 0,providerSource:i.source,provider:u.provider,reasoningOptions:u.reasoning_options,description:u.description,openWeights:u.open_weights,lastUpdated:u.last_updated,enabled:u.enabled,free:u.free===!0})}return o}function iP(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var Qj=new Set([eP]),Jj="beeuni",aP="codex",Xj=new Set(Z_);function Zj(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Zt(e){return Qj.has(e.modelID)}function e$(e){return km(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function cP(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=e$(e.catalogModels),s=iP(e.catalogModels),o=new Map;for(let i of e.pins??[])o.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,u=o.get(a);if(u==="hide")return!1;if(i.providerID===Jj){let d=Zj(i.modelID,i.provider),g=d===aP?t?.has(aP)??!1:t?.has(d)??!1;if(Xj.has(i.modelID))return!n||i.modelID===tP;if(!g)return!1;if(u==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return Zt(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Zt(i)}catch{return Zt(i)}return!1}if(u==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return Zt(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Zt(i)}catch{return Zt(i)}return!1}}function uP(e,t){return t.search.trim().length>0||e.providerID==="beeuni"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function lP(e,t){if(!e||pr.has(e.providerID)||oe(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>oe(i.modelID)>0))return e;let r=i=>oe(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,o=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??lr(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!o||o===e.modelID?e:{...e,modelID:o}}function pP(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?wm(n):void 0}function dP(e){let{models:t,providers:n}=e,r=u=>to(t,u),s=u=>u.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let u=e.configModel.split("/");if(u.length>=2){let[p,...d]=u,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let u of e.recent??[])if(r(u))return u;if(n){let u=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=u[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of eo(Object.keys(m.models).map(x=>({id:x})))){let x={providerID:m.id,modelID:h.id};if(r(x))return x}}}})(),i=s(e.picks??[]),a=i??s([e.serverDefault,e.globalDefault,e.agentModel,o]);return{model:lP(a,t),explicit:i,fallback:o}}return _P(t$);})();
96
+ `),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let c=0;c<s;c++)a.push({type:"unchanged",text:n[c]});for(let c=s;c<o;c++)a.push({type:"removed",text:n[c]});for(let c=s;c<i;c++)a.push({type:"added",text:r[c]});for(let c=o;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function kL(e){let t=Io(e.input),n=t.map(([s,o])=>AL(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:Kf(e),diff:r}}var aP=/^Found\s+(\d+)\s+match/i,RL=/^(\/[^:]+?):\s*/,iP=/Line\s+(\d+):/g;function CL(e){let t=e.trim(),n=t.match(aP),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let s=[];for(let o of r.split(/\n\n+/)){let i=o.trim();if(!i)continue;let a=i.match(RL);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(iP.lastIndex=0;(g=iP.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,f).trim();s.push({path:c,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return s}function TL(e){return e.trim().split(`
97
+ `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function EL(e){let t=re(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=aP.test(e.output.trim())?CL(e.output):TL(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function IL(e){let t=re(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=re(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function Gf(e){let t=xn(e)??{};return{content:re(t.content)??"",status:re(t.status)??"pending",priority:re(t.priority)}}function ML(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(Gf)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(Gf)};let n=xn(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(Gf)}:{kind:"todo",items:[]}}function OL(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=xn(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let c=xn(a),p=c&&re(c.label);return p?[{label:p,description:c?re(c.description):void 0}]:[]});return{question:re(s.question)??"",header:re(s.header),options:i}})}}function DL(e){let n=e.input&&Object.keys(e.input).length>0?oP(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Fr(e.outputParsed):oP(e.outputParsed):e.outputText!==void 0?r=Fr(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function cP(e){switch(le(e.name)){case"web_search":return mL(e);case"bash":return PL(e);case"read":return xL(e);case"write":return wL(e);case"edit":return kL(e);case"grep":case"glob":return EL(e);case"task":return IL(e);case"todowrite":return ML(e);case"question":return OL(e);default:return DL(e)}}var jL=new Set(["AbortError","MessageAbortedError"]),LL=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],$L=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function lP(e){let t=e.toLowerCase();return $L.some(n=>t.includes(n))?!1:LL.some(n=>t.includes(n))}function BL(e){let t=e.data,n=t&&typeof t=="object"?t.message:void 0;return typeof n=="string"?n:typeof e.message=="string"?e.message:void 0}function Nr(e){if(typeof e=="string")return lP(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&jL.has(n))return!0;let r=BL(t);return typeof r=="string"?lP(r):!1}var uP=["user","runtime-disposed","orphan-finalized","wake"],UL=["orphan-finalized","wake"];function FL(e){if(!e||typeof e!="object")return;let t=e.data;if(!t||typeof t!="object")return;let n=t.reason;if(!(typeof n!="string"||!n))return uP.includes(n)?n:void 0}function Gr(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e??"")}function Vf(e){let t=Gr(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}var NL=Vf;function Vo(e){let t=Vf(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var qL=Vo;function pP(e){return Vo(e)!==null}var GL=pP,WL=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],KL=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],VL=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function dP(e){return VL.test(Gr(e))}function wn(e){let t=Gr(e);return t?dP(t)||WL.some(n=>n.test(t)):!1}var HL=/server url not ready|sandbox is still loading/i;function zL(e){return HL.test(Gr(e))||wn(e)}var qr=class extends Error{constructor(t){let n=t?.trim();super(n&&wn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function gP(e){let t=Vo(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${a}`,detail:o?`${i?`${i}: `:""}${o}`:void 0}}let n=Gr(e);return wn(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var YL=gP;function Hf(e){if(!e.external_id){if(e.base_url)return e.base_url;throw new Error(`Cannot build sandbox URL: missing external_id for ${e.provider} sandbox "${e.sandbox_id}"`)}return`${lt()}/p/${e.external_id}/${Je.BEEUNI_MASTER}`}function JL(e,t){return e.external_id?`${lt()}/p/${e.external_id}/${t}`:null}async function QL(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function mP(e){let t=await ur();if(t)return{sandbox:t.sandbox,created:!1};let r=(await At())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await Et(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await it(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Qs(r,s,o),created:!0}}async function XL(){return(await ur().catch(()=>null))?.sandbox??null}async function ZL(e){return{sandbox:(await mP(e)).sandbox}}async function e$(e){let t=lr(e);if(!t)return null;try{let n=await Rm(t);return n?Qs(await kt(n.project_id),n,null):(await ur(t))?.sandbox??null}catch{return null}}async function t$(e,t){throw await Xs(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function n$(e){let t=lr(e);return(await km().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function r$(){return null}async function s$(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Xs(e);if(!t)throw new Error("Project session sandbox not found");await Xn(t.projectId,t.sessionId)}async function o$(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Xs(e);if(!t)throw new Error("Project session sandbox not found");await Zn(t.projectId,t.sessionId)}async function i$(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function a$(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function zf(e,t,n){let r=Hf(e),s=await j(`${de(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function c$(e,t){return zf(e,`/beeuni/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function l$(e,t,n,r="member"){await zf(e,`/beeuni/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function u$(e,t,n){await zf(e,`/beeuni/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var Yf="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function p$(e){throw G("getInvite",Yf)}async function d$(e){throw G("acceptInvite",Yf)}async function g$(e){throw G("declineInvite",Yf)}async function m$(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function f$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function y$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function h$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function _$(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function b$(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}async function fP(e){let t=e?`?channel=${e}`:"",r=await(await Fe(`${lt()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await Jf(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function Jf(e){let t=e?`?channel=${e}`:"";return(await(await Fe(`${lt()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function yP(){return(await Fe(`${lt()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}var vn=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function hP(e,t){let n=new Headers(e.headers);return n.set("Accept","application/json"),t&&n.set("Content-Type","application/json"),e.accessToken&&n.set("Authorization",`Bearer ${e.accessToken}`),n}async function _P(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function bP(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function ue(e,t,n){let r=n?.body!==void 0,s=await fetch(`${It(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:hP(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await _P(s);if(!s.ok)throw new vn(bP(s,o),s.status,o);return o}function S$(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString();return n?`?${n}`:""}function SP(e,t){return ue(`/marketplace/items${S$(t)}`,e)}function PP(e){return ue("/marketplace/marketplaces",e)}function xP(e,t){return ue(`/marketplace/items/${encodeURIComponent(e)}`,t)}function wP(e,t,n){return ue(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function vP(e,t){return ue("/access/check-email",t,{method:"POST",body:{email:e}})}function AP(e,t){return ue("/access/request-access",t,{method:"POST",body:e})}function kP(e){return ue("/auth/logout",e,{method:"POST",body:{}})}function RP(e,t){return ue(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function CP(e,t){return ue("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function TP(e,t){return ue(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function EP(e,t){return ue(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function IP(e,t,n={}){return ue(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function MP(e,t){return ue(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function OP(e,t,n,r){return ue(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function DP(e,t){return ue(`/p/public-share/${encodeURIComponent(e)}`,t)}function jP(e,t,n){return ue(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function LP(e,t){return ue("/system/demo-request",t,{method:"POST",body:e})}async function $P(e,t,n){let r=await fetch(`${It(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Jt(t)}`,{headers:hP(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await _P(r);throw new vn(bP(r,s),r.status,s)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}function BP(e,t){throw G("buildPublicTemplateUrl")}async function UP(e,t,n){throw G("getPublicTemplate")}var P$="beeuni:connect-link:";function Qf(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);t=Math.imul(t^s,16777619)>>>0,n=Math.imul(n^s,1540483477)>>>0}return`${P$}${t.toString(36)}${n.toString(36)}`}function x$(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(Qf(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(Qf(i));return}return c}catch{return}},o=(i,a)=>{if(t)try{t.setItem(Qf(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=s(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var FP="Could not start the connect flow.";async function w$(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:FP}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:FP};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var NP=3e3,qP=5e3,GP=5*6e4;function v$(e,t){let n=e===0?NP:qP;return t+n>GP?null:n}function A$(e){let t=e.project_name?.trim();return{app:e.name?.trim()||e.app?.trim()||e.slug,project:t&&t!=="this project"?t:null}}var y2="1";var k$="beeuni.query-cache";function KP(e){return!!e&&typeof e.then=="function"}function WP(e){return KP(e)?e:Promise.resolve()}function R$(e){if(e[0]!=="kx")return!1;let t=e[1];if(t==="accounts")return e.length===3&&typeof e[2]=="string"&&e[2]!=="anonymous";if(t==="projects")return e.length===3;if(t!=="project"||typeof e[2]!="string")return!1;let n=e[3];if(e.length===4)return n==="summary"||n==="detail";if(n!=="sessions")return!1;if(e.length===6)return e[4]==="list-paged";if(e.length===7&&e[4]==="list-paged"){let r=e[6];return typeof r=="object"&&r!==null&&!r.q}return e.length===7&&e[4]==="list-children"?e[6]==="":e.length===5&&e[4]!=="list"&&e[4]!=="list-paged"}function C$(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=k$,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),S=()=>{try{return WP(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},E=(v,b)=>{if(!b)return 0;let P;try{P=JSON.parse(b)}catch{return S(),0}if(!P||P.v!==s||P.user!==n||!Array.isArray(P.queries)||p()-P.at>o)return S(),0;let O=0;for(let A of P.queries){if(!A||!Array.isArray(A.k)||A.d===void 0||typeof A.t!="number"||p()-A.t>o||!r(A.k))continue;let $=v.getQueryState(A.k);$&&$.data!==void 0&&$.dataUpdatedAt>=A.t||(v.setQueryData(A.k,A.d,{updatedAt:A.t}),v.invalidateQueries?.({queryKey:A.k,exact:!0,refetchType:"none"}),O+=1)}return O},L=v=>v.getQueryCache().getAll().filter(b=>b.state.data!==void 0&&r(b.queryKey)).map(b=>({k:b.queryKey,d:b.state.data,t:b.state.dataUpdatedAt})).sort((b,P)=>P.t-b.t),D=(v,b)=>{let P=[],O=0;for(let A of v){let $=JSON.stringify(A).length+1;O+$>b||(P.push(A),O+=$)}return P},w=async v=>{let b=D(L(v),i);for(;;){let P={v:s,user:n,at:p(),queries:b};try{await WP(t.setItem(d,JSON.stringify(P)));return}catch{if(b.length===0)return;b=b.slice(0,Math.floor(b.length/2))}}},y=()=>{f!==null&&(clearTimeout(f),f=null)},_=()=>{y();let v=g;return!v||!m||(m=!1,h=h.then(()=>w(v)).catch(()=>{})),h},R=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,_()},a))};return{storageKey:d,restore(v){let b;try{b=t.getItem(d)}catch{return 0}return KP(b)?b.then(P=>E(v,P)).catch(()=>0):E(v,b)},persist(v){g=v,m=!0;let b=v.getQueryCache().subscribe(P=>{P.type!=="updated"&&P.type!=="removed"&&P.type!=="added"||r(P.query.queryKey)&&R()});return()=>{b(),g===v&&(g=null,y())}},flush(){return _()},async clear(){y(),g=null,m=!1,await h,await S()}}}function T$(){let e;try{e=globalThis.localStorage}catch{e=void 0}if(!e)return null;let t=e;return{getItem:n=>{try{return t.getItem(n)}catch{return null}},setItem:(n,r)=>t.setItem(n,r),removeItem:n=>{try{t.removeItem(n)}catch{}}}}var VP="/beeuni/part/";function HP(e){return typeof e=="string"&&e.startsWith(VP)}async function E$(e){if(!HP(e))throw new Error(`not an attachment part reference: ${e}`);let t=Xe();if(!t)throw new Error("runtime url not bound");let n=await j(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function zP(e){try{let t=new URL(e);if(/^\/proxy\/\d+(?:\/|$)/.test(t.pathname))return`${t.origin}/v1/p/auth`;let n=t.pathname.indexOf("/p/");return n!==-1?`${t.origin}${t.pathname.slice(0,n)}/p/auth`:`${t.origin}/v1/p/auth`}catch{return null}}function I$(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.has(n.origin)}catch{return!1}}function Xf(e,t){return I$(e,t)?(t?zP(t):null)??zP(e):null}function Wr(e){try{let{hostname:t}=new URL(e);return/^p\d+-[^.]+\./.test(t)||/^(?:dev|staging|prod|preview)-p\d+-[a-z0-9-]+\./i.test(t)}catch{return!1}}function Zf(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var M$=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function O$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function D$(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let s=(t.slice(n+3).split("/")[0]??"").toLowerCase(),o=`${r}://${s}`.split("{port}").map(i=>i.split("{sandbox}").map(O$).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function j$(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function YP(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function L$(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:M$.test(n.hostname)?t.backendUrls.some(r=>{let s=j$(r);return s!==null&&YP(s)===YP(n)}):t.templates.some(r=>D$(n.origin,r))}async function JP(e,t={}){if(!Wr(e))return!1;let n=C().backendUrl;n&&await ut(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return L$(e,{templates:g_(),backendUrls:r})}async function QP(e,t={}){let n=Xf(e,t.serverUrl||C().backendUrl||void 0);if(!n)return!1;let r=await st();if(!r)return!1;try{return(await fetch(n,{method:"POST",credentials:"include",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).ok}catch{return!1}}async function $$(e,t={}){if(Wr(e)){if(!await JP(e,t))return e;let n=await st();return n?Zf(e,n):e}return await QP(e,t),e}var B$=3e3;function XP(e){return!Number.isFinite(e)||e<100||e>599?"unknown":e===502||e===503||e===504?"unreachable":e===401||e===403?"unknown":"reachable"}async function U$(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return XP(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function F$(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function N$(e,t){throw G("buildPresentationTemplatePdfUrl")}function q$(e,t){throw G("buildPresentationTemplateImageUrl")}function ZP(e,t){return`${F$(e)}/presentation/convert-to-${t}`}async function G$(e,t,n,r){let s=ZP(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!1;for(;;){let p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,S)=>{let E=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(E),S(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let h=JSON.parse(m);f=String(h.error||h.detail||h.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function W$(e){return e.activityFresh||e.runtimeReady?"live":e.unreachable||e.stalled?"unreachable":e.sandbox==="stopped"||e.sandbox==="archived"||e.sandbox==="provisioning"||e.sandbox==="queued"||e.sandbox==="branching"?"waking":e.sandbox==="completed"?"unknown":e.sandbox==="failed"?"unreachable":e.sandbox==="running"?"connecting":"unknown"}function K$(e){return e==="unreachable"}function V$(e){return!e||e.status===0?"unknown":e.ok&&Qm(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var ex=1e4,H$={connection:"unknown",faultSinceMs:null};function z$(e,t,n,r=ex){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let s=e.faultSinceMs??n;return n-s>=r?{connection:t,faultSinceMs:s}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:s}}function tx({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<Ho,c=!!t&&i-t.atMs<Jo;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:c,abortFloor:c?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=zo,streamFresh:!!s&&i-s.atMs<=An,inboxFresh:!!n&&i-n.atMs<=Yo,activityFresh:!!o&&i-o.atMs<=An}}function kn(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function ey(e,t,n){if(!t)return!1;let r=kn(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=kn(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function Y$(e,t,n,r){let{activity:s,server:o}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!ey(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function J$(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,c=i?s.turns.filter(g=>!ey(g,n,s)):[],p=c.find(g=>g.state==="active")??c[0],d=!!o&&!(o.type==="idle"&&o.origin==="local");return p&&s.atMs>=a&&(!d||s.atMs>=o.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:kn(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function Q$(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&o.type!=="idle"&&(!p||o.atMs>s.atMs)&&o.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&s.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function X$(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,S=c&&!n&&s.atMs>=p,E=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(S&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:kn(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(E)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let L=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:a};return{state:"idle",source:L.source,turnId:null,since:L.atMs,serverOpenTurnToken:r}}function nx(e){let t=tx(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=Y$(e,t,s,o);if(i)return i;let{result:a,openTurn:c}=J$(e,t,s,o);return a??Q$(e,t,o)??X$(e,t,c,o)}var Ho=6e4,zo=45e3,An=45e3,Yo=1e4,Z$=3e3,Jo=15e3;function e0(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function t0(e){let t=0;for(let n of e)(n.state==="queued"||n.state==="delivering"||n.state==="waiting"&&n.reason!=="held")&&(t+=1);return t}function n0(e){return nx(e)}function r0(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,c=[null,t?t.atMs+Ho:null,n?n.atMs+Jo:null,r?r.atMs+Yo:null,s?s.atMs+zo:null,o?o.atMs+An:null,i?i.atMs+An:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function rx(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(o=>o.message_id===t),r=e.last_ended,s=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!s?.message||Nr({name:s.name??void 0,message:s.message})?null:s}var s0="SandboxMemoryGuard";function o0(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=rx(e,t);if(r?.message){if(r.name!==s0)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let s=e.recent_failures?.find(a=>a.message_id===t);if(!s)return null;let o=s.ended_at?Date.parse(s.ended_at):Number.NaN;return Number.isFinite(o)&&typeof e.atMs=="number"&&e.atMs-o<2500?null:{kind:"unexplained"}}var i0=6e4;function a0(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function c0(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var sx=9e4;function l0(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+sx}var u0=75e3,p0=2,d0=2e4;function ty(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function g0(e){return e.filter(t=>t!=null).join("|")}function m0(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function f0(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...ty(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...ty(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!c&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return g;let f=m0(e.attempts,s);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var y0={"retry-start":"retrying",restart:"restarting"};function h0(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${y0[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function _0(e){return e===1?"once":e===2?"twice":`${e} times`}function b0(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(s=>s.step==="restart").length,n=e.attempts.some(s=>s.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${_0(t)}`),`Tried: ${r.join(", then ")}.`}var S0={"needs-you":{label:"Needs you",tone:"actionable",description:"Waiting for your review"},starting:{label:"Starting",tone:"progress",description:"Its computer is starting"},running:{label:"Running",tone:"live",description:"Its computer is up"},done:{label:"Done",tone:"muted",description:"Finished"},stopped:{label:"Stopped",tone:"muted",description:"Asleep. Opening it wakes its computer"},failed:{label:"Failed",tone:"danger",description:"Its computer didn't start"},legacy:{label:"Legacy",tone:"muted",description:"Imported. Open it to restore"}};function ox(e){return!!(e.metadata??{}).legacy_migration}function P0(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return"running";case"completed":case"stopped":return ox(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function x0(e){switch(e){case"waking":return{label:"Waking computer",tone:"progress"};case"connecting":return{label:"Connecting",tone:"progress"};case"unreachable":return{label:"Can't reach computer",tone:"danger"};default:return null}}var w0={unreachable:"Lost contact with this session's computer. Messages you send are queued until it reconnects.",unreachableMidTurn:"Lost contact with this session's computer while a turn is still open. Messages you send stay queued until it answers.",stalled:"Waking this session's computer is taking longer than usual. Messages you send are queued.",starting:"Starting this session's computer. Your message sends automatically.",idle:"This session's computer is asleep. Your next message wakes it up and is delivered.",waking:"Waking this session's computer. Messages you send are queued and go out automatically."};function v0(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function Qo(e){return e.runtime_sessions??e.opencode_sessions??[]}function ix(e){let t=Qo(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function A0(e){let t=ix(e);return t?Qo(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function k0(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>Qo(r).some(s=>s.id===t))??null)}var R0=new Set;function ax(e){for(let t of[...R0])try{t(e)}catch{}}var dx={schema:pe,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var gx=e=>Object.values(e.ext??{}).find(t=>t.version===ke),mx=e=>!!e&&gx(e)!==void 0,C0=e=>{let t=gx(e);return t?t.native_id??null:e.thread_id},cx=new WeakMap;function fx(e,t){let n=C0(e),r=cx.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=Vs({...dx,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return cx.set(t,{native:n,rows:o}),o}var ny=e=>e.info.time?.created;var T0=(e,t)=>(ny(e)??-1/0)-(ny(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var lx=new WeakMap,ux=new WeakMap,yx=e=>typeof e=="object"&&e!==null,E0=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,I0=e=>e.info.role==="user"&&e.parts.some(t=>yx(t)&&t.type==="compaction"),M0=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},px=new WeakMap;function O0(e,t,n){let r=t.info,s=`${e}|${String(r.id)}|${String(r.time?.created)}`,o=!1,i=n.blocks.map((a,c)=>{let p=t.parts[c];if(!yx(p)||a.type==="compaction")return a;let d=`${s}|${c}|${a.id}`,g=px.get(p);return g&&g.key===d?(o=!0,g.block):(px.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function D0(e){let t=new Map,n=new Set;for(let r of e){if(!I0(r))continue;let s=e.find(o=>!n.has(o)&&M0(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function j0(e,t,n,r,s){let o=lx.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=Hs({session_id:e,root_id:t,rows:(r?[n,r]:[n]).map(d=>({runtime_session_id:t,info:d.info,parts:d.parts}))},{live:!0}),c=O0(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:s,message:{...c,seq:s},lost:a.grade_counts};return lx.set(n,p),p}function hx(e,t,n){let r=ux.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(T0),{paired:o,used:i}=D0(s),a={tool_input:0,cut_point:0,attachment:0},c=[];for(let m of s){if(i.has(m))continue;let f=j0(e,t,m,o.get(m),c.length+1);for(let h of["tool_input","cut_point","attachment"])a[h]+=f.lost[h];c.push(f.message)}let p=E0(s.map(ny).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=c.filter(m=>m.role==="user"&&m.kind==="turn"),g={...dx,session_id:e,created_at:p,restore_grade:a.tool_input+a.cut_point+a.attachment>0?"partial":"converted",grade_counts:a,harness:{current:"opencode",history:[]},selection:{agent:d.at(-1)?.agent??null,model:d.at(-1)?.model??null},threads:[{schema:pe,v:1,thread_id:t,parent_thread_id:null,spawned_by:null,agent:d[0]?.agent??null,title:null,created_at:c[0]?.created_at||p,messages:c,ext:{opencode:{version:ke,native_id:t}}}]};return ux.set(n,{sessionId:e,native:t,log:g}),g}var ry=new WeakMap,Rn=new WeakMap,_x=new WeakMap;function Xo(e){let t,n=Rn.get(e);return n&&(t=L0(n).get(e.id)),t?(ry.set(t,e),t):(e.type!=="harness"?t=Ng(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=_x.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},_x.set(e,t)),t&&ry.set(t,e),t)}var Kr=e=>ry.get(e),Bt=e=>e.flatMap(t=>Xo(t)??[]),bx=new WeakMap;function L0(e){let t=bx.get(e);return t||bx.set(e,t=new Map(_t(e)[0]?.parts.map(n=>[n.id,n]))),t}var Sx=new Map;function _t(e){let t=Sx.get(e.thread_id);return t||(t={schema:pe,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},Sx.set(e.thread_id,t)),fx(t,e)}var $0="beeuni-v1-import";function kx(e,t){let n=Ff(e);return n?{cost:null,tokens:n}:void 0}var sy={schema:pe,v:1};function Zo(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var oy=e=>e.type==="tool_call",B0=e=>e.status==="pending"||e.status==="running",iy=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function Rx(e,t){let n=iy(e);return!B0(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var Px=new WeakMap;function Cx(e,t){let n=Px.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),s={...sy,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"beeuni-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return Px.set(e,s),s}var xx=new WeakMap;function U0(e){let t=xx.get(e);return t||(t={...sy,message_id:e.reply_to,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},xx.set(e,t)),t}var wx=new WeakMap;function F0(e){let t=wx.get(e);return t||(t={...sy,message_id:`${e.message_id}:continued`,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},wx.set(e,t)),t}var N0=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function q0(e,t){let n=[],r=new Map;for(let g of e){if(g.role!=="user"||g.kind==="context"||r.has(g.message_id))continue;let m={user:g,assistant:[],partial:!1};r.set(g.message_id,m),n.push(m)}let s=[],o=[],i=new Map,a=new Map,c=null,p=null;for(let g of e){if(g.role==="user"){let S=r.get(g.message_id);S&&!t.has(g.message_id)&&(c=S,i.has(S)||i.set(S,i.size),S.user.kind==="compaction"&&(p=S));continue}if(g.role!=="assistant"||N0(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??c;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let S=a.get(p);S||(S={user:F0(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,S)),f=S}if(f){f.assistant.push(g);continue}if(!g.reply_to){o.push(g);continue}let h=s[s.length-1];h&&h.user.message_id===g.reply_to?h.assistant.push(g):s.push({user:U0(g),assistant:[g],partial:!0})}if(o.length){let g=n[0]??s[0];g?g.assistant.unshift(...o):n.push({user:o[0],assistant:o.slice(1),partial:!1})}let d=n.filter(g=>!t.has(g.user.message_id)).flatMap(g=>{let m=a.get(g);return m?[g,m]:[g]});return[...s,...d,...[...t].flatMap(g=>r.get(g)??[])]}function G0(e,t){if(!t)return t;let n=t;for(let r of e){let s=r.continues;s&&(n===s.marker||n===s.prompt||t===s.prompt)&&(n=r.user.message_id)}return n}function W0(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=_t(n)[0]?.info?.error??n.error.message,s=we(r),o=Rr(r);return{code:n.error.code,message:s?.message||_e(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function K0(e,t,n){return e.length&&e.every(t)?kx(e.flatMap(r=>_t(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:ay(e,n)}function ay(e,t){let n=e.flatMap(r=>{let s=r.usage;if(!s)return[];let o={type:"step-finish",cost:s.cost??0,tokens:{input:s.input,output:s.output,reasoning:s.reasoning??0,cache:{read:s.cache_read,write:s.cache_write}}};return[{part:o,message:{info:{id:r.message_id,role:"assistant",providerID:r.model?.provider,modelID:r.model?.model},parts:[o]}}]});return kx(n,t)??null}function V0(e){if(e.kind!=="compaction")return null;let t=e.blocks.find(n=>n.type==="compaction")??null;return{block:t,hasContent:!!t?.summary?.trim(),inFlight:e.status==="streaming"}}function H0(e){let t=e.user.blocks;if(!t.length||!t.every(r=>r.type==="text"&&r.synthetic))return null;let n=e.assistant.length===1&&e.assistant[0].blocks.length===1?e.assistant[0].blocks[0]:null;return n&&oy(n)&&n.name==="bash"?n:null}function z0(e,t,n,r){if(!n.length)return[];let s=new Set(e.assistant.map(i=>i.message_id)),o=new Set;for(let i of n)i.spawned_by&&s.has(i.spawned_by.message_id)&&o.add(i.thread_id);for(let i of t){let a=i.type==="subtask"?i.thread_id:oy(i)?Or(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var Y0=e=>e.assistant.some(t=>t.blocks.some(n=>oy(n)&&le(n.name)==="todowrite"&&_n(n))),vx=new WeakMap,J0=[];function cy(e){let t=Zo(e.messages,n=>n.role==="assistant");return!!t&&wf(_t(t))}var Ax=new WeakMap;function Q0(e){let t=Ax.get(e);if(!t){let n=e.messages.filter(r=>r.in_context||r.status==="streaming");t=n.length===e.messages.length?e:{...e,messages:n},Ax.set(e,t)}return t}function ei(e,t={}){let n=t.hideOutOfContext?Q0(e):e,r=new Set(t.held??J0),s=q0(n.messages,r),o=Zo(n.messages,f=>f.role==="assistant"),i=cy(n),a=Lf({turns:s.map(f=>({userMessage:{info:{id:f.user.message_id}},assistantMessages:f.assistant.map(h=>({info:{time:h.status==="streaming"?{}:{completed:1},error:h.error??void 0}}))})),hintMessageId:G0(s,t.liveMessageId),unrunTurnIds:r}),c=Zo(s,Y0)??s[s.length-1],p=mx(n),d=f=>p||f.producer.harness===$0,g=t.threads??[],m=new Set(g.map(f=>f.thread_id));return s.map(f=>{let h=t.busy===!0&&a.workingTurnId===f.user.message_id,S=a.pendingTurnIds.includes(f.user.message_id),E=i&&f.assistant.includes(o),L=`${f.partial}|${h}|${S}|${f===c}|${E}`,D=vx.get(f.user);if(D&&D.key===L&&D.pricing===t.pricing&&D.heads===t.threads&&D.assistant.length===f.assistant.length&&D.assistant.every((v,b)=>v===f.assistant[b]))return D.turn;let w=f.assistant.flatMap(v=>v.blocks);for(let v of f.assistant)for(let b of v.blocks)Rn.set(b,v);let y=z0(f,w,g,m),_=f.assistant[f.assistant.length-1],R={id:f.user.message_id,user:f.user,assistant:f.assistant,partial:f.partial,continues:f.continues??null,blocks:w,status:E?"streaming":_?_.status:f.user.kind==="compaction"?f.user.status:"pending",error:W0(f),cost:K0([f.user,...f.assistant],d,t.pricing),compaction:V0(f.user),threads:y,plan:f===c,shell:H0(f),response:Zo(w,v=>v.type==="text"&&!!v.text.trim())??null,attachments:f.user.blocks.filter(v=>v.type==="attachment"&&(v.mime.startsWith("image/")||v.mime==="application/pdf")),live:h,queued:S,retrying:E};return vx.set(f.user,{assistant:f.assistant,key:L,pricing:t.pricing,heads:t.threads,turn:R}),R})}var ly=e=>Kr(e);function Mx(e,t={}){return Of(Mf(Bt(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(Kr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(ly)}:n.kind==="text"?{kind:n.kind,block:Kr(n.part)}:{kind:n.kind,block:ly(n.part)})}var X0=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:Bt(e.blocks)}:{kind:e.kind,part:Xo(e.block)};function Ox(e,t){let n=new Map(e.map(o=>[X0(o),o])),r=Nf([...n.keys()],t);if(!r)return null;let s=o=>o.map(i=>n.get(i));return{work:s(r.work),hoisted:s(r.hoisted),final:s(r.final)}}function Z0(e){if(!te(e)||!qg(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=bf(e);return(n.answers??qf(n.outputText??"",t.length)??[]).length>0}function Dx(e){return If(Bt(e),n=>Pn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(Z0)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:Kr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(ly),family:n.step.family,label:n.step.label,status:n.step.status,durationMs:n.step.durationMs};let r=e.find(o=>o.id===n.key.slice(8)),s=r&&Rn.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function jx(e,t){return Bf(Bt(e.blocks).map(n=>({part:n})),t?.flatMap(_t))}function Lx(e){return qo(Bt(e))}function $x(e){return Tf(Bt(e))}function Bx(e,t){return t.working?t.trailing?!0:e.some(n=>{if(n.type==="tool_call")return n.status==="pending"||n.status==="running";if(n.type!=="reasoning")return!1;let r=Xo(n),s=Rn.get(n);return!!r&&Ae(r)&&Go(r)&&(!s||s.status==="streaming")}):!1}var Tx=new WeakMap;function Ux(e){if(!iy(e))return e;let t=Tx.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},Tx.set(e,t)}return t}function eB(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function Fx(e){let t=e.map(ae),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=Df(t).map(eB);return ar({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function Nx(e,t,n){let r=ae(e),s=r.state;return ar({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function qx(e){let t=_t(e).map(r=>jo(r)),n=t.find(r=>r.error)?.error;return{parts:t.flatMap(r=>r.parts),error:n,isEmpty:t.every(r=>r.isEmpty)&&!n}}var Ex=Object.freeze([]),Ix=new WeakMap;function Gx(e){if(!e)return Ex;let t=Ix.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&_n(s)):[]);t=n.length?n:Ex,Ix.set(e,t)}return t}function Wx(e,t={}){let n={cost:null,messages:{all:0,user:0,assistant:0},tokens:{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},context:null};for(let r of ei(e)){let s=ay([r.user,...r.assistant],t.pricing);if(s)for(let o of Object.keys(n.tokens))n.tokens[o]+=s.tokens[o]}for(let r of e.messages){r.role==="user"?n.messages.user++:r.role==="assistant"&&n.messages.assistant++,r.kind==="compaction"&&r.status!=="streaming"&&n.messages.assistant++;let s=r.usage;(r.role==="assistant"||r.kind==="compaction")&&s&&s.input+s.output+(s.reasoning??0)+s.cache_read+s.cache_write>0&&(n.context=r)}return n.messages.all=n.messages.user+n.messages.assistant,n}var tB="prt_beeuni_restore_g";function Vx(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(tB))}function Hx(e,t){let n=new Map,r=[...e??[]].sort((s,o)=>s.from_seq-o.from_seq);for(let s=1;s<r.length;s++){let o=r[s],i=r[s-1].harness;if(o.harness===i)continue;let a=t.findIndex(c=>c.user.seq>=o.from_seq);a<0||a===0&&t[0].user.seq!==o.from_seq||n.set(t[a].id,{harness:o.harness,previous:i,version:o.version,at:o.at})}return n}var uy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,nB=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function zx(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.beeuni?.data,n=uy(t)?t.restore:void 0;if(!uy(n))return null;let r=uy(n.dropped)?n.dropped:{},s=e.grade_counts,o=[{kind:"message",count:nt(r.message)},{kind:"attachment",count:nt(s?.attachment)},{kind:"text",count:nt(r.text)+nt(n.truncated)},{kind:"tool_input",count:nt(s?.tool_input)},{kind:"tool_result",count:nt(r.tool_result)},{kind:"cut_point",count:nt(s?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,c])=>nB.has(a)?i:i+nt(c),0)}];return{generation:nt(n.generation),missing:o.filter(i=>i.count>0)}}var Yx=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function Jx(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of Yx(r))s.ref&&s.bytes!==void 0&&!t.has(s.ref)&&t.set(s.ref,s.bytes);return[...t].map(([n,r])=>({ref:n,bytes:r}))}var Qx=(e,t)=>{let n=e.ref===void 0?void 0:t.get(e.ref);if(n===void 0)return e;let{ref:r,bytes:s,...o}=e;return{...o,text:n}},rB=(e,t)=>e.map(n=>n.type==="text"?Qx(n,t):n),Kx=new WeakMap;function sB(e,t){let n=Kx.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>Yx(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?Qx(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:rB(s.result.content,t)}}:s)}:e;return Kx.set(e,{texts:t,out:r}),r}var ti=1024*1024;function Xx(e){return e.reduce((t,n)=>t+n.bytes,0)>ti?"download":"inline"}function Zx(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>ti)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function ew(e,t){if(t.size===0)return e;let n=e.messages.map(r=>sB(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function oB(e){return e==="TIMEOUT"||e==="request_deadline"}function iB(e){let t=nw(e)?e.code:void 0;return typeof t=="string"?t:void 0}var nw=e=>typeof e=="object"&&e!==null;function tw(e){let t=e?.metadata;return!!nw(t)&&t.warm===!0}var aB=5,cB=2e3,lB=e=>new Promise(t=>setTimeout(t,e));async function uB(e,{attempts:t=aB,delayMs:n=cB,sleep:r=lB}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function pB(e,t){let n=new Map,r=new Set,s=new Set,o=new Set,i=0,a=(c,p,d)=>{if(r.has(c)||n.has(c))return Promise.resolve();r.add(c);let g=i,m=(async()=>{let f=null;try{let h=await e.ensure(c,p);if(g!==i)return;s.has(h.sessionId)?f=h.sessionId:n.set(c,h)}catch{}finally{g===i&&r.delete(c)}f&&d>0&&await a(c,f,d-1)})();return o.add(m),m.finally(()=>o.delete(m)),m};return{ensure:(c,p)=>a(c,p?.excludeSessionId,1),take:(c,p,{replenish:d})=>{let g=n.get(c);return g?(n.delete(c),s.add(g.sessionId),d&&a(c,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(c,p,d)=>{try{return await e.claim(c,d),!0}catch(g){return oB(iB(g))?uB(async()=>!tw(await e.read(c,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:c=>{for(let[p,d]of n)if(d.sessionId===c)return n.delete(p),s.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(tw(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),s.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),s.clear()},settled:async()=>{for(;o.size>0;)await Promise.all([...o])}}}var dB=12e4,ni=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},gB=1e3,mB=15e3,rw=100,fB=50,yB=10;function sw(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let i=new URLSearchParams({limit:String(r)});s&&i.set("before",s);let a=await e.getToken?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!c.ok)throw c.status===503?new qr(`session ${c.status}`):new x(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function ow(e){return hB(sw(e))}function iw(e){return new py({...e,loadPage:sw(e)})}async function hB(e){let t=[],n=new Set,r;do{let i=await e({limit:rw,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])o.has(a.info.id)||(o.add(a.info.id),s.push(a));return s}var _B={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},py=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??_B,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??dB,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed||t==="visible"&&this.streamReliable&&this.snapshot.freshness==="fresh"?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof ni;if(!r&&Nr(n))return;if(r||this.update({freshness:wn(n)?"loading":"error"}),n instanceof x&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(gB*2**this.retryAttempt,mB);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?fB:rw,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,s=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",s,{once:!0});let o,i=new Promise((c,p)=>{o=this.startTimer(()=>{let d=new ni(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(o),n.removeEventListener("abort",s)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let i=[...t.messages],a=new Set(this.knownUserMessageIds),c=new Set(s?[s]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<yB&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw o?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,o?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,i=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};var bB=5e3,cw=40,mQ=5*6e4,SB=16,Vr=new Map;function lw(e,t,n,r=Date.now()){let s=uw(e,t);for(Vr.delete(s),Vr.set(s,{envelope:n,atMs:r});Vr.size>SB;){let o=Vr.keys().next().value;if(o===void 0)break;Vr.delete(o)}}var aw=new Map;function uw(e,t){return`${e}/${t}`}function PB(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=bB}function pw(e,t,n=Date.now()){if(!e||!t)return null;let r=uw(e,t),s=aw.get(r);return s?PB(s,n)?s.promise:(aw.delete(r),null):null}function dw(e){let t=e.transcript;if(!t||t.known!==!0||t.requested!==!0)return null;let{known:n,requested:r,...s}=t;if(!s.available)return s;let o=e.session?.runtime_session_id??e.session?.opencode_session_id,i=s.runtime_session_id??s.opencode_session_id;return o&&i===o?s:null}var xB=2e3;async function wB(e,t,n){let r=pw(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??xB,null)})]).finally(()=>clearTimeout(s)):null;return(o&&dw(o))??Yn(e,t,{limit:cw,history:!0,signal:n.signal})}async function gw(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s;try{s=await wB(t,n,{})}catch{return{envelope:null,empty:!1}}if(lw(t,n,s),dy(s)!==r)return{envelope:s,empty:!1};try{let o=await Jn(t,n);return{envelope:s,empty:gy({savedEmptyRoot:r,rootSessionId:r,turnRead:!0,hasEndedTurn:o.last_ended!=null,hasOpenOrQueuedTurn:o.turns.length>0})}}catch{return{envelope:s,empty:!1}}}function dy(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function gy(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function vB(e){throw G("buildTunnelEventStreamUrl")}function AB(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(w,y){o?.(w,y);let _=d.get(w);if(_)for(let R of _)try{R(y)}catch{}}async function S(){if(m)return;let w=new AbortController;g=w,p&&(p.aborted?w.abort():p.addEventListener("abort",()=>w.abort(),{once:!0}));let y=w.signal;try{let _={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(_["Content-Type"]="application/json"),f&&(_["Last-Event-ID"]=f);let R=await fetch(t,{method:r,headers:_,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:y,credentials:"include"});if(!R.ok)throw new Error(`SSE connection failed: ${R.status} ${R.statusText}`);if(!R.body)throw new Error("SSE response has no body");i?.();let v=R.body.getReader(),b=new TextDecoder,P="",O="message",A=[],$=T=>{if(T===""){A.length>0&&h(O,A.join(`
98
+ `)),O="message",A=[];return}if(T.startsWith(":"))return;let q=T.indexOf(":"),W=q===-1?T:T.slice(0,q),H=q===-1?"":T.slice(q+1);H.startsWith(" ")&&(H=H.slice(1)),W==="event"?O=H.trim()||"message":W==="data"?A.push(H):W==="id"&&!H.includes("\0")&&(f=H)},N=T=>{let q="";!T&&P.endsWith("\r")&&(q="\r",P=P.slice(0,-1));let W=P.split(/\r\n|\n|\r/);P=(W.pop()??"")+q;for(let H of W)$(H)};for(;!m;){let{done:T,value:q}=await v.read();if(T)break;P+=b.decode(q,{stream:!0}),N(!1)}m||(P+=b.decode(),N(!0),c?.())}catch(_){if(m||_ instanceof DOMException&&_.name==="AbortError")return;a?.(_ instanceof Error?_:new Error(String(_)))}}function E(){m=!0,g?.abort(),g=null,d.clear()}function L(w,y){let _=d.get(w)??new Set;_.add(y),d.set(w,_)}function D(w,y){d.get(w)?.delete(y)}return{connect:S,close:E,addEventListener:L,removeEventListener:D}}function kB(e,t){throw G("createTunnelEventStream")}var mw="/_beeuni/viewer",ri=6e4,Cn=new Map;function fw(){Cn.clear(),Hr.clear()}async function RB(e,t){let n;try{n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}})}catch{return null}if(n.status===401||n.status===404||!n.ok)return null;let r=await n.json().catch(()=>null);return r&&typeof r.user_id=="string"?r:null}async function my(e={}){let t=e.path??mw,n=e.fetch??((o,i)=>fetch(o,i)),r=Cn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=RB(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-ri:Date.now()+ri;return Cn.set(t,{session:o,expiresAt:a}),o});return Cn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function yw(e={}){let t=e.path??mw;return Object.assign(async()=>(await my(e))?.access_token??null,{invalidate:n=>{let r=Cn.get(t);r&&!r.inflight&&r.session?.access_token===n&&Cn.delete(t)}})}var Hr=new Map;async function CB(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let o=await n.json().catch(()=>null);o?.error==="app_not_linked"&&console.warn(`[beeuni] ${String(o.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let s=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return Hr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-ri:Date.now()+ri}),r.token}catch{return null}}function fy(e={}){let t=e.path??"/_beeuni/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((s,o)=>fetch(s,o));return async(s={})=>{let o=Hr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=CB(n,r).then(a=>(a===null&&Hr.delete(n),a));return Hr.set(n,i),i}}function hw(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("beeuniBinding needs the App origin: pass { origin } outside a browser.");return{url:`${de(n)}/_beeuni/apps/${encodeURIComponent(e)}`,token:fy({audience:e,fetch:t.fetch})}}var bt=class extends Error{code;constructor(t,n){super(n),this.name="BeeuniMemberError",this.code=t}},ve=e=>typeof e=="string"&&e.length>0?e:null;function _w(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function si(e){if(!e||typeof e!="object")return null;let t=e,n=ve(t.sub)??ve(t.subject)??ve(t.user_id)??ve(t.userId);return n?{userId:n,email:ve(t.email),name:ve(t.name),picture:ve(t.picture)??ve(t.pictureUrl),groups:_w(t.groups),groupIds:_w(t.group_ids??t.groupIds),role:ve(t.role),accountId:ve(t.account_id)??ve(t.accountId),projectId:ve(t.project_id)??ve(t.projectId)}:null}function Sw(e,t={}){let n=si(e);if(!n)throw new bt("unauthenticated","Sign in with Beeuni to continue.");let{groups:r,roles:s}=t;if(r&&!r.some(o=>n.groups.includes(o)||n.groupIds.includes(o)))throw new bt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new bt("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var TB=60,yy=new Map;function Pw(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function bw(e){return JSON.parse(new TextDecoder().decode(Pw(e)))}async function EB(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),s=e.slice(n+1),o=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(s),i=>i.charCodeAt(0))):decodeURIComponent(s);return JSON.parse(o)}if(/^https?:\/\//.test(e)){let n=yy.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>yy.delete(e)),yy.set(e,n)),n}return JSON.parse(e)}async function xw(e,t={}){let n=w=>{throw new bt("unauthenticated",`Beeuni sign-in token refused: ${w}.`)},r=t.jwks??ct("BEEUNI_AUTH_JWKS"),s=t.issuer??ct("BEEUNI_AUTH_ISSUER"),o=t.audience??ct("BEEUNI_AUTH_AUDIENCE");if(!r)return n("no key set configured (BEEUNI_AUTH_JWKS)");if(o!==!1&&!o)return n("no audience configured (BEEUNI_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,c,p]=i,d,g;try{d=bw(a),g=bw(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await EB(r,t.fetch??((w,y)=>fetch(w,y)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(w=>w.kty==="EC"&&(d.kid===void 0||w.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${c}`),S;try{S=Pw(p)}catch{return n("malformed")}let E=!1;for(let w of f)try{let{kid:y,alg:_,use:R,key_ops:v,...b}=w,P=await crypto.subtle.importKey("jwk",b,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},P,S,h)){E=!0;break}}catch{}if(!E)return n("bad signature");let L=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+TB<L)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let w=g.aud;if(!(w===o||Array.isArray(w)&&w.includes(o)))return n("wrong audience")}let D=si(g);return D||n("no subject")}function hy(e){let t=e.agents.map(IB),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function IB(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function _y(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Js(n?{...r,mode:null}:r))}function ww(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let o=e.selectedAgent?.trim();return o?{selected:o,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=_y(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(o=>o.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let s=e.defaultAgent?.trim();return s&&n.some(o=>o.name===s)?{selected:s,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var vw=hy;function Aw(e){return e.providerID==="beeuni"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function by(e){return{providerID:"beeuni",modelID:e}}function oi(e,t){let n=e.startsWith("beeuni/")?e.slice(7):e;if(!t){let r=n.indexOf("/");if(r>0&&r<n.length-1)return{providerID:n.slice(0,r),modelID:n.slice(r+1)}}return by(n)}var Sy=[{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"poe",env:["POE_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"infer",env:["INFER_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"bee",env:["BEE_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]}];function Py(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function OB(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"beeuni":e.id.slice(0,t)}function kw(e,t){let n=new Map;for(let r of e){let s=t(r),o=n.get(s);o?o.push(r):n.set(s,[r])}return n}function Se(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function Rw(e){return e.reduce((t,n)=>{let r=Py(n)??0,s=Py(t)??0;return r!==s?r>s?n:t:Se(n.id)>Se(t.id)?n:t})}function xy(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of kw(e,OB)){let a=[...kw(o,p=>p.family||p.id).values()].map(Rw),c=a.filter(p=>{let d=Py(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[Rw(a)])s.add(p.id)}return s}function ii(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>Se(r.id)>0)?n.filter(r=>Se(r.id)>0):n}function zr(e){let t;for(let n of ii(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&Se(n.id)>Se(t.id))&&(t=n)}return t}var DB={"amazon-bedrock":{methods:[{label:"Bearer token",envVars:["AWS_BEARER_TOKEN_BEDROCK","AWS_REGION"]}]},google:{methods:[{envVars:["GOOGLE_GENERATIVE_AI_API_KEY"]},{envVars:["GOOGLE_API_KEY"]},{envVars:["GEMINI_API_KEY"]}]}};function Cw(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var jB=(()=>{let e=new Map;for(let{id:n,env:r}of Sy)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let s=[...r].sort((o,i)=>o.length-i.length||o.localeCompare(i));t.set(n,r.find(o=>Cw(o)===n)??s[0])}return t})();function Tw(e){let t=DB[e.id];if(t)return t;let n=e.env??[],r=n.length===1?jB.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[Cw(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function wy(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var LB=["low","medium","high"];function Ew(e){if(!e)return{temperature:!1,topP:!1};let t=e.reasoning_options?.find(a=>a.type==="effort"),n=e.reasoning_options?.find(a=>a.type==="budget_tokens"),r=t?.values?.length?{values:t.values}:n?{values:[...LB]}:void 0,s=e.temperature===!0,o=e.limit?.output,i=typeof o=="number"&&o>0?{ceiling:o}:void 0;return{reasoningEffort:r,temperature:s,topP:s,maxOutputTokens:i}}var Iw=Sy;var $B=[{id:"gpt-6-astra",name:"GPT-6 Astra",upstreamModelId:"openai/gpt-6-astra",transport:"openrouter",pricingRef:"openrouter/openai/gpt-6-astra",pricing:{inputPerMillion:10,cachedInputPerMillion:1,cacheWritePerMillion:12.5,outputPerMillion:50,contextOver200k:{contextThreshold:272e3,inputPerMillion:20,cachedInputPerMillion:2,cacheWritePerMillion:25,outputPerMillion:75}},tier:"flagship",vision:!0,limit:{context:105e4,output:128e3},openrouterProvider:{order:["openai"],allow_fallbacks:!0}},{id:"gpt-6-sol",name:"GPT-6 Sol",upstreamModelId:"openai/gpt-6-sol",transport:"openrouter",pricingRef:"openrouter/openai/gpt-6-sol",pricing:{inputPerMillion:2.2,cachedInputPerMillion:.22,cacheWritePerMillion:2.75,outputPerMillion:11,contextOver200k:{contextThreshold:272e3,inputPerMillion:4.4,cachedInputPerMillion:.44,cacheWritePerMillion:5.5,outputPerMillion:16.5}},tier:"balanced",vision:!0,limit:{context:105e4,output:128e3},openrouterProvider:{only:["azure/us"],allow_fallbacks:!1,zdr:!0,data_collection:"deny"}}],OQ=new Map($B.map(e=>[e.id,e]));var Mw=["gpt-6-astra","gpt-6-sol"],Ow="gpt-6-astra",Dw="gpt-6-sol";var Lw=Iw.map(e=>({id:e.id,authRequirement:Tw(e)})),Yr=new Set(["beeuni"]),vy=new Set(["beeuni"]);function Tn(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,s=Array.isArray(r)?r:[];return s.length===0?{...e,all:[],connected:[]}:{...e,all:s,connected:s.map(o=>o.id)}}function BB(e){if(!e)return!1;let t=Tn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(s=>r.includes(s.id)&&s.models&&Object.keys(s.models).length>0)}function UB(e){let t=Tn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(s=>!vy.has(s.id)),connected:r.filter(s=>!vy.has(s))}}function FB(e,t,n){let r=Tn(e),s=Array.isArray(r.all)?r.all:[],o=new Set(s.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)o.has(a.id)&&wy(a.authRequirement,c=>t.has(c))&&i.add(a.id);return o.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var NB=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function qB(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var Ay="opencode";function GB(e){return e.cost?.input===0&&e.cost?.output===0}function jw(e){return e===Ay?Number.MAX_SAFE_INTEGER:NB.get(e)??Number.MAX_SAFE_INTEGER-1}function WB(e,t){let n=VB(t),r={},s=(e.providers??[]).map(o=>{let i=(o.models??[]).filter(a=>a.status!=="deprecated");return o.id===Ay&&!n.has(Ay)?{...o,models:i.filter(GB),keyless:!0}:{...o,models:i,keyless:!1}}).filter(o=>(o.keyless||n.has(o.id))&&!vy.has(o.id)&&(o.models?.length??0)>0).sort((o,i)=>jw(o.id)-jw(i.id)).map(o=>{let i=[...o.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||Se(p.id)-Se(c.id)),a=zr(i)?.id??i[0]?.id;return a&&(r[o.id]=a),{id:o.id,name:o.name,source:o.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=qB(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:s,connected:s.map(o=>o.id),default:r}}function KB(e,t){if(!e)return t;if(!t)return e;let n=Tn(e),r=Tn(t),s=new Map;for(let d of Array.isArray(r.all)?r.all:[])s.set(d.id,d);let o=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])o.push(s.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(o.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=s.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:o,connected:a,default:p}}function VB(e){let t=new Set;for(let n of Lw)wy(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function HB(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="beeuni/auto").map(([r,s])=>{if(s.variants&&Object.keys(s.variants).length>0)return[r,s];let o=Ew({id:r,name:s.name,reasoning:s.reasoning,reasoning_options:s.reasoning_options}).reasoningEffort?.values;return o?.length?[r,{...s,variants:Object.fromEntries(o.map(i=>[i,{}]))}]:[r,s]})),n=Object.keys(t)[0];return{default:n?{beeuni:n}:{},connected:["beeuni"],all:[{id:"beeuni",name:"Beeuni",source:"gateway",models:t}]}}function zB(e,t){return UB(FB(Tn(e),t,Lw))}function $w(e){if(e.gatewayEnabled)return e.modelPicker?HB(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?zB(e.runtimeProviders,t):void 0;return KB(e.llmCatalogProviders?WB(e.llmCatalogProviders,t):void 0,BB(n)?n:void 0)}function YB(e){return"capabilities"in e&&e.capabilities!=null}function ai(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function Bw(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],s=Array.isArray(e.connected)?e.connected:[],o=[];for(let i of r)if(s.includes(i.id)&&!(n==="gateway"?!Yr.has(i.id):Yr.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="beeuni/auto")continue;let p;if(YB(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}o.push({id:Aw({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return o}function Uw(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var JB=new Set([Ow]),QB="beeuni",Fw="codex",XB=new Set(Mw);function ZB(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function En(e){return JB.has(e.modelID)}function eU(e){return xy(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function Nw(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=eU(e.catalogModels),s=Uw(e.catalogModels),o=new Map;for(let i of e.pins??[])o.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,c=o.get(a);if(c==="hide")return!1;if(i.providerID===QB){let d=ZB(i.modelID,i.provider),g=d===Fw?t?.has(Fw)??!1:t?.has(d)??!1;if(XB.has(i.modelID))return!n||i.modelID===Dw;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return En(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return En(i)}catch{return En(i)}return!1}if(c==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return En(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return En(i)}catch{return En(i)}return!1}}function qw(e,t){return t.search.trim().length>0||e.providerID==="beeuni"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function Gw(e,t){if(!e||Yr.has(e.providerID)||Se(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>Se(i.modelID)>0))return e;let r=i=>Se(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,o=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??zr(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!o||o===e.modelID?e:{...e,modelID:o}}function Ww(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?by(n):void 0}function Kw(e){for(let t=(e?.length??0)-1;t>=0;t--){let n=e[t],{provider:r,model:s}=n.model??{};if(n.role==="user"&&r&&s)return{providerID:r,modelID:s}}}var tU=new Set(["explicit","repointed"]);function Vw(e){let t=e.session?er(e.session):null,n=t?oi(t,e.gatewayEnabled):void 0;return(tU.has(String(e.session?.metadata?.opencode_model_source))?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(o=>!!o)}function Hw(e){let{models:t,providers:n}=e,r=c=>ai(t,c),s=c=>c.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=c[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of ii(Object.keys(m.models).map(S=>({id:S})))){let S={providerID:m.id,modelID:h.id};if(r(S))return S}}}})(),i=s(e.picks??[]),a=i??s([e.serverDefault,e.globalDefault,e.agentModel,o]);return{model:Gw(a,t),explicit:i,fallback:o}}return ev(nU);})();