@beeuni/sdk 0.1.0 → 0.2.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 (106) hide show
  1. package/README.md +35 -83
  2. package/dist/beeuni.esm.min.js +35 -35
  3. package/dist/beeuni.global.js +35 -35
  4. package/dist/browser/stores/sync-store.d.ts +6 -0
  5. package/dist/browser/stores/sync-store.js +52 -21
  6. package/dist/core/client/beeuni.d.ts +7 -29
  7. package/dist/core/client/beeuni.js +3 -11
  8. package/dist/core/client/facade-catalog.d.ts +0 -4
  9. package/dist/core/client/facade-catalog.js +1 -5
  10. package/dist/core/client/project-connections.d.ts +2 -2
  11. package/dist/core/client/project-connections.js +2 -2
  12. package/dist/core/client/project-operations.d.ts +4 -15
  13. package/dist/core/client/project-operations.js +2 -6
  14. package/dist/core/client/project-platform-security.d.ts +1 -1
  15. package/dist/core/client/project-platform-settings.d.ts +1 -1
  16. package/dist/core/http/api-client.d.ts +0 -7
  17. package/dist/core/http/api-client.js +1 -37
  18. package/dist/core/http/auth.d.ts +2 -4
  19. package/dist/core/http/auth.js +2 -8
  20. package/dist/core/rest/platform-client/client-policy.d.ts +8 -0
  21. package/dist/core/rest/platform-client/client-policy.js +30 -0
  22. package/dist/core/rest/platform-client/index.d.ts +3 -4
  23. package/dist/core/rest/platform-client/index.js +3 -4
  24. package/dist/core/rest/platform-client/types.d.ts +1 -1
  25. package/dist/core/rest/projects-client/apps.d.ts +8 -1
  26. package/dist/core/rest/projects-client/connectors.d.ts +6 -55
  27. package/dist/core/rest/projects-client/connectors.js +2 -29
  28. package/dist/core/rest/projects-client/git-backend.d.ts +1 -10
  29. package/dist/core/rest/projects-client/git-backend.js +0 -10
  30. package/dist/core/rest/projects-client/iam-sso.d.ts +0 -10
  31. package/dist/core/rest/projects-client/iam-sso.js +0 -3
  32. package/dist/core/rest/projects-client/index.d.ts +1 -4
  33. package/dist/core/rest/projects-client/index.js +1 -4
  34. package/dist/core/rest/projects-client/projects.d.ts +2 -1
  35. package/dist/core/rest/projects-client/projects.js +3 -0
  36. package/dist/core/rest/projects-client/sandbox.d.ts +8 -9
  37. package/dist/core/rest/projects-client/session-sandbox.d.ts +1 -1
  38. package/dist/core/rest/projects-client/sessions.d.ts +2 -2
  39. package/dist/core/session/control-stream.d.ts +1 -0
  40. package/dist/core/session/control-stream.js +18 -1
  41. package/dist/core/session-log/guard.d.ts +6 -0
  42. package/dist/core/session-log/guard.js +109 -0
  43. package/dist/core/session-log/index.d.ts +3 -0
  44. package/dist/core/session-log/index.js +2 -0
  45. package/dist/core/session-log/saved-log.d.ts +10 -0
  46. package/dist/core/session-log/saved-log.js +25 -0
  47. package/dist/core/session-log/source.d.ts +25 -0
  48. package/dist/core/session-log/source.js +30 -0
  49. package/dist/core/session-log/store.d.ts +21 -0
  50. package/dist/core/session-log/store.js +126 -0
  51. package/dist/core/session-log/tool-call.d.ts +6 -0
  52. package/dist/core/session-log/tool-call.js +46 -0
  53. package/dist/core/session-log/types.d.ts +264 -0
  54. package/dist/core/session-log/types.js +6 -0
  55. package/dist/core/session-log/v1-view.d.ts +10 -0
  56. package/dist/core/session-log/v1-view.js +151 -0
  57. package/dist/core/session-log/v1.d.ts +31 -0
  58. package/dist/core/session-log/v1.js +466 -0
  59. package/dist/core/session-sync/copy-store-types.d.ts +19 -0
  60. package/dist/core/session-sync/copy-store-types.js +1 -0
  61. package/dist/core/session-sync/saved-copy-store.js +25 -4
  62. package/dist/core/stream/event-stream.js +2 -2
  63. package/dist/core/turns/classify.d.ts +2 -1
  64. package/dist/core/turns/classify.js +3 -1
  65. package/dist/core/turns/parts.d.ts +3 -2
  66. package/dist/core/turns/parts.js +4 -2
  67. package/dist/core/turns/segments/index.d.ts +1 -0
  68. package/dist/core/turns/segments/index.js +1 -0
  69. package/dist/core/turns/segments/work-split.d.ts +10 -0
  70. package/dist/core/turns/segments/work-split.js +40 -0
  71. package/dist/core/turns/state.d.ts +2 -7
  72. package/dist/core/turns/state.js +28 -134
  73. package/dist/core/turns/tools/tool-meta.d.ts +2 -1
  74. package/dist/core/turns/tools/tool-meta.js +3 -1
  75. package/dist/core/turns/tools/tool-outcome.d.ts +2 -1
  76. package/dist/core/turns/tools/tool-outcome.js +3 -1
  77. package/dist/core/turns/types.d.ts +1 -1
  78. package/dist/core/warm-session-pool.d.ts +29 -0
  79. package/dist/core/warm-session-pool.js +127 -0
  80. package/dist/index.d.ts +2 -2
  81. package/dist/index.js +2 -2
  82. package/dist/internal/connector-catalog.d.ts +47 -0
  83. package/dist/internal/connector-catalog.js +27 -0
  84. package/dist/internal/host-configuration.d.ts +22 -0
  85. package/dist/internal/host-configuration.js +28 -0
  86. package/dist/internal/platform-admin-react.d.ts +12 -0
  87. package/dist/internal/platform-admin-react.js +13 -0
  88. package/dist/internal/platform-admin.d.ts +9 -0
  89. package/dist/internal/platform-admin.js +9 -0
  90. package/dist/react/index.d.ts +0 -13
  91. package/dist/react/index.js +0 -13
  92. package/dist/react/opencode.d.ts +1 -0
  93. package/dist/react/opencode.js +1 -0
  94. package/dist/react/query-keys.d.ts +0 -1
  95. package/dist/react/query-keys.js +0 -1
  96. package/dist/react/session-transcript-subscription.js +3 -1
  97. package/dist/react/sign-in-with-beeuni.d.ts +1 -1
  98. package/dist/react/use-admin-providers.d.ts +5 -5
  99. package/dist/react/use-opencode-events/handle-event.d.ts +1 -0
  100. package/dist/react/use-opencode-events/handle-event.js +5 -0
  101. package/dist/react/use-opencode-events/index.js +1 -0
  102. package/dist/react/use-runtime-reconnect.js +2 -2
  103. package/dist/react/use-session-log.d.ts +15 -0
  104. package/dist/react/use-session-log.js +134 -0
  105. package/dist/react/use-session.js +2 -0
  106. package/package.json +15 -7
@@ -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 Ao=Object.defineProperty;var cS=Object.getOwnPropertyDescriptor;var lS=Object.getOwnPropertyNames;var uS=Object.prototype.hasOwnProperty;var pS=(e,t)=>{for(var n in t)Ao(e,n,{get:t[n],enumerable:!0})},dS=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of lS(t))!uS.call(e,s)&&s!==n&&Ao(e,s,{get:()=>t[s],enumerable:!(r=cS(t,s))||r.enumerable});return e};var gS=e=>dS(Ao({},"__esModule",{value:!0}),e);var I$={};pS(I$,{ABORT_REASONS:()=>x_,ABORT_REASONS_NOT_YET_EMITTED:()=>YO,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>jo,ANALYTICS_UNAVAILABLE_CODE:()=>Do,ATTACHMENT_PART_REF_PREFIX:()=>sP,ApiError:()=>_,AuthError:()=>ne,BEEUNI_TRANSCRIPT_SCHEMA:()=>Rt,BeeuniMemberError:()=>ut,BillingError:()=>ze,CONNECTION_FAULT_GRACE_MS:()=>dP,CONNECTOR_POLL_FIRST_DELAY_MS:()=>Z_,CONNECTOR_POLL_INTERVAL_MS:()=>eP,CONNECTOR_POLL_WINDOW_MS:()=>tP,CONTEXT_TOOLS:()=>Eb,ConnectorApprovalPendingError:()=>Xr,ConnectorCallError:()=>Tn,ConnectorPageLimitError:()=>Zr,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>Mb,DEFAULT_NOTIFICATION_PREFERENCES:()=>Zv,DEFAULT_TRANSCRIPT_OPTIONS:()=>jg,FEATURE_DISABLED_CODE:()=>jr,FEATURE_FLAG_KEYS:()=>YS,FEATURE_NOT_SUPPORTED_CODE:()=>Eo,FILE_VERBS:()=>lt,FileExistsError:()=>Xt,HeadlessAuthError:()=>Wt,HostBoundaryError:()=>gn,INBOX_NOTIFICATION_KINDS:()=>Xv,INBOX_OBSERVATION_MAX_MS:()=>fo,INITIAL_SETTLED_CONNECTION:()=>rj,KNOWN_TOOL_KINDS:()=>lf,MAX_PROMPT_ATTACHMENTS_BYTES:()=>Wx,MAX_PROMPT_ATTACHMENT_BYTES:()=>hc,MAX_PROMPT_ATTACHMENT_FILES:()=>nf,MEMORY_VERBS:()=>aO,MODEL_NOT_SERVABLE_CODE:()=>Mo,NO_GROUP_ACTIVITY_TOOLS:()=>Qf,OPTIMISTIC_ABORT_MAX_MS:()=>yo,OPTIMISTIC_COMPACTION_MAX_MS:()=>yj,OPTIMISTIC_RECEIPT_MAX_MS:()=>go,PERSISTED_QUERY_CACHE_VERSION:()=>bV,PLUMBING_TOOLS:()=>zb,PREVIEW_PROBE_TIMEOUT_MS:()=>zD,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>Rw,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>kw,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>xf,PROVISION_IN_FLIGHT_CODE:()=>Oo,PublicSessionShareError:()=>us,RUNTIME_NOT_READY_MARKERS:()=>tD,RUNTIME_PERMISSION_CAPABILITIES:()=>Ok,RUNTIME_PERMISSION_REPLIES:()=>Mk,RequestTooLargeError:()=>mt,RuntimeNotReadyError:()=>Jt,SANDBOX_FS_ROOTS:()=>Ns,SANDBOX_PORTS:()=>Be,SERVER_COMPACTION_REVALIDATE_MS:()=>yP,SERVER_OBSERVATION_MAX_MS:()=>mo,SESSION_LIST_STATUS:()=>Tj,SESSION_LOG_MINOR:()=>Ft,SESSION_LOG_SCHEMA:()=>$e,SESSION_NOTICE:()=>Oj,STANDALONE_TOOLS:()=>Xf,STREAM_OBSERVATION_MAX_MS:()=>mn,SandboxNotReadyError:()=>wr,SessionNotReadyError:()=>wt,SessionStartError:()=>os,TURN_END_LEDGER_LAG_MS:()=>lj,TURN_ERROR_CODES:()=>Cy,WAKE_ESCALATION_COOLDOWN_MS:()=>xj,WAKE_MAX_RESTARTS:()=>Sj,WAKE_NO_PROGRESS_MS:()=>Pj,WIRE_ID_BACKDATE_MS:()=>Os,WIRE_ID_CLOCK_TOLERANCE:()=>rt,WIRE_ID_TIME_MASK:()=>Fe,WIRE_ID_TIME_SCALE:()=>Ht,WIRE_MESSAGE_ID:()=>xy,__getConfigResolver:()=>yS,__setConfigResolver:()=>fS,abortErrorReason:()=>JO,acceptAccountInvite:()=>si,acceptInvite:()=>xD,actReviewItem:()=>mp,activateConnection:()=>Ca,addComputerToProject:()=>Ea,addGroupMembers:()=>qu,addMarketplaceSource:()=>Qp,advanceWakeEscalation:()=>vj,allDescendantIds:()=>Wb,appendPreviewToken:()=>Am,approveProjectAccessRequest:()=>Di,approveTask:()=>Gk,archiveProject:()=>In,assignTicket:()=>Qk,attachGroupToProject:()=>Wi,authMfa:()=>Ts,authUser:()=>Rs,authenticatedFetch:()=>j,authenticatedRequest:()=>Mn,authorizePreviewUrl:()=>HD,backendApi:()=>l,beeuniAppViewerToken:()=>TP,beeuniBinding:()=>EP,beeuniPty:()=>jy,beeuniToken:()=>Im,bindSlackIdentity:()=>nA,bindTeamsIdentity:()=>rA,brokerProjectSecretRequest:()=>na,browserKeyValueStorage:()=>BD,buildPresentationTemplateImageUrl:()=>XD,buildPresentationTemplatePdfUrl:()=>QD,buildPreviewAuthEndpoint:()=>wm,buildPublicTemplateUrl:()=>J_,buildRuntimePresentationConversionUrl:()=>pP,buildSandboxTemplate:()=>lc,buildScrapeFailureResults:()=>Qb,buildStaticFileHealthPreviewUrl:()=>HC,buildStaticFileLocalUrl:()=>VC,buildStaticFilePreviewUrl:()=>KC,buildStaticFileServicePath:()=>gh,buildTunnelEventStreamUrl:()=>Xj,buildWebProxyUrl:()=>XC,bulkActReviewItems:()=>fp,bulkDeletePolicies:()=>vA,bulkImportPolicies:()=>kA,burstSummary:()=>vE,burstSummaryLabel:()=>kE,callConnector:()=>ht,cancelAccountDeletion:()=>Ff,cancelAccountInvite:()=>ei,cancelSandbox:()=>yD,cancelScheduledChange:()=>zl,cancelSubscription:()=>Kl,checkAccessEmail:()=>$_,childMapByParent:()=>dE,claimNext:()=>Bh,claimPerSeatBilling:()=>Qw,claimWarmProjectSession:()=>Jc,classifyPart:()=>Zg,classifyPreviewProbeStatus:()=>uP,classifyPtyClose:()=>My,classifyTurn:()=>Lb,cleanErrorMessage:()=>PE,cleanResultSnippet:()=>TE,cleanWorkerOutput:()=>tO,clearBeeuniAppViewerCache:()=>IP,clearModelDefault:()=>Tl,clearSessionFresh:()=>sw,closeChangeRequest:()=>Ec,closeMilestone:()=>vR,collectTurnParts:()=>cE,commentTicket:()=>Zk,commitSessionChanges:()=>Dc,compactionExpiryAtMs:()=>bj,compactionTurnInfo:()=>RE,compareMessagesForDisplay:()=>rE,compareSemver:()=>aI,completeInFlight:()=>Fh,completeSlackInstall:()=>iu,completeTeamsInstall:()=>au,composerSelectableAgents:()=>Mm,computeStatusFromPart:()=>dm,configureAutoTopup:()=>Xl,configureBeeuni:()=>Er,confirmCheckoutSession:()=>Gl,connectEmail:()=>fu,connectSlack:()=>su,connectionFromHealth:()=>nj,connectionIsFaulted:()=>tj,connectionSharedWithEveryone:()=>Px,connectorConnect:()=>Wa,connectorConnectConnection:()=>Oa,connectorFinalize:()=>Xa,connectorFinalizeConnection:()=>Da,connectorHeadline:()=>jD,contextLabelForTool:()=>BE,contextToolSummary:()=>iT,contextToolTrigger:()=>aT,convertPresentationToGoogleSlides:()=>lv,convertRuntimePresentation:()=>ZD,copyFile:()=>ir,costExportUrl:()=>eu,countLiveInboxPrompts:()=>pj,countReviewItemsBySegment:()=>pv,createAccount:()=>Go,createAccountAuditWebhook:()=>Fp,createAccountSecretResource:()=>pa,createAccountToken:()=>Cp,createApp:()=>ed,createAppAccessSession:()=>cd,createAppDeployment:()=>ud,createAppToken:()=>rd,createAppVolume:()=>Rd,createAppVolumeSnapshot:()=>Ed,createArtifactKind:()=>aM,createAssignment:()=>cp,createAuditWebhook:()=>tv,createBackup:()=>vD,createBeeuni:()=>jh,createBeeuniPty:()=>yg,createBeeuniSession:()=>Ms,createCheckoutSession:()=>ql,createConnector:()=>Ka,createConnectorLinkInfoCache:()=>MD,createFile:()=>or,createGatewayKey:()=>Ou,createGroup:()=>Lu,createHttpSessionSyncController:()=>vP,createMarketplaceInstallSession:()=>Iv,createMilestone:()=>wR,createModelVisibility:()=>nS,createOAuthClient:()=>rp,createPerSeatCheckout:()=>Jw,createPersistedQueryCache:()=>LD,createPolicy:()=>xA,createPortalSession:()=>Wl,createProject:()=>mi,createProjectAgent:()=>lR,createProjectCliToken:()=>Op,createProjectRepo:()=>fi,createProjectResourceGrant:()=>zi,createProjectSession:()=>Pt,createProjectSkill:()=>Si,createProjectTrigger:()=>_l,createPromptAttachmentController:()=>Og,createRole:()=>Yu,createSSEStream:()=>Zj,createSandbox:()=>lD,createSandboxShare:()=>Pp,createSandboxTemplate:()=>ic,createSavedCopyStore:()=>xw,createScimToken:()=>TA,createServiceAccountApi:()=>QA,createSessionPrompt:()=>Bn,createSessionPublicShare:()=>Hc,createSessionQueue:()=>Uh,createSessionReminder:()=>wp,createSsoGroupMapping:()=>qA,createTask:()=>Fk,createTicket:()=>zk,createTunnelEventStream:()=>e$,createWarmSessionPool:()=>Wj,currentSavedCopyStore:()=>Bc,declineAccountInvite:()=>oi,declineInvite:()=>wD,deleteAccountImmediately:()=>Nf,deleteAccountSecretResource:()=>ma,deleteApp:()=>nd,deleteAppDeployment:()=>yd,deleteAuditWebhook:()=>rv,deleteBackup:()=>RD,deleteBeeuniProject:()=>bR,deleteConnector:()=>Ha,deleteConnectorCredential:()=>Qa,deleteCredential:()=>MR,deleteDriveFile:()=>Hv,deleteEnv:()=>gg,deleteFile:()=>Ct,deleteGatewayBudget:()=>Eu,deleteGitHubInstallation:()=>Mi,deleteGroup:()=>Fu,deleteMilestone:()=>RR,deleteOAuthClient:()=>ip,deletePersonalProjectSecret:()=>ca,deletePolicy:()=>AA,deleteProjectAgent:()=>pR,deleteProjectProviderOAuth:()=>sa,deleteProjectResourceGrant:()=>Yi,deleteProjectSecret:()=>ia,deleteProjectSession:()=>cl,deleteProjectTrigger:()=>Sl,deletePromptAttachment:()=>Lt,deleteRole:()=>Xu,deleteSandboxTemplate:()=>cc,deleteServiceAccountApi:()=>ZA,deleteSessionPrompt:()=>nl,deleteSessionReminder:()=>ds,deleteSessionReminders:()=>vp,deleteSsoGroupMapping:()=>GA,deleteSsoProvider:()=>FA,deleteTask:()=>Wk,deleteTicket:()=>eR,describeAccountInvite:()=>ri,describeConnectorTool:()=>Hr,destroyAppMachine:()=>wd,destroyAppVolume:()=>Id,detachGroupFromProject:()=>Vi,detectLocalhostUrls:()=>lh,directSubsessions:()=>jj,disableServiceAccountApi:()=>XA,disconnectEmail:()=>yu,disconnectSlack:()=>lu,discoverConnectionOAuth2:()=>Ax,discoverConnectionOAuth2Resource:()=>vx,discoverConnectorAuth:()=>Va,discoverLocalSandbox:()=>gD,dismissDriveConflict:()=>Fv,downloadAccountAudit:()=>Y_,downloadDriveFile:()=>qv,dropClientForUrl:()=>qR,dropPublicClientForUrl:()=>KR,editQueued:()=>Wh,editSessionPrompt:()=>rl,enqueue:()=>Lh,ensurePmSession:()=>aR,ensurePreviewSessionCookie:()=>lP,ensureProjectConnectorConnection:()=>Sx,ensureSandbox:()=>k_,ensureWarmProjectSession:()=>Yc,env:()=>Ty,exchangeCode:()=>As,execInApp:()=>vd,exportAccountAudit:()=>Lp,extractGatewayErrorDetails:()=>be,extractSkillBaseDir:()=>y_,extractSkillContent:()=>fO,extractSkillFiles:()=>f_,extractWorkerPreview:()=>rO,failInFlight:()=>Nh,fallbackBusyRowAfterTurnId:()=>MM,familyForTool:()=>co,featureDisabledKey:()=>Co,featureFlags:()=>eg,fetchAccountStateWithToken:()=>Hw,fetchAccountsWithToken:()=>zS,fetchAttachmentPart:()=>FD,fetchBeeuniAppViewer:()=>Cm,fetchCostExportCsv:()=>tA,fetchProjectArchive:()=>fc,fetchProjectFileRaw:()=>Gx,fetchProjectsForAccountWithToken:()=>sx,fetchSessionAttachment:()=>Xd,fileDownloadRequest:()=>Vy,filePhase:()=>iO,fileVerb:()=>oO,files:()=>Zy,finalizeAppArtifact:()=>fs,finalizeConnectorSetupLink:()=>G_,findActiveTranscriptShare:()=>Iw,findFiles:()=>rr,findLastTextPart:()=>lE,findSessionAttachments:()=>mk,findText:()=>sr,fireProjectTrigger:()=>wl,fixSandboxWithAgent:()=>oc,flattenModels:()=>ZP,flattenThought:()=>fM,forkAppVolume:()=>Od,formatBillingErrorForUI:()=>To,formatCost:()=>VM,formatDuration:()=>gm,formatJsonFailureOutput:()=>SE,formatMessageDay:()=>SM,formatMessageExact:()=>xM,formatOpenCodeRuntimeError:()=>oD,formatRawOutput:()=>IE,formatRuntimeError:()=>v_,formatTokens:()=>HM,formatTranscript:()=>Vh,freshSendHint:()=>$M,generateSessionId:()=>$h,getAccount:()=>Wo,getAccountBranding:()=>Vo,getAccountDeletionStatus:()=>Lf,getAccountState:()=>jl,getAccountStateMinimal:()=>$l,getAgentCardLabel:()=>$b,getAgentConfig:()=>qw,getAgentPersona:()=>dR,getAllVersions:()=>C_,getAnsweredQuestionParts:()=>pE,getApp:()=>gs,getAppAccess:()=>od,getAppAuthEnv:()=>sd,getAppDeployment:()=>dd,getAppDeploymentLogs:()=>gd,getApprovalLink:()=>Cv,getAuthToken:()=>Ye,getAuthTokenWithRetry:()=>gx,getAutoTopupSettings:()=>Ql,getAutoTopupSetupStatus:()=>Yw,getBeeuniProject:()=>fR,getBeeuniProjectBySession:()=>yR,getBeeuniPtyWebSocketUrl:()=>_g,getBillingCreditBreakdown:()=>Bl,getBillingTierConfigurations:()=>Nl,getBillingTransactionsSummary:()=>Ll,getBillingUsageHistory:()=>Fl,getChangeRequest:()=>kc,getChangeRequestDiff:()=>Rc,getChangeRequestMergePreview:()=>Cc,getChildSessionError:()=>ST,getChildSessionId:()=>Yg,getChildSessionToolParts:()=>xT,getClient:()=>ot,getClientForUrl:()=>Ae,getConnectStatus:()=>Ya,getConnectionOAuth2Application:()=>wx,getConnectionOAuth2Status:()=>Tx,getConnectionPolicies:()=>Ex,getConnectorCatalog:()=>Ut,getConnectorConfig:()=>qa,getConnectorPolicies:()=>Fa,getConnectorSetupLink:()=>N_,getCostSummary:()=>eA,getCurrentProject:()=>Ag,getDefaultAccountState:()=>Dl,getDiagnostics:()=>kT,getDirectory:()=>jb,getDiscoverConnector:()=>Qr,getDiscoverIntegration:()=>Ux,getDriveFileUrl:()=>Dd,getEmailInstallation:()=>gu,getEmailMode:()=>mu,getEnterpriseDemo:()=>ov,getFileStatus:()=>nr,getFileWithDir:()=>Hg,getFilename:()=>Db,getFolderAccess:()=>jv,getFullChangelog:()=>Sm,getGatewayBreakdown:()=>ku,getGatewayBudgets:()=>Iu,getGatewayErrors:()=>Cu,getGatewayKeys:()=>Mu,getGatewayLog:()=>wu,getGatewayOverview:()=>Au,getGatewayRoutingPolicy:()=>bu,getGatewaySeries:()=>vu,getGatewaySessions:()=>Ru,getGitHubInstallation:()=>Ai,getGoogleAuthUrl:()=>cv,getGroup:()=>Uu,getHiddenToolParts:()=>yT,getInvite:()=>SD,getLatestSandboxVersion:()=>R_,getManagedGitBackend:()=>ix,getManagedGitStatus:()=>ex,getMarketplaceCatalogItem:()=>zp,getMarketplaceCatalogItemFile:()=>Yp,getMfaRequired:()=>MA,getMilestone:()=>SR,getMobileClientPolicy:()=>Dg,getModelDefaults:()=>Cl,getNotificationPreferences:()=>Bd,getOAuthClient:()=>np,getOAuthConsentRequest:()=>B_,getOpenCodeConfigInvalidError:()=>XO,getPartText:()=>gT,getPatPolicy:()=>zA,getPermissionForTool:()=>RT,getProject:()=>An,getProjectActivity:()=>gR,getProjectCommit:()=>Sc,getProjectCommitDiff:()=>xc,getProjectDetail:()=>vn,getProjectDrive:()=>Dv,getProjectFileHistory:()=>wc,getProjectGitToken:()=>gi,getProjectLlmCatalog:()=>kn,getProjectLlmCatalogProviders:()=>QS,getProjectModelAccess:()=>Wn,getProjectModelPicker:()=>Rn,getProjectSandboxHealth:()=>En,getProjectSandboxProviderTransition:()=>tx,getProjectSession:()=>Ln,getProjectSessionConfigState:()=>ll,getProjectSessionScope:()=>dl,getProrationPreview:()=>Yl,getProviders:()=>aD,getProxyBaseUrl:()=>zC,getPublicClientForUrl:()=>WR,getPublicMarketplaceItem:()=>D_,getPublicMarketplaceItemFile:()=>j_,getPublicSessionShare:()=>wv,getPublicSessionShareMessages:()=>Av,getPublicShareByToken:()=>V_,getPublicTemplate:()=>Q_,getQuestionForTool:()=>CT,getReferralCode:()=>pA,getReferralStats:()=>mA,getRetryInfo:()=>zM,getRetryMessage:()=>YM,getReviewItem:()=>dp,getRolePermissions:()=>Hu,getRoleUsage:()=>zu,getRuntimeConfigInvalidError:()=>po,getSSHConnection:()=>ID,getSandbox:()=>cD,getSandboxById:()=>uD,getSandboxPortUrl:()=>iD,getSandboxUrl:()=>bm,getSandboxUrlForExternalId:()=>Qe,getSecretSetupLink:()=>W_,getServerHealth:()=>qs,getServiceLogs:()=>UR,getSessionAudit:()=>Qc,getSessionCostRecord:()=>Gn,getSessionDrives:()=>Yf,getSessionHealth:()=>Cg,getSessionMessageAuthors:()=>yl,getSessionModelUsage:()=>hl,getSessionOpenBundle:()=>Tw,getSessionOversight:()=>jA,getSessionParticipants:()=>qc,getSessionPolicy:()=>WA,getSessionPreviewCandidates:()=>Kc,getSessionProviderSecretPool:()=>ba,getSessionTranscript:()=>Xc,getSessionTranscriptSync:()=>Zc,getSessionTurn:()=>el,getSessionWatch:()=>Gc,getShellModePart:()=>eO,getSlackChannelFile:()=>uu,getSlackInstallation:()=>ru,getSlackManifest:()=>cu,getSlackMode:()=>ou,getSsoProvider:()=>UA,getStaticFileHealthPath:()=>mh,getTask:()=>Uk,getTaskStatus:()=>Bk,getTemplate:()=>Tv,getTicket:()=>Vk,getToolInfo:()=>wT,getToolPrimaryArg:()=>Zs,getTranscriptFilename:()=>Hh,getTurnError:()=>NM,getTurnErrorDetails:()=>GM,getTurnErrorRawText:()=>qM,getTurnStatus:()=>WM,getTurnTokens:()=>KM,getUsageRollup:()=>Zl,getVersionDiff:()=>Ac,getWebPushPublicKey:()=>Nd,getWorkingState:()=>BM,grantAccountSecretResource:()=>fa,grantSandboxProjectAccess:()=>_D,grantSecretToAgent:()=>Ww,groupMessagesIntoTurns:()=>oE,groupShowSegments:()=>vM,groupSteps:()=>um,hasDiffs:()=>JM,hasLocalhostUrls:()=>qC,hasPreviewTarget:()=>dh,hasRetryingAssistantTurn:()=>mE,heartbeatGapEvent:()=>Uy,holdSessionPrompts:()=>il,humanizeReviewActionPath:()=>bp,humanizeSearchQuery:()=>dr,humanizeToolName:()=>Qg,importSsoProviderFromMetadata:()=>LA,inboxObservationSupersedes:()=>uj,initialWakeEscalationState:()=>km,inputPath:()=>Ve,installTemplate:()=>Ev,interruptSessionPrompt:()=>sl,invalidateTokenCache:()=>Wr,inviteAccountMember:()=>Xo,inviteProjectMember:()=>Bi,inviteRepoCollaborator:()=>pi,isAbortError:()=>xr,isAgentPart:()=>cT,isAppRouteUrl:()=>ch,isAttachment:()=>mT,isAttachmentPartRef:()=>oP,isAuthFailure:()=>Ot,isBillingError:()=>Io,isCompactionPart:()=>lT,isConfigured:()=>Mr,isContextTool:()=>oT,isEmptyConversation:()=>RP,isEmptyShowPart:()=>ys,isErrorOutput:()=>fE,isExternalUrl:()=>tI,isFeatureDisabledError:()=>Ro,isFilePart:()=>zg,isInternalLocalhostUrl:()=>QC,isInvisibleActivityPart:()=>Vd,isInviteSent:()=>cx,isLastUserMessage:()=>LM,isLegacyMigratedSession:()=>hP,isManagedGithubProject:()=>JS,isNoGroupActivityTool:()=>Kd,isOfferedModel:()=>xo,isOpenCodeConfigInvalidError:()=>ZO,isPaintableSavedCopy:()=>bf,isPatchPart:()=>pT,isPersistableQueryKey:()=>UD,isPreviewUrl:()=>JC,isProxiableLocalhostUrl:()=>fh,isQuestionTool:()=>rk,isReasoningPart:()=>ke,isRetryableTurnError:()=>Kb,isRuntimeConfigInvalidError:()=>w_,isRuntimeNotReadyResponse:()=>A_,isRuntimeReady:()=>Rg,isRuntimeStartingError:()=>sD,isSandboxNotReadyError:()=>dn,isSelectableAgent:()=>bs,isServerReachable:()=>vg,isSessionAttachmentRef:()=>ck,isSessionFresh:()=>$c,isSessionStartError:()=>Uw,isShellActivityTool:()=>nk,isShellMode:()=>d_,isShortOutput:()=>nO,isShowContentUnavailable:()=>ek,isShowPayloadEmpty:()=>Vn,isSnapshotPart:()=>uT,isStandaloneActivityTool:()=>Hd,isStepPart:()=>dT,isSubdomainPreviewUrl:()=>vr,isTextPart:()=>ve,isToolPart:()=>oe,isToolPartHidden:()=>hT,isTurnErrorCode:()=>cg,isUnderSandboxRoot:()=>xg,isWebProxyUrl:()=>eI,isWireIdAheadOf:()=>Ay,leaveAccount:()=>ci,linkGitHubInstallation:()=>Ti,linkRepository:()=>xi,listAccountAudit:()=>$p,listAccountAuditWebhooks:()=>Bp,listAccountInvites:()=>Zo,listAccountMembers:()=>Qo,listAccountResourceGrants:()=>PA,listAccountSecretResources:()=>ua,listAccountSessions:()=>VA,listAccountTokens:()=>Rp,listAccounts:()=>qo,listActions:()=>RA,listAgentIdentities:()=>Ku,listAllConnections:()=>wa,listAppAgents:()=>id,listAppDeployments:()=>pd,listAppMachines:()=>bd,listAppVolumeSnapshots:()=>Td,listAppVolumes:()=>kd,listApps:()=>Zp,listAssignments:()=>ap,listAuditEvents:()=>sv,listAuditWebhooks:()=>ev,listBackups:()=>AD,listBeeuniProjectSessions:()=>hR,listBeeuniProjects:()=>mR,listBeeuniPty:()=>fg,listBillingTransactions:()=>Ul,listChangeRequests:()=>vc,listChannelBindings:()=>cA,listColumns:()=>tR,listConnectSections:()=>jx,listConnectToolkits:()=>Dx,listConnections:()=>xa,listConnectorAccounts:()=>zr,listConnectorTools:()=>Vr,listConnectors:()=>ja,listCostByProject:()=>Zw,listCredentialEvents:()=>IR,listCredentials:()=>CR,listDiscoverConnectors:()=>Jr,listDiscoverIntegrations:()=>$x,listDiscoverSections:()=>za,listDriveConflicts:()=>Bv,listDriveFiles:()=>Nv,listDriveFolder:()=>zf,listDriveVersions:()=>zv,listEnv:()=>pg,listFeaturedMarketplaces:()=>Hp,listFields:()=>rR,listFiles:()=>tn,listFolderPrincipals:()=>Lv,listGatewayLogs:()=>xu,listGitHubInstallations:()=>vi,listGitHubRepositories:()=>Ri,listGitHubRepositoryBranches:()=>Ci,listGroupMembers:()=>Nu,listGroupProjectGrants:()=>hA,listGroups:()=>$u,listLinkableGitHubInstallations:()=>ki,listMarketplaceCatalogItems:()=>Kp,listMarketplaceSources:()=>Jp,listMarketplaces:()=>Vp,listMemberGroups:()=>bA,listMemberProjectAccess:()=>_A,listMilestoneEvents:()=>xR,listMilestones:()=>PR,listMyAccountInvites:()=>ni,listNotifications:()=>Ud,listOAuthClients:()=>tp,listOAuthGrants:()=>Tp,listPendingApprovals:()=>Ji,listPendingProjectInvites:()=>Fi,listPermissions:()=>up,listPolicies:()=>SA,listProjectAccess:()=>$i,listProjectAccessRequests:()=>Oi,listProjectAgentIdentities:()=>Vu,listProjectAgents:()=>cR,listProjectAudit:()=>Up,listProjectBranches:()=>_c,listProjectCliTokens:()=>Mp,listProjectCommits:()=>Pc,listProjectDirectory:()=>dc,listProjectFiles:()=>pc,listProjectGroupGrants:()=>Gi,listProjectPolicies:()=>ec,listProjectProviderOAuth:()=>ra,listProjectReminders:()=>kp,listProjectResourceGrants:()=>Hi,listProjectSandboxTemplates:()=>nc,listProjectSandboxes:()=>uc,listProjectSecrets:()=>Zi,listProjectSessions:()=>_t,listProjectSessionsPage:()=>Fc,listProjectSnapshots:()=>rc,listProjectTriggerEventApps:()=>vl,listProjectTriggerEventTypes:()=>Al,listProjectTriggers:()=>bl,listProjects:()=>yt,listProjectsForAccount:()=>ui,listPublicMarketplaceItems:()=>M_,listPublicMarketplaces:()=>O_,listReferrals:()=>fA,listReviewItems:()=>pp,listRoles:()=>Wu,listSandboxProjectMembers:()=>bD,listSandboxShares:()=>_p,listSandboxes:()=>dD,listScimTokens:()=>IA,listServiceAccountsApi:()=>JA,listServiceTemplates:()=>$R,listServices:()=>jR,listSessionConnectRequests:()=>Ox,listSessionCosts:()=>nu,listSessionDrives:()=>Qv,listSessionPrompts:()=>tl,listSessionProviderSecretPools:()=>_a,listSessionPublicShares:()=>Vc,listSessionReminders:()=>xp,listSessionsNeedingInput:()=>Qi,listSignedInDevices:()=>kv,listSsoGroupMappings:()=>NA,listTaskEvents:()=>Lk,listTasks:()=>$k,listTemplates:()=>oR,listTicketEvents:()=>Hk,listTickets:()=>Kk,loadHttpSessionHistory:()=>AP,loadPreviewUrlTemplate:()=>nt,looksLikeError:()=>nm,looksLikeHtml:()=>DE,looksLikeJsonPayload:()=>CE,makeDriveFolder:()=>Kv,mapApiReviewItem:()=>xv,markNotificationsRead:()=>Ld,markSessionFresh:()=>$n,maxWireIdClock:()=>ig,memoryRelPath:()=>cO,mergeBurstSteps:()=>dM,mergeChangeRequest:()=>Tc,messageCreatedAt:()=>yM,messageTime:()=>c_,mintWireMessageId:()=>Ds,mintWireMessageIdAbove:()=>ag,mkdir:()=>on,modelInDefaultView:()=>rS,modelRefToKey:()=>FP,moveDriveFile:()=>Vv,narrateFailedStep:()=>lm,narrateStep:()=>cm,narrationToolName:()=>Pr,narrowChatEvent:()=>Ly,newestWireIdClock:()=>vy,nextConnectorPollDelay:()=>DD,normalizeActivityToolName:()=>de,normalizeExternalInput:()=>nI,normalizeName:()=>Z,normalizeToolName:()=>Jg,notifyHostSignal:()=>_P,openChangeRequest:()=>Ic,openEventStream:()=>Ls,paginateConnector:()=>Za,parseBillingError:()=>Sn,parseEmbeddedFailure:()=>EE,parseFlagOverride:()=>yk,parseJsonFailure:()=>Hb,parseLocalhostUrl:()=>ur,parseMemoryView:()=>lO,parseOpenCodeErrorPayload:()=>QO,parsePresentationOutput:()=>dO,parseProxyHop:()=>kg,parseQuestionAnswersFromOutput:()=>gO,parseReadOutput:()=>mO,parseRuntimeErrorPayload:()=>hm,parseScrapeInputUrls:()=>Jb,parseScrapeOutput:()=>Xb,parseSubdomainUrl:()=>Tg,parseTaskRows:()=>sO,parseWebProxyUrl:()=>ZC,parseWebSearchOutput:()=>im,partOutcome:()=>rm,patchBeeuniProject:()=>_R,patchVerb:()=>pO,pickerProviderList:()=>XP,platformConfig:()=>k,pollConnectionOAuth2DeviceAuthorization:()=>Ix,pollProjectProviderOAuth:()=>Gr,previewGatewayRoute:()=>Su,previewMfaRequired:()=>OA,previewSlackIdentity:()=>sA,previewTeamsIdentity:()=>oA,probeEffectivePermission:()=>Zu,probeEffectivePermissions:()=>ep,probePreviewPort:()=>YD,projectArchiveRequest:()=>yc,projectCompacting:()=>hj,projectConfigAgentsToOpenCodeAgents:()=>LP,projectConfigAgentsToRuntimeAgents:()=>Em,projectSessionConnection:()=>ej,projectSessionForRuntimeId:()=>$j,projectSessionStartSeed:()=>$w,projectWorking:()=>dj,provisionProject:()=>yi,provisionProjectStream:()=>ZS,provisionProjectWithToken:()=>ox,proxyLocalhostUrl:()=>Ig,proxyUrlToInternal:()=>YC,purchaseCredits:()=>Jl,putConnectionOAuth2Application:()=>xx,rawErrorText:()=>Lg,reactivateSandbox:()=>hD,reactivateSubscription:()=>Vl,readBeeuniMember:()=>Po,readBlob:()=>rn,readDriveFile:()=>Gv,readFile:()=>nn,readProjectFile:()=>mc,reasoningIsRunning:()=>r_,rebuildProjectSnapshot:()=>sc,reconcileConnection:()=>Aa,reconcileMemberConnection:()=>va,reconcileServices:()=>BR,recordPlatformLogout:()=>L_,recoverLinkResults:()=>oo,refreshReferralCode:()=>dA,refreshSession:()=>Kt,registerAppArtifact:()=>ms,registerConnectionOAuth2Client:()=>kx,registerDeviceToken:()=>jd,registerService:()=>FR,registerWebPushSubscription:()=>qd,rejectProjectAccessRequest:()=>ji,relativizePath:()=>vT,reloadProjectSessionConfig:()=>ul,reloadProjectSessionConfigStream:()=>pl,removeAccountAuditWebhook:()=>qp,removeAccountBrandingAsset:()=>Yo,removeAccountMember:()=>ii,removeBeeuniPty:()=>bg,removeGroupMember:()=>Gu,removeMarketplaceSource:()=>Xp,removeQueued:()=>Gh,renameConnection:()=>Ta,renameFile:()=>cr,renameSandbox:()=>pD,reopenChangeRequest:()=>Mc,reopenMilestone:()=>kR,reorderQueued:()=>Kh,replaceColumns:()=>nR,replaceFields:()=>sR,replaceProjectRepository:()=>wi,replaceTemplates:()=>iR,requestAccountDeletion:()=>Bf,requestChangesOnChangeRequest:()=>Oc,requestProjectAccess:()=>ax,requestProjectConnector:()=>Wp,requestProjectSecret:()=>Gp,requestTopUp:()=>zw,requireBeeuniMember:()=>DP,resendAccountInvite:()=>ti,resendPendingProjectInvite:()=>qi,resetAccountBranding:()=>Jo,resetClient:()=>GR,resetGatewayRoutingPolicy:()=>Pu,resetPassword:()=>vs,resetPublicClient:()=>VR,resolveApproval:()=>Xi,resolveComposerAgent:()=>UP,resolveComposerModel:()=>iS,resolveConnectorStart:()=>OD,resolveModelDefault:()=>oS,resolvePublicShareUrl:()=>Cw,resolveScrapeResults:()=>jE,resolveWorkingTurn:()=>UM,resolvedPlan:()=>Vw,restartAppMachine:()=>xd,restartProjectSession:()=>Fn,restartSandbox:()=>mD,restoreAppVolume:()=>Md,restoreBackup:()=>kD,restoreDriveVersion:()=>Yv,retryAccountSecretResource:()=>ga,retryFailed:()=>qh,retrySessionPrompt:()=>ol,revealCredential:()=>ER,reviewItemTarget:()=>uv,reviewSegmentForStatus:()=>Wf,reviewVerdictForStatus:()=>dv,revokeAccountSecretResourceGrant:()=>ya,revokeAccountSession:()=>HA,revokeAccountToken:()=>Ip,revokeAssignment:()=>lp,revokeConnection:()=>Ra,revokeGatewayKey:()=>Du,revokeOAuthGrant:()=>Ep,revokePendingProjectInvite:()=>Ni,revokeProjectAccess:()=>Li,revokeProjectCliToken:()=>Dp,revokeSandboxProjectAccess:()=>PD,revokeSandboxShare:()=>Sp,revokeScimToken:()=>EA,revokeSessionPublicShare:()=>zc,rewriteLocalhostUrl:()=>ct,rollbackApp:()=>hd,rootRuntimeSession:()=>bP,rotateAccountSecretResource:()=>da,rotateOAuthClientSecret:()=>op,runConnector:()=>es,runGatewayPlayground:()=>ju,runProjectProviderOAuthFlow:()=>dx,runtimeSessionsOf:()=>ho,runtimeSupports:()=>rh,sanitizePtyChunk:()=>Dy,saveGitHubInstallation:()=>Ii,savedCopyEmptyRoot:()=>kP,scaleApp:()=>Ad,scheduleDowngrade:()=>Hl,searchConnectorTools:()=>Sa,searchProjectFiles:()=>gc,segmentTurn:()=>wM,selectableProjectAgents:()=>bk,sendMagicLink:()=>Ss,sendReferralEmails:()=>yA,serverCompactionRevalidateAtMs:()=>_j,serviceAction:()=>LR,sessionConnectionLabel:()=>Mj,sessionListStatus:()=>Ej,sessionModelPin:()=>fl,sessionParentId:()=>vw,sessionPromptActions:()=>Ow,sessionStartKey:()=>Bw,setAccountSecretResourceAccess:()=>ha,setAgentScope:()=>El,setBootstrapAuthToken:()=>fx,setCachedAuthToken:()=>mx,setConnectionPolicies:()=>Mx,setConnectorAuthorizationStrategy:()=>La,setConnectorCredential:()=>Ja,setConnectorCredentialMode:()=>Ua,setConnectorName:()=>Ga,setConnectorPolicies:()=>Na,setConnectorSecretBinding:()=>Lx,setConnectorSensitive:()=>Ba,setDefaultConnection:()=>Ia,setEnterpriseDemo:()=>iv,setEnv:()=>dg,setGatewayBudget:()=>Tu,setGatewayRoutingPolicy:()=>_u,setMemberSuperAdmin:()=>CA,setMfaRequired:()=>DA,setModelDefault:()=>Il,setPersonalProjectSecret:()=>aa,setProjectModelAccess:()=>Kn,setProjectModelEnablement:()=>Fw,setProjectOnboardingComplete:()=>Pi,setProjectOnboardingProfile:()=>rx,setProjectPolicies:()=>tc,setProjectSecretStrategy:()=>ta,setProjectSessionModel:()=>ml,setProjectSessionScope:()=>gl,setProjectSessionSharing:()=>Nc,setProjectTriggersActivation:()=>xl,setSavedCopyStore:()=>ww,setSessionOversight:()=>$A,setSessionProviderSecretPool:()=>Pa,setSessionWatch:()=>Wc,settleSessionConnection:()=>sj,setupSSH:()=>CD,shareConnection:()=>Ma,shareFolder:()=>$v,shellActivityGroupLabel:()=>sk,shellExitCode:()=>fm,shouldHideResponsePart:()=>FM,shouldShowToolPart:()=>Ob,shouldSuppressWorkingTurnBusy:()=>TM,showGroupItems:()=>CM,showTurnBusyIndicator:()=>pm,signInWithPassword:()=>Ps,signInWithProvider:()=>ws,signInWithSso:()=>Is,signOut:()=>Es,signOutDevice:()=>Rv,signUp:()=>_s,skillDocumentPath:()=>SO,skillInputDir:()=>bO,sortSessions:()=>gE,splitTurnWork:()=>XM,splitUserParts:()=>fT,startApp:()=>md,startAppMachine:()=>Pd,startConnectionOAuth2Authorization:()=>Rx,startConnectionOAuth2DeviceAuthorization:()=>Cx,startConnectorSetupLink:()=>q_,startProjectProviderOAuth:()=>qr,startProjectSession:()=>Xe,startProjectSessionOrThrow:()=>Rl,startSessionWithToken:()=>H_,startTask:()=>qk,stepLabel:()=>sm,stopApp:()=>fd,stopAppMachine:()=>Sd,stopProjectSession:()=>Nn,stopSandbox:()=>fD,storeGitHubUserToken:()=>Ei,stripAnsi:()=>TT,stripTrailingSlashes:()=>ce,submitAccessRequest:()=>U_,submitDemoRequest:()=>z_,submitOAuthConsent:()=>F_,submitReviewItem:()=>gp,submitSecretSetupLink:()=>K_,syncConnectors:()=>$a,syncSubscription:()=>Xw,systemReload:()=>zR,toDaemonPath:()=>at,toInternalUrl:()=>yh,toSandboxAbsolutePath:()=>en,toToolView:()=>qT,toWorkspaceRelative:()=>wg,toolCallBlock:()=>mb,toolCallMetadata:()=>fb,toolInfo:()=>eo,toolKind:()=>le,toolViewModel:()=>P_,triggersRequest:()=>Ey,turnEndCause:()=>fP,turnEndNotice:()=>fj,turnHasSteps:()=>uE,turnIsConfirmedActive:()=>OM,turnRendersQueued:()=>DM,turnRetryLabel:()=>Dj,unassignTicket:()=>Xk,unregisterDeviceToken:()=>$d,unregisterWebPushSubscription:()=>Gd,unshareFolder:()=>Uv,unwrapError:()=>he,updateAccountAuditWebhook:()=>Np,updateAccountBranding:()=>Ho,updateAccountMemberRole:()=>ai,updateAccountName:()=>Ko,updateAgentConfig:()=>Gw,updateApp:()=>td,updateAppAccess:()=>ad,updateAppVolume:()=>Cd,updateAuditWebhook:()=>nv,updateBeeuniPty:()=>hg,updateChangeRequest:()=>jc,updateChannelBinding:()=>lA,updateConnectionCredential:()=>ka,updateEmailPolicy:()=>hu,updateExperimentalFeature:()=>bi,updateFeatureFlag:()=>hi,updateGroup:()=>Bu,updateMilestone:()=>AR,updateNotificationPreferences:()=>Fd,updateOAuthClient:()=>sp,updatePassword:()=>ks,updatePatPolicy:()=>YA,updatePolicy:()=>wA,updateProject:()=>Cn,updateProjectAccess:()=>Ui,updateProjectAgent:()=>uR,updateProjectDefaultAgent:()=>Ol,updateProjectGroupGrant:()=>Ki,updateProjectSandboxProvider:()=>_i,updateProjectSession:()=>al,updateProjectTrigger:()=>Pl,updateRole:()=>Ju,updateRolePermissions:()=>Qu,updateSandboxTemplate:()=>ac,updateSessionPolicy:()=>KA,updateSessionReminder:()=>ps,updateSessionReminders:()=>Ap,updateTask:()=>Nk,updateTemplateWarmPool:()=>nx,updateTicket:()=>Yk,updateTicketStatus:()=>Jk,updateUserMetadata:()=>Cs,uploadAccountBrandingAsset:()=>zo,uploadAppArtifactArchive:()=>ld,uploadConnectorAttachment:()=>Yr,uploadDriveFile:()=>Wv,uploadFile:()=>sn,uploadNativeFile:()=>zy,uploadPromptAttachment:()=>jn,uploadSessionAttachment:()=>Qd,uploadSlackChannelFile:()=>pu,uploadTimeoutMsForBytes:()=>Qt,upsertCredential:()=>TR,upsertProjectGitCredential:()=>oa,upsertProjectSecret:()=>ea,validateProjectManifest:()=>di,validateReferralCode:()=>gA,validateToken:()=>li,verifyBeeuniToken:()=>$P,verifyGatewayProvider:()=>uA,verifyOtp:()=>xs,verifySsoDomain:()=>BA,wakeEscalationAttemptSummary:()=>Ij,wakeEscalationNote:()=>Rj,wakeProgressFingerprint:()=>wj,wireIdClock:()=>vt,wireIdClockAt:()=>zt,wireIdClockDelta:()=>kt,workedForLabel:()=>ZM,workingExpiryAtMs:()=>gj,workingTurnDrawsBusyRow:()=>jM,writeActivityGroupLabel:()=>ok,writeFile:()=>ar,wsDomain:()=>ao,wsFavicon:()=>OE,wsRootDomain:()=>ME});var mS={backendUrl:"",getToken:async()=>null},vo=null,Tr=null;function fS(e){Tr=e}function yS(){return Tr}function Er(e,t){t?.global!==!1&&(vo=e)}function k(){return Tr?.()??vo??mS}function Mr(){return vo!==null||Tr?.()!==void 0}function hS(e){return new Promise(t=>setTimeout(t,e))}async function Or(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 hS(s)),i=await e(),i)return i;return i}var ko=12e4;function bS(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Nm(e,t,n=ko){let r=e instanceof Request?e.signal:t?.signal;if(bS(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function Dr(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var _=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)}},ne=class extends _{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},ze=class extends _{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},mt=class extends _{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"}},_S="ENDPOINT_RETIRED";function G(e,t){let n=t?` ${t}`:"";return new _(`${e}() is retired: the Beeuni API no longer serves this endpoint.${n}`,{code:_S})}var jr="feature_disabled";function qm(e){if(!(e instanceof _)||e.status!==403||e.code!==jr)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Ro(e){let t=qm(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function Co(e){let t=qm(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function Sn(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 ze(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 Io(e){return e instanceof ze}function Ot(e){if(e instanceof ne)return!0;let t=e?.status;return t===401||t===403}function To(e){if(!(e instanceof ze))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 _e(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function Pe(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(_e())};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(_e())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var Gm="request_deadline",PS=/^Request exceeded the \d+s server processing deadline$/,Wm=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Gm||PS.test(n),SS="git_mirror_unavailable",xS=/^git mirror is temporarily unavailable$/,wS=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===SS||xS.test(n);async function AS(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await Pe(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 _e();return{message:n,data:r}}function vS(e,t,n){return Wm(e,t,n)||wS(e,t,n)||e===501&&t?.code===Eo||e===409&&(t?.code===Mo||t?.code===Oo)||e===503&&(t?.code===Do||t?.code===jo)}async function Km(e,t,n,r){let{message:s,data:o}=await AS(e,t),i=new _(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Wm(e.status,o,s)?Gm:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=Sn(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 mt(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&&!vS(e.status,o,s)&&k().onError?.(i,r),{error:i,success:!1}}var kS="X-Beeuni-Impersonate",Vm="beeuni.impersonation",Dt=null,$o=!1,RS=new Set;function Hm(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function CS(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 IS(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 TS(){for(let e of RS)try{e()}catch{}}function ES(){return $o||($o=!0,Dt=IS(Hm()?.getItem(Vm)??null)),Dt&&!CS(Dt)?(MS(),null):Dt}function MS(){$o=!0;let e=Dt!==null;Dt=null;try{Hm()?.removeItem(Vm)}catch{}e&&TS()}var OS=/(^|\/)admin\/(api|analytics)(\/|$)/;function DS(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!OS.test(t)}function zm(e){if(e!==void 0&&!DS(e))return{};let t=ES();return t?{[kS]:t.grantId}:{}}var jS=!1;function $S(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function Lo(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function xn(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function Ur(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap($S))xn(n,s,o);return n}function Bo(e,t,n){let r={...t},s=k().clientVersion?.trim();s&&!Lo(r,"x-beeuni-client-version")&&xn(r,"X-Beeuni-Client-Version",s),jS&&xn(r,"x-beeuni-admin-bypass","1");for(let[o,i]of Object.entries(zm(e)))xn(r,o,i);return Lo(r,"authorization")||xn(r,"Authorization",`Bearer ${n}`),r}async function Br(e,t){let n=await Lr();if(!n)throw new ne;return{headers:new Headers(Bo(e,Ur(e,{headers:t}),n)),rejected:()=>wn(n)}}function US(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function Ym(e,t,n,r,s){if(t instanceof Request){let c=new Headers(Bo(t.url,Ur(t,n),r));return e(new Request(t,{headers:c,...s?{signal:s}:{}}))}let o=String(t),i=Bo(o,Ur(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var Jm=null;async function Fo(e){let t=await Or(()=>k().getToken(),e);return t&&(Jm=t),t}var Lr=Fo;function wn(e=Jm){e&&k().getToken.invalidate?.(e)}var Uo=new Map;function LS(e){let t=Uo.get(e);if(t)return t;let n=(async()=>(wn(e),Lr({attempts:2,baseDelayMs:200})))().finally(()=>Uo.delete(e));return Uo.set(e,n),n}async function ft(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=ko}=n,o=n.fetch??k().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:Nm(e,t,s);if(i?.aborted)throw _e();let a=await(i?Pe(Lr(),i):Lr());if(!a)throw new ne;let c=r&&!US(t)&&!Lo(Ur(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await Ym(o,e,t,a,i);if(d.status!==401||!c)return d;let g=await LS(a);return!g||g===a?d:Ym(o,p,t,g,i)}async function Me(e,t,n,r){let s=await ft(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new _(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var Qm=()=>k().backendUrl||"",BS=new Set([502,503,504]),FS=e=>BS.has(e),Xm=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},NS=e=>Xm(e)||(e??"GET").toUpperCase()==="DELETE",qS=2,Fr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function Oe(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 GS(e,i,n,r,s,o,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function GS(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw _e();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 KS(e,t,c,s,o,i,a);if(p instanceof ne)return{error:p,success:!1};if(!p.ok)return await Km(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await Pe(p.json(),a.activeController.signal):g?.includes("text/")?d=await Pe(p.text(),a.activeController.signal):d=await Pe(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return VS(c,e,t.method,n,r,s,a)}finally{Nr(a)}}function Nr(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function WS(e,t,n){try{await Pe(e.arrayBuffer(),t)}catch(r){if(Fr(r))throw r}finally{Nr(n)}}async function KS(e,t,n,r,s,o,i){let a=Xm(t.method),c=NS(t.method),p=c?qS+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 Pe(ft(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(y){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),y instanceof ne)return new ne;if(i.didTimeout&&Fr(y)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(Fr(y)||g===p-1)throw y;continue}if(!a||!FS(d.status)||g===p-1)return s||Nr(i),d;await WS(d,m.signal,i)}return d}function VS(e,t,n,r,s,o,i){Nr(i);let a=Fr(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new _("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(Qm(),"")||t;c=new _(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(c=new _(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(Qm(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&k().onError?.(c,s)):(c=new _(String(e)),r&&k().onError?.(c,s));return{error:c,success:!1}}var De=()=>k().backendUrl||"",Eo="feature_not_supported",Mo="model_not_servable",Oo="provision_in_flight",Do="analytics_unavailable",jo="accounts_list_unavailable";async function HS(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await ft(`${De()}${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 ne)return Dr();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>Oe(`${De()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>Oe(`${De()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>Oe(`${De()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>Oe(`${De()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>Oe(`${De()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>Oe(`${De()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Oe(`${De()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Oe(`${De()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:HS};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function No(e){return e.replace(/\/v1\/?$/,"")}async function jt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=No(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 qo(){return u(await l.get("/accounts"))}async function Go(e){return u(await l.post("/accounts",e))}async function Wo(e){return u(await l.get(`/accounts/${e}`))}async function Ko(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function Vo(e){return u(await l.get(`/accounts/${e}/branding`))}async function Ho(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function zo(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 Yo(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function Jo(e){return u(await l.delete(`/accounts/${e}/branding`))}async function Qo(e){return u(await l.get(`/accounts/${e}/members`))}async function Xo(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Zo(e){return u(await l.get(`/accounts/${e}/invites`))}async function ei(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function ti(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 ri(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function si(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}async function oi(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function ii(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function ai(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function ci(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function zS(e){return jt(e,"/v1/accounts")}async function li(){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 YS=["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","volumes","stateless_sessions","drives","ephemeral_sandboxes","session_log"];async function yt(){return u(await l.get("/projects"))}async function ui(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function An(e,t){return u(await l.get(`/projects/${e}`,t))}async function pi(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function di(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function gi(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function JS(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function vn(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 kn(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Rn(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function QS(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function mi(e){return u(await l.post("/projects",e))}async function fi(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function yi(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Zm=200;function XS(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>Zm?`${n.slice(0,Zm)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function ZS(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 _(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=XS(g);if(m){if(t(m),m.type==="error")throw new _(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 ex(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Cn(e,t){return u(await l.patch(`/projects/${e}`,t))}async function hi(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function bi(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function _i(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function tx(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function nx(e,t){throw G("updateTemplateWarmPool")}async function Pi(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function rx(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function In(e){return u(await l.delete(`/projects/${e}`))}async function sx(e,t){return jt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function ox(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=No(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 Si(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function xi(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function wi(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Ai(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function vi(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ki(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Ri(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 Ci(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 Ii(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function Ti(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Ei(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function Mi(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 ix(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function ax(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Oi(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function Di(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function ji(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function $i(e){return u(await l.get(`/projects/${e}/access`))}async function Ui(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function Li(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function cx(e){return"status"in e&&e.status==="invited"}async function Bi(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 Fi(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function Ni(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function qi(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Gi(e){return u(await l.get(`/projects/${e}/group-grants`))}async function Wi(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 Ki(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 Vi(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function Hi(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function zi(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 Yi(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function Ji(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Qi(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Xi(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 Zi(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function ea(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function ta(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 ra(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function qr(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 Gr(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function sa(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var lx=2e3,ux=3e3,px=10*6e4;async function dx(e){let{projectId:t,provider:n,input:r,onChallenge:s,isCancelled:o,sleep:i=m=>new Promise(y=>setTimeout(y,m)),now:a=()=>Date.now()}=e,c=()=>o?.()??!1,p=await qr(t,n,r);if(c())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(lx,p.interval_ms||ux),g=p.expires_at||a()+px;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await Gr(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 oa(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function ia(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function aa(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function ca(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var la=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,$t=(e,t)=>`${la(e)}/${encodeURIComponent(t)}`,ef=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function ua(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${la(e)}${n}`))}async function pa(e,t){return u(await l.post(la(e),t))}async function da(e,t,n){return u(await l.put(`${$t(e,t)}/value`,{value:n}))}async function ga(e,t){return u(await l.post(`${$t(e,t)}/retry`))}async function ma(e,t){return u(await l.delete($t(e,t)))}async function fa(e,t,n,r){return u(await l.put(`${$t(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function ya(e,t,n,r){return u(await l.delete(`${$t(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function ha(e,t,n,r){return u(await l.put(`${$t(e,t)}/access`,{mode:n,user_ids:r}))}async function ba(e,t,n){return u(await l.get(ef(e,t,n)))}async function _a(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function Pa(e,t,n,r){return u(await l.put(ef(e,t,n),{secret_ids:r}))}async function Ye(){return Fo()}async function gx(e){return Or(()=>k().getToken(),e,Wr)}function Wr(){wn()}function mx(e){e===null&&wn()}function fx(e){}async function j(e,t,n){try{return await ft(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof ne)return Dr();throw r}}function Kr(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Ut(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(`${Kr(e,"catalog")}${r}`)).connectors??[]}async function Vr(e){let t=[];for(let n of await Ut(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 Sa(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await Vr(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 Hr(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 Ut(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 yx(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 hx=9e4;async function ht(e,t,n={},r={}){let{connector:s,action:o}=yx(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(Kr(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??hx,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function zr(e,t){let n=await l.get(Kr(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function bx(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 _x(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 Yr(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=_x(k().backendUrl),a=Kr(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 _(bx(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 Px(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 xa(e){return u(await l.get(`/projects/${e}/connections`))}async function wa(e){return u(await l.get(`/projects/${e}/connections/all`))}async function Aa(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function va(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function ka(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function je(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function Sx(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function xx(e,t,n){return u(await l.put(je(e,t,"application"),n))}async function wx(e,t){return u(await l.get(je(e,t,"application")))}async function Ax(e,t,n){return u(await l.post(je(e,t,"discover"),n))}async function vx(e,t,n={}){return u(await l.post(je(e,t,"discover-resource"),n))}async function kx(e,t,n){return u(await l.post(je(e,t,"register"),n))}async function Rx(e,t,n){return u(await l.post(je(e,t,"authorize"),n))}async function Cx(e,t,n){return u(await l.post(je(e,t,"device"),n))}async function Ix(e,t,n){return u(await l.post(je(e,t,`device/${encodeURIComponent(n)}`),{}))}async function Tx(e,t){return u(await l.get(je(e,t,"status")))}async function Ra(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Ca(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Ia(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function Ta(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Ea(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Ma(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Oa(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function Da(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function ja(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 $a(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Ua(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function La(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Ba(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Fa(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Na(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function Ex(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function Mx(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function qa(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Ga(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Wa(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 Ox(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Ka(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function Va(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function Ha(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Dx(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 jx(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 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 u(await l.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function za(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 Qr(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var $x=Jr,Ux=Qr;async function Ya(){return u(await l.get("/connectors/connect-status"))}async function Ja(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 Qa(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function Lx(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Xa(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 Tn=class extends _{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,...y}=n;super(t,{...y,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}},Xr=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)}},Zr=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)}},Se=e=>typeof e=="string"&&e?e:null;function tf(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function Bx(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function Fx(e,t,n){if(!(e instanceof _)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Se(r.reason)??Se(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 Tn(Se(r.message)??Se(r.hint)??s,{status:e.status,code:i===null?tf(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Se(r.connector)??t,action:Se(r.action)??n,binding:Se(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:Bx(e.response),connectUrl:Se(r.connect_url),hint:Se(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Se(r.requested_account)})}function Nx(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 es(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 ht(e,`${o}.${i}`,r,s)}catch(c){throw Fx(c,o,i)}if(a.status==="pending_approval")throw new Xr(o,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new Tn(c,{status:200,code:a.upstream_error?"upstream_error":tf(c),details:a,data:a,reason:c,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return Nx(a)}async function*Za(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 Zr(t,n,i,c);let d=await es(e,t,n,c,a);yield d,c=o(d,c)}}async function ec(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function tc(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 rc(e){return u(await l.get(`/projects/${e}/snapshots`))}async function En(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function sc(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function oc(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function ic(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function ac(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function cc(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function lc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function uc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Mn(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 Br(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function pc(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 dc(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"),u(await l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function gc(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 mc(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 qx=10*6e4;async function fc(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 Me(o,{method:"GET"},{timeoutMs:qx},"Failed to download")).blob()}async function yc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Mn(`${k().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function Gx(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 Me(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var hc=52428800,Wx=104857600,nf=20;var ns=e=>`/projects/${encodeURIComponent(e)}/attachments`,rs={showErrors:!1,deadlineCoversBody:!0},rf=3e4,Kx=12e4,Vx=6e4,Hx=5*6e4,zx=6e4,Yx=6e4;function ts(){return new _("Request aborted",{name:"AbortError",code:"ABORTED"})}function On(e){if(e?.aborted)throw ts()}function Jx(e){return!(e instanceof _)||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 Dn(e,t,n=!1){let r;for(let s=0;;s++){On(t);try{return await e()}catch(o){let i=n&&o instanceof _&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(Jx(o)||i))throw o;r??=Date.now()+(n?Hx:Vx);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 On(t),o}}}}function Qx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function bc(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"&&Qx(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 sf(e,t,n,r){return u(await l.post(ns(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...rs,signal:n,timeout:rf}),"Failed to start attachment upload")}async function of(e,t,n,r){let s=bc({...await Dn(()=>sf(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function af(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 _(r,{status:e,details:n,code:String(n?.statusCode??e)})}function Xx(e){if(!(e instanceof _))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function Zx(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,c=!1,p,d=y=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),y?o(y):s())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new _("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},zx)},m=()=>{d(ts()),i.abort()};i.open(t.method,t.url);for(let[y,h]of Object.entries(t.headers))i.setRequestHeader(y,h);i.upload.onprogress=y=>{g(),a=Math.min(y.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(af(i.status,i.responseText))},i.onerror=()=>d(new _("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(ts()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function ew(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"?ts():new _(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw af(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function tw(e,t,n){On(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?Zx(r,e,t,n):ew(e,t,n)}async function nw(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 Dn(()=>tw(i,t,r),r.signal)}catch(a){let c=Xx(a);if(c!==409){if(o||!(c===400||c===401||c===403))throw a;o=!0,s=await of(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return cf(e,t,s,r)}async function cf(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${ns(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){On(r.signal);let a=i.received_bytes,c=Math.min(a+s,t.size),p=t.slice(a,c),d=await Dn(async()=>u(await l.putRaw(`${o}/chunks/${a/s}`,p,{...rs,signal:r.signal,timeout:rf}),"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 jn(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");On(n.signal);let r=n.resume?bc({...n.resume},t):bc({...await Dn(()=>sf(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()<Yx&&(r=await of(e,t,r,n)),r=r.upload.kind==="direct"?await nw(e,t,r,n):await cf(e,t,r,n)),n.onProcessing?.();let s=`${ns(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Dn(async()=>u(await l.post(`${s}/complete`,{},{...rs,signal:n.signal,timeout:Kx}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof _&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Lt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${ns(e)}/${encodeURIComponent(t)}`,{...rs,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function _c(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 Pc(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 Sc(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function xc(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 wc(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 Ac(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 vc(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 u(await l.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function kc(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function Rc(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function Cc(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function Ic(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function Tc(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Ec(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Mc(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Oc(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Dc(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function jc(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var Bt=new Set,rw=500;function $n(e){e&&(Bt.add(e),Bt.size>rw&&Bt.delete(Bt.values().next().value))}function $c(e){return!!e&&Bt.has(e)}function sw(e){e&&Bt.delete(e)}var $e="beeuni.session/2",Ft=1,lf=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),z=e=>typeof e=="string",xe=e=>z(e)&&e.length>0,Le=e=>e===null||z(e),J=(e,t)=>e===void 0||t(e),Ue=(...e)=>t=>e.includes(t),Un=e=>Number.isInteger(e)&&e>=0,Nt=e=>typeof e=="number",df=e=>e.schema===$e&&Un(e.v),bt=e=>J(e,z),Uc=e=>e===void 0||re(e)&&Object.values(e).every(t=>re(t)&&z(t.version)),gf=e=>e===null||re(e)&&z(e.provider)&&z(e.model)&&bt(e.variant),ow=e=>e===null||re(e)&&Nt(e.input)&&Nt(e.output)&&Nt(e.cache_read)&&Nt(e.cache_write)&&J(e.reasoning,Nt)&&J(e.cost,Nt),uf=e=>re(e)&&(e.type==="text"&&z(e.text)||e.type==="attachment"&&z(e.mime)),iw=e=>re(e)&&Array.isArray(e.content)&&e.content.every(uf)&&J(e.model_content,t=>Array.isArray(t)&&t.every(uf))&&typeof e.is_error=="boolean",pf={text:e=>z(e.text)&&J(e.bytes,Un)&&bt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>z(e.text),attachment:e=>z(e.mime)&&bt(e.ref)&&J(e.bytes,Un)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>z(e.call_id)&&z(e.name)&&xe(e.kind)&&Ue("pending","running","complete","error")(e.status)&&J(e.result,iw),compaction:e=>Le(e.summary)&&Le(e.first_kept_message_id),subtask:e=>z(e.thread_id)&&z(e.agent)&&z(e.description),step:e=>Ue("start","finish")(e.phase),harness:e=>xe(e.harness)&&xe(e.kind)&&typeof e.model_visible=="boolean"};function aw(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!re(r)||!xe(r.id)||n.has(r.id)||!Object.hasOwn(pf,r.type)||!pf[r.type](r)||!Uc(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function cw(e){return re(e)&&df(e)&&xe(e.message_id)&&xe(e.thread_id)&&Number.isInteger(e.seq)&&Ue("user","assistant","system")(e.role)&&Ue("turn","compaction","context")(e.kind)&&Ue("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&J(e.hidden_reason,Ue("failed_attempt","aborted","retracted","reverted","superseded"))&&J(e.origin,Ue("prompt","steer","command","automation","subagent","notification"))&&J(e.agent,Le)&&J(e.reply_to,Le)&&J(e.parent_message_id,Le)&&bt(e.native_agent_id)&&bt(e.context_ref)&&gf(e.model)&&ow(e.usage)&&Ue("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||re(e.error)&&xe(e.error.code)&&z(e.error.message))&&z(e.created_at)&&Le(e.completed_at)&&re(e.producer)&&xe(e.producer.harness)&&z(e.producer.harness_version)&&z(e.producer.adapter_version)&&Uc(e.ext)&&aw(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function lw(e){return re(e)&&df(e)&&xe(e.thread_id)&&Le(e.parent_thread_id)&&(e.spawned_by===null||re(e.spawned_by))&&z(e.created_at)}function uw(e){return re(e)&&J(e.schema,t=>t===$e)&&J(e.v,Un)&&bt(e.session_id)&&J(e.title,Le)&&bt(e.created_at)&&J(e.restore_grade,Ue("native","converted","partial"))&&J(e.todos,Array.isArray)&&J(e.pending,t=>re(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&J(e.selection,t=>re(t)&&J(t.agent,Le)&&gf(t.model??null))&&J(e.harness,t=>re(t)&&z(t.current)&&Array.isArray(t.history))&&Uc(e.ext)}function mf(e){return re(e)&&Un(e.generation)&&typeof e.has_more=="boolean"&&uw(e.session)&&Array.isArray(e.threads)&&e.threads.every(lw)&&(e.thread_id===null||xe(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>cw(t)&&t.thread_id===e.thread_id)}var pw=e=>mf(e)&&e.messages.length>0;function dw(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 ff={paintable:pw,fit:dw,capturedAt:()=>0},gw=new WeakMap;function yf(e,t,n){gw.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 bf(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 ss=1,mw=12,fw=15e5,yw=3e5,hw=336*60*60*1e3,_f="beeuni.saved-copy";function Lc(e){return!!e&&typeof e.then=="function"}function bw(e,t){return Lc(e)?e.then(t):t(e)}function _w(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 Pw(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var Sw={paintable:bf,fit:_w,capturedAt:Pw};function xw(e){let t=hf(e,Sw),n=hf({...e,namespace:`${e.namespace??_f}.log`},ff),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 yf(r,n,t.remove),r}function hf(e,t){let{storage:n,userId:r,maxSessions:s=mw,maxBytes:o=fw,maxEnvelopeBytes:i=yw,maxAgeMs:a=hw,namespace:c=_f,now:p=()=>Date.now()}=e,d=`${c}:${r}:`,g=`${d}index`,m=(P,x)=>`${d}${P}/${x}`,y=P=>{try{let x=n.getItem(P);return Lc(x)?x.catch(()=>null):x}catch{return null}},h=P=>{try{let x=n.removeItem(P);Lc(x)&&x.catch(()=>{})}catch{}},w=async P=>{try{await n.removeItem(P)}catch{}},M=P=>{if(!P)return[];try{let x=JSON.parse(P);return x?.v===ss&&Array.isArray(x.entries)?x.entries:[]}catch{return[]}},B=Promise.resolve(),F=P=>{let x=B.then(P,P);return B=x.catch(()=>{}),x},f=async P=>{try{await n.setItem(g,JSON.stringify({v:ss,entries:P}))}catch{}},b=async()=>M(await y(g)),S=async(P,x)=>{let v=[...P].sort(($,D)=>$.u-D.u),R=v.reduce(($,D)=>$+D.b,0);for(;v.length>s||R>o;){let $=v.findIndex(E=>E.s!==x);if($===-1)break;let[D]=v.splice($,1);R-=D.b,await w(`${d}${D.s}`)}return v},O=P=>{F(async()=>{let x=await b(),v=x.find(R=>R.s===P);v&&(v.u=p(),await f(x))})},C=P=>F(async()=>{await w(`${d}${P}`);let x=await b(),v=x.filter(R=>R.s!==P);v.length!==x.length&&await f(v)});return{keyFor:m,read(P,x){let v=`${P}/${x}`;return bw(y(m(P,x)),R=>{if(!R)return null;let $;try{$=JSON.parse(R)}catch{return h(m(P,x)),C(v),null}return!$||$.v!==ss||$.user!==r||p()-$.at>a||!t.paintable($.e)?(h(m(P,x)),C(v),null):(O(v),$.e)})},write(P,x,v){let R=`${P}/${x}`;if(!t.paintable(v))return C(R);let $={v:ss,user:r,at:p(),e:v},D=t.fit($,i);if(D===null)return C(R);let E=t.capturedAt(v);return F(async()=>{let q=await b(),Q=q.find(Ie=>Ie.s===R);if(Q&&E>0&&Q.c>E)return;let V=q.filter(Ie=>Ie.s!==R),_n={s:R,b:D.length,u:p(),c:E},Ce=await S([...V,_n],R),Pn=m(P,x);try{await n.setItem(Pn,D)}catch{let Ie=Ce.filter(ee=>ee.s!==R).sort((ee,pt)=>ee.u-pt.u)[0];Ie&&(await w(`${d}${Ie.s}`),Ce=Ce.filter(ee=>ee.s!==Ie.s));try{await n.setItem(Pn,D)}catch{await w(Pn),Ce=Ce.filter(ee=>ee.s!==R)}}await f(Ce)})},remove(P,x){return C(`${P}/${x}`)},clear(){return F(async()=>{let P=await b();for(let x of P)await w(`${d}${x.s}`);await w(g)})}}}var Pf=null;function ww(e){Pf=e}function Bc(){return Pf}var Aw=new Set;function Sf(e){for(let t of Aw)try{t(e)}catch{}}function vw(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 kw=50,xf=200,Rw=xf;function wf(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 Fc(e,t){let n=await l.get(`/projects/${e}/sessions${wf(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function _t(e,t){return u(await l.get(`/projects/${e}/sessions${wf(t)}`))}async function Nc(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function qc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Gc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Wc(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}function Cw(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 Iw(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 Kc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function Vc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Hc(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function zc(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Pt(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||$n(n?.session_id),n}async function Yc(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||$n(r.session.session_id),r}async function Jc(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return $n(n.session_id),n}async function Ln(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Qc(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 Xc(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 Zc(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 el(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/turn`))}async function Tw(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 Ew(e){if(e)return e==="interrupt"?"transcript":"composer"}async function Bn(e,t,n){let r=n.placement??Ew(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 tl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function nl(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function rl(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function sl(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function ol(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function il(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function al(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function cl(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return Bc()?.remove(e,t),n}async function Fn(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,n.reset_machine?{reset_machine:!0,...n.discard_state?{discard_state:!0}:{}}:{}))}async function Nn(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return Sf(t),n}async function ll(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function Mw(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 ul(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function pl(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 _(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 y=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=Mw(y);if(h){if(r(h),h.type==="error")throw new _(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 dl(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function gl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function ml(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function fl(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function yl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function hl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function Ow(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 bl(e){return u(await l.get(`/projects/${e}/triggers`))}async function _l(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function Pl(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function Sl(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function xl(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function wl(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}async function Al(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 vl(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var Je=new Map;function kl(e,t){return`${e}::${t}`}function Af(e,t){Je.delete(e),Je.set(e,t)}function vf(e,t){let n=kl(e,t),r=Je.get(n);return r&&Af(n,r),r}function kf(e,t,n){let r=kl(e,t);if(!Je.has(r)&&Je.size>=512){let s=Je.keys().next().value;s!==void 0&&Je.delete(s)}Af(r,n)}function Rf(e,t){Je.delete(kl(e,t))}function Dw(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function qn(){return Dw(k().backendUrl||"http://localhost:8008/v1")}function Cf(){let e=k().sandboxId;return e?`${qn()}/p/${e}/8000`:""}function jw(e,t=8e3){return`${qn()}/p/${e}/${t}`}function Qe(e,t=8e3){return jw(e,t)}function $w(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 os=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 Uw(e){return e instanceof Error&&e.name==="SessionStartError"}function Lw(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 os(s,{status:n,code:r,terminal:!0}):null}function If(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 Xe(e,t,n){let r=await If(e,t,n);if(!r.success||!r.data){let s=Lw(r.error);if(s&&!(s.status===404&&$c(t)))throw s;return null}return Tf(e,t,r.data)}async function Rl(e,t,n){let r=await If(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return Tf(e,t,r.data)}function Tf(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&kf(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Qe(r),sandboxId:r}),n}function Bw(e,t){return["session-start",e,t]}async function Cl(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function Il(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function Tl(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 Fw(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Ef(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Nw(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?Ef(e.connectors_required):void 0,n=e.connectors_personal?Ef(e.connectors_personal):void 0;if(t&&n&&!Nw(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 El(e,t,n){let r=is(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function qw(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Ml(n.block):null}}async function Gw(e,t,n){let r=Ml(n,!0),s=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Ml(s.block):null}}function Ml(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 Ww(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Ol(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var Mf="Use createPerSeatCheckout().";function Dl(){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 Kw(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function Vw(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??Dl(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:Kw(r),label:s,sublabel:null,isGrandfathered:!1}}async function Of(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?Dl():t.data}function Df(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 jl(e){return Of(`/billing/account-state${Df(e)}`)}async function $l(e){return Of(`/billing/account-state/minimal${Df(e)}`)}async function Ul(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 Ll(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 Bl(){return u(await l.get("/billing/credit-breakdown"))}async function Fl(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function Nl(){return u(await l.get("/billing/tier-configurations"))}async function Hw(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return jt(e,`/v1/billing/account-state${t}`)}async function ql(e){throw G("createCheckoutSession",Mf)}async function Gl(e,t){throw G("confirmCheckoutSession",Mf)}async function Wl(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Kl(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Vl(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Hl(e,t,n){throw G("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function zl(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function Yl(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 Jl(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 Ql(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 zw(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Xl(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 Yw(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 Jw(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 Qw(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function Xw(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function Zl(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 tu(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function as(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function cs(e){return e.size>0?`?${e}`:""}async function nu(e={}){let t=new URLSearchParams;return tu(t,e),e.ownerId&&t.set("owner_id",e.ownerId),as(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${cs(t)}`))}async function Gn(e,t={}){let n=new URLSearchParams;return tu(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${cs(n)}`))}async function Zw(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),as(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${cs(t)}`))}async function eA(e={}){let t=new URLSearchParams;return tu(t,e),e.sessionId&&t.set("session_id",e.sessionId),as(t,e),u(await l.get(`/usage/cost-summary${cs(t)}`))}function eu(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)}as(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 tA(e,t={}){let n=eu(e==="projects"?"projects":"sessions",t),r=await Me(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 jf(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function nA(e){return jf("slack",e)}function rA(e){return jf("teams",e)}async function $f(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function sA(e){return $f("slack",e)}function oA(e){return $f("teams",e)}async function ru(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function su(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var iA={oauth_available:!1,install_url:null};async function ou(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?iA:t.data}async function Uf(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 iu(e,t){return Uf("slack",e,t)}function au(e,t){return Uf("teams",e,t)}async function cu(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function lu(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 uu(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 pu(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 du(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 aA={provider:"agentmail",managed_available:!1};async function gu(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?du(r.data):null}async function mu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?aA:t.data}async function fu(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return du(n)}async function yu(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 hu(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 du(r)}async function cA(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function lA(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 bu(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function _u(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Pu(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Su(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function xu(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 wu(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Au(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function vu(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function ku(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ru(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Cu(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Iu(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Tu(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Eu(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Mu(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Ou(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Du(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function ju(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 uA(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function pA(){throw G("getReferralCode")}async function dA(){throw G("refreshReferralCode")}async function gA(e){throw G("validateReferralCode")}async function mA(){throw G("getReferralStats")}async function fA(e={}){throw G("listReferrals")}async function yA(e){throw G("sendReferralEmails")}function U(e){return l.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function $u(e){return A(await U(`/accounts/${e}/iam/groups`)).groups}async function Uu(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}`))}async function Lu(e,t){return A(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Bu(e,t,n){return A(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Fu(e,t){return A(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function Nu(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}/members`)).members}async function qu(e,t,n){return A(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function hA(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Gu(e,t,n){return A(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function bA(e,t){return A(await U(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function _A(e,t){let n=A(await U(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function Ze(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 PA(e,t={}){let n=Ze({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await U(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function SA(e,t={}){let n=Ze({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await U(`/accounts/${e}/iam/policies${n}`)).policies}async function xA(e,t){return A(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function wA(e,t,n){return A(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function AA(e,t){return A(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function vA(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function kA(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Wu(e){return A(await U(`/accounts/${e}/iam/roles`)).roles}async function Ku(e){return A(await U(`/accounts/${e}/iam/agent-identities`)).agents}async function Vu(e){return A(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function Hu(e,t){return A(await U(`/accounts/${e}/iam/roles/${t}/permissions`))}async function RA(e){return A(await U(`/accounts/${e}/iam/actions`)).actions}async function zu(e,t){return A(await U(`/accounts/${e}/iam/roles/${t}/usage`))}async function Yu(e,t){return A(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Ju(e,t,n){return A(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Qu(e,t,n){return A(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Xu(e,t){return A(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function CA(e,t,n){return A(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function IA(e){return A(await U(`/accounts/${e}/iam/scim/tokens`)).tokens}async function TA(e,t){return A(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function EA(e,t){return A(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function MA(e){return A(await U(`/accounts/${e}/iam/mfa-required`))}async function OA(e){return A(await U(`/accounts/${e}/iam/mfa-required/preview`))}async function DA(e,t){return A(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function jA(e){return A(await U(`/accounts/${e}/iam/session-oversight`))}async function $A(e,t){return A(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function UA(e){return A(await U(`/accounts/${e}/iam/sso/provider`)).provider}async function LA(e,t){return A(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function BA(e){return A(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function FA(e){return A(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function NA(e){return A(await U(`/accounts/${e}/iam/sso/mappings`)).mappings}async function qA(e,t){return A(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function GA(e,t){return A(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function WA(e){return A(await U(`/accounts/${e}/iam/session-policy`))}async function KA(e,t){return A(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function VA(e){return A(await U(`/accounts/${e}/iam/sessions`)).sessions}async function HA(e,t){return A(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function zA(e){return A(await U(`/accounts/${e}/iam/pat-policy`))}async function YA(e,t){return A(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function JA(e){return A(await U(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function QA(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function XA(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function ZA(e,t){return A(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function ev(e){return A(await U(`/accounts/${e}/audit/webhooks`)).webhooks}async function tv(e,t){return A(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function nv(e,t,n){return A(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function rv(e,t){return A(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function sv(e,t={}){let n=Ze({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 A(await U(`/accounts/${e}/audit${n}`))}async function Zu(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),A(await U(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function ep(e,t,n){return n.length===0?[]:A(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function ov(e){return A(await U(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function iv(e,t){return A(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function tp(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function np(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function rp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function sp(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function op(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function ip(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function av(e){return Ze({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 ap(e,t){return u(await U(`/accounts/${e}/iam/assignments${av(t)}`)).assignments}async function cp(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 lp(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function up(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await U(`/accounts/${e}/iam/permissions${n}`)).permissions}async function Lf(){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 Bf(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function Ff(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function Nf(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}var qf="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function cv(e){throw G("getGoogleAuthUrl",qf)}async function lv(e,t){throw G("convertPresentationToGoogleSlides",qf)}async function pp(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 u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function dp(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function gp(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function mp(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function fp(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}var yp="call:";function uv(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(yp)&&e.length>yp.length?{type:"connector_call",executionId:e.slice(yp.length)}:{type:"review_item",reviewItemId:e}}function Wf(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function pv(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Wf(n.status)]+=1;return t}function dv(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 hp(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function bp(e){let t=e.indexOf(".");return t<=0?hp(e):`(${hp(e.slice(0,t))}) ${hp(e.slice(t+1))}`}function gv(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var ls=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},L=e=>typeof e=="string"&&e?e:void 0,we=e=>Array.isArray(e)?e:void 0,Gf=e=>typeof e=="number"?e:0,mv=e=>e.split(`
14
+ `).map(t=>t.trim()).filter(Boolean);function fv(e,t){let n=ls(e.advanced),r=L(e.description),s=we(e.whatChanged)??(r?mv(r):t.summary?[t.summary]:[]);return{crId:L(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:L(e.impact)??"",verification:we(e.verification)??[],previewUrl:L(e.previewUrl)??L(e.preview_url),conflicts:we(e.conflicts),requestedChanges:we(e.requested_changes)??[],advanced:{headRef:L(n.headRef)??L(e.head_ref)??"",baseRef:L(n.baseRef)??L(e.base_ref)??"",headSha:L(n.headSha)??L(e.head_sha)??L(e.head_commit_sha)??"",baseSha:L(n.baseSha)??L(e.base_sha)??"",additions:Gf(n.additions),deletions:Gf(n.deletions),files:we(n.files)??[],mergeMode:L(n.mergeMode)??"merge"}}}function yv(e,t){let n=we(e.actions);if(n)return{actions:n.map((c,p)=>({id:L(c.id)??`${t.review_item_id}-${p}`,title:L(c.title)??"Action",connector:L(c.connector)??"",action:L(c.action)??"",consequence:L(c.consequence)??"",risk:L(c.risk)??t.risk,icon:L(c.icon)??"generic",argsPreview:we(c.argsPreview)??[],policySource:L(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=L(e.action_path)??"",{connector:s,action:o}=gv(r),i=ls(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:L(e.execution_id)??t.review_item_id,title:r?bp(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,approvalContext:L(e.approval_context),connectorRisk:L(e.risk)??null,policySource:"Requires approval"}]}}function hv(e,t){return{artifactKind:L(e.artifactKind)??"document",artifactLabel:L(e.artifactLabel)??"Output",previewUrl:L(e.previewUrl)??L(e.preview_url),preview:L(e.preview),files:we(e.files),note:L(e.note)??t.summary??""}}function bv(e,t){return{question:L(e.question)??t.title??"",context:L(e.context),options:we(e.options)??[]}}function _v(e,t){return{note:L(e.note)??t.summary??"",children:we(e.children)??[]}}function Pv(e){let t=ls(e.detail);switch(e.kind){case"change":return fv(t,e);case"approval":return yv(t,e);case"output":return hv(t,e);case"decision":return bv(t,e);case"batch":return _v(t,e)}}function Sv(e,t){let n=typeof e.number=="number"?e.number:void 0,r=L(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function xv(e,t={}){let n=ls(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?L(n.action_path):void 0,i=e.kind==="change"?Sv(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?bp(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:Pv(e)}}async function _p(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Pp(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 Sp(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 us=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Kf(e,t=""){return`${qn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Vf(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 us(s,t.status)}return r}async function wv(e){return Vf(Kf(e))}async function Av(e){return Vf(Kf(e,"/messages"))}async function xp(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function wp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function ps(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function ds(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var vv=4;async function Hf(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(vv,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 Ap(e,t,n){return Hf(t,r=>ps(e,r.sessionId,r.reminderId,n))}function vp(e,t){return Hf(t,n=>ds(e,n.sessionId,n.reminderId))}async function kp(e){return u(await l.get(`/projects/${e}/reminders`))}async function Rp(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 Cp(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 Ip(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function Tp(){return u(await l.get("/oauth/grants")).grants}async function Ep(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function kv(){return u(await l.get("/accounts/me/devices")).devices}async function Rv(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function Mp(e){return u(await l.get(`/projects/${e}/cli-token`))}async function Op(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function Dp(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function qt(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 jp(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 $p(e,t){let n=qt(jp(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function Up(e,t){let n=qt(jp({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function Lp(e,t){let n=qt(jp(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Bp(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Fp(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Np(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function qp(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Gp(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 Wp(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 Cv(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function Kp(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 Vp(){return u(await l.get("/marketplace/marketplaces"))}async function Hp(){return u(await l.get("/marketplace/marketplaces/featured"))}async function zp(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Yp(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Jp(){return u(await l.get("/marketplace/sources"))}async function Qp(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Xp(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function Iv(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function Tv(e){throw G("getTemplate")}async function Ev(e,t){throw G("installTemplate")}async function Zp(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function ed(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function gs(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function td(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function nd(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function rd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function sd(e,t){let n=await gs(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 od(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function id(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 ad(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function cd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function ms(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 Mv(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function Ov(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 ld(e,t,n={}){let r=await Mv(t),s=n.mediaType??"application/gzip",o=await ms(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 Ov(r),size_bytes:r.byteLength})}async function ud(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function pd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function dd(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function gd(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 md(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function fd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function yd(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function hd(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var fe=(e,t)=>`/projects/${e}/apps/${t}`;async function bd(e,t){return u(await l.get(`${fe(e,t)}/machines`),"Failed to list machines").machines}async function _d(e,t,n,r){return u(await l.post(`${fe(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Pd=(e,t,n)=>_d(e,t,n,"start"),Sd=(e,t,n)=>_d(e,t,n,"stop"),xd=(e,t,n)=>_d(e,t,n,"restart");async function wd(e,t,n){return u(await l.delete(`${fe(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Ad(e,t,n){return u(await l.put(`${fe(e,t)}/scale`,{count:n}),"Failed to scale the App")}async function vd(e,t,n){return u(await l.post(`${fe(e,t)}/exec`,n),"Failed to run the command")}async function kd(e,t){return u(await l.get(`${fe(e,t)}/volumes`),"Failed to list volumes").volumes}async function Rd(e,t,n){return u(await l.post(`${fe(e,t)}/volumes`,n),"Failed to create the volume")}async function Cd(e,t,n,r){return u(await l.patch(`${fe(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function Id(e,t,n,r){u(await l.delete(`${fe(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Td(e,t,n){return u(await l.get(`${fe(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Ed(e,t,n){return u(await l.post(`${fe(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Md(e,t,n,r){return u(await l.post(`${fe(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function Od(e,t,n,r){return u(await l.post(`${fe(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function ce(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var pe=e=>`/drives/${encodeURIComponent(e)}`;async function Dv(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new _("Files not found",{status:404});return t[0]}async function jv(e,t){return u(await l.get(`${pe(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function $v(e,t){return u(await l.put(`${pe(e)}/access`,t),"Failed to share folder")}async function Uv(e,t){let n=u(await l.delete(`${pe(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function Lv(e){return u(await l.get(`${pe(e)}/principals`),"Failed to load people")}async function Bv(e){return u(await l.get(`${pe(e)}/conflicts`),"Failed to load conflicts").conflicts}async function Fv(e,t){u(await l.post(`${pe(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function Nv(e,t="/"){return(await zf(e,t)).entries}async function zf(e,t="/"){return u(await l.get(`${pe(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function Dd(e,t,n){let r=ce(k().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${pe(e)}/files/content?${new URLSearchParams(s)}`}async function qv(e,t,n){let r=await j(Dd(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new _(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function Gv(e,t,n){let r=await j(Dd(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new _(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function Wv(e,t,n,r){return u(await l.putRaw(`${pe(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function Kv(e,t){return u(await l.post(`${pe(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function Vv(e,t,n){return u(await l.post(`${pe(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function Hv(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${pe(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function zv(e){return u(await l.get(`${pe(e)}/versions`),"Failed to load versions").versions}async function Yv(e,t){u(await l.post(`${pe(e)}/restore`,{versionId:t}),"Failed to restore version")}var Jv=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function Qv(e,t){return(await Yf(e,t)).drives}async function Yf(e,t){return u(await l.get(Jv(e,t)),"Failed to load session files")}async function jd(e){return u(await l.post("/notifications/device-token",e))}async function $d(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var Xv=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered"];async function Ud(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 Ld(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 Zv={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 Bd(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function Fd(e){return u(await l.put("/notifications/preferences",e))}async function Nd(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function qd(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 Gd(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function Wn(e){return u(await l.get(`/projects/${e}/model-access`))}async function Kn(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function ek(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 Wd(e){return typeof e=="string"&&e.trim().length>0}function Jf(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Wd(t)||Wd(n)||Wd(r)}function tk(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 Vn(e){if(!e)return!0;let t=tk(e.items);return t?!t.some(Jf):!Jf(e)}function de(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function nk(e){return de(e)==="bash"}function rk(e){let t=de(e);return t==="question"||t==="ask"}function sk(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Qf=new Set(["show","show_user"]);function Kd(e){return Qf.has(de(e))}function ok(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Vd(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||ys(e))}function ys(e){let t=de(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:Vn(e.state?.input)}var Xf=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Hd(e){return Xf.has(de(e))}var ik=50*1024*1024,zd="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",ak=new RegExp(`^beeuni-attachment://(${zd})/(${zd})/(${zd})$`);function Jd(e){if(typeof e!="string")return null;let t=ak.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function ck(e){return Jd(e)!==null}var Yd=new WeakMap;async function Qd(e,t,n,r={}){if(n.size>ik)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:Yd.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=Yd.get(n)??new Map;c.set(s,i),Yd.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 Xd(e,t){let n=Jd(e);if(!n)throw new Error("Invalid attachment reference");let r=k().backendUrl.replace(/\/$/,""),s=await j(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new _("Could not load attachment",{status:s.status});return s.blob()}var lk=new Set(["show","show_user"]);function uk(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 Gt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Hn=e=>typeof e=="string"&&e.length>0?e:null,Zf=e=>typeof e=="string"?Hn(e.split("/").pop()):null;function hs(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 pk(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 dk(e,t){for(let n of uk(e))t(hs(n,"attachment"),hs(n,"filename")??Zf(hs(n,"path")),hs(n,"mime"))}function gk(e,t){for(let n of[e,...pk(e.items)])Gt(n)&&t(n.attachment,Zf(n.path),null)}function mk(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!Gt(r)||!Gt(r.info)||!Array.isArray(r.parts))continue;let s=Hn(r.info.id);if(!s)continue;let o=Hn(r.info.role)??"unknown",i=(a,c,p)=>{let d=Jd(a);!d||n.has(a)||(n.add(a),t.push({url:a,attachment_id:d.attachmentId,filename:c,mime:p,message_id:s,role:o}))};for(let a of r.parts)Gt(a)&&(a.type==="file"?i(a.url,Hn(a.filename),Hn(a.mime)):a.type==="text"&&typeof a.text=="string"?dk(a.text,i):a.type==="tool"&&typeof a.tool=="string"&&lk.has(de(a.tool))&&Gt(a.state)&&Gt(a.state.input)&&gk(a.state.input,i))}return t}function et(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function fk(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 yk(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 Zd(e,t,n){return e!==void 0?e:fk(et(t),n)}var eg={get disableMobileAdvertising(){return Zd(k().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Zd(k().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Zd(k().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var hk=new Set(["project-manager"]);function bs(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:eg.enableProjects||!hk.has(e.name)}function bk(e){let t=e.agents.filter(bs),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 ey(){return{projects:{list:yt,listForAccount:ui,get:An,detail:vn,create:mi,createRepo:fi,provision:yi,update:Cn,archive:In,llmCatalog:kn,modelPicker:Rn,modelAccess:Wn,setModelAccess:Kn,sandboxHealth:En,sandboxTemplates:nc,sessions:_t,createSession:Pt},github:{linkRepository:xi,replaceProjectRepository:wi,getInstallation:Ai,listInstallations:vi,listLinkableInstallations:ki,listRepositories:Ri,listRepositoryBranches:Ci,linkInstallation:Ti,saveInstallation:Ii,deleteInstallation:Mi,storeUserToken:Ei},connectStatus:Ya,marketplace:{items:s=>Kp(s),item:s=>zp(s),itemFile:(s,o)=>Yp(s,o),marketplaces:()=>Vp(),featured:()=>Hp(),sources:{list:()=>Jp(),add:s=>Qp(s),remove:s=>Xp(s)}}}}function ty(){return{billing:{accountState:jl,accountStateMinimal:$l,transactions:Ul,transactionsSummary:Ll,creditBreakdown:Bl,usageHistory:Fl,usageRollup:Zl,sessionCosts:{list:nu,get:Gn},tierConfigurations:Nl,checkout:{createSession:n=>ql(n),confirmSession:(n,r)=>Gl(n,r)},subscription:{createPortalSession:(n,r)=>Wl(n,r),cancel:(n,r)=>Kl(n,r),reactivate:n=>Vl(n),scheduleDowngrade:(n,r,s)=>Hl(n,r,s),cancelScheduledChange:n=>zl(n),prorationPreview:(n,r)=>Yl(n,r)},credits:{purchase:n=>Jl(n),autoTopupSettings:n=>Ql(n),configureAutoTopup:n=>Xl(n)}},sandboxShares:{list:_p,create:Pp,revoke:Sp}}}var Be={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",BEEUNI_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function tt(){let e=et("BACKEND_URL")||k().backendUrl;return e||"http://localhost:8008/v1"}function St(e){let t=ce(e);return t.endsWith("/v1")?t:`${t}/v1`}function zn(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=zn(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return zn(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function _k(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 tg(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?`${tt()}/p/${n.external_id}/${Be.BEEUNI_MASTER}`:""),status:_k(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 ng(){let e=await yt(),t=[];for(let n of e){let r=await _t(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:tg(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 xt(e){let t=await ng();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 Wt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function se(e,t,n){let r=n?.fetch??k().fetch??((p,d)=>fetch(p,d)),s=ce(n?.backendUrl??k().backendUrl??"");if(!s)throw new Wt("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(`${St(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 Wt(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 _s(e,t){return se("/auth/signup",{body:e},t)}function Ps(e,t){return se("/auth/sign-in/password",{body:e},t)}function Ss(e,t){return se("/auth/sign-in/magic-link",{body:e},t)}function xs(e,t){return se("/auth/verify-otp",{body:e},t)}function ws(e,t){return se("/auth/sign-in/oauth",{body:e},t)}function As(e,t){return se("/auth/oauth/exchange",{body:e},t)}function Kt(e,t){return se("/auth/refresh",{body:e},t)}function vs(e,t){return se("/auth/password/reset",{body:e},t)}function ks(e,t,n){return se("/auth/password/update",{body:e,bearer:t},n)}function Rs(e,t){return se("/auth/user",{bearer:e},t)}function Cs(e,t,n){return se("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function Is(e,t){return se("/auth/sign-in/sso",{body:e},t)}var Ts={enroll:(e,t,n)=>se("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>se(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>se(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>se(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function Es(e,t={},n){return se("/auth/sign-out",{body:t,bearer:e},n)}function Ms(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=w=>(w.expires_at??0)*1e3,g=w=>d(w)-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 w of[...p])try{w(r)}catch{}try{e.onChange?.(r)}catch{}}async function y(){if(o)return r;if(!i){let w=c,M=(async()=>{let B=await e.storage.get();if(w===c&&B)try{let F=JSON.parse(B);F.session?.access_token&&F.session?.refresh_token&&(r=F.session,s=F.user??null)}catch{r=null}return o=!0,r})();i=M,M.then(()=>{i===M&&(i=null)},()=>{i===M&&(i=null)})}return i}async function h(){if(await y(),!r)return null;if(!a){let w=r.refresh_token,M=c,B=Kt({refresh_token:w},e.request).then(async F=>(M!==c||(r=F.session,F.user&&(s=F.user),await m()),r)).catch(async F=>{if(M!==c)return r;let f=F&&typeof F=="object"&&"status"in F?F.status:0;if(f>=400&&f<500)return r=null,s=null,await m(),null;throw F}).finally(()=>{a===B&&(a=null)});a=B}return a}return{subscribe(w){return p.add(w),()=>{p.delete(w)}},current:()=>r,user:()=>s,load:y,async set(w,M){await y(),c+=1,a=null,r=w,M!==void 0&&(s=M),w||(s=null),await m()},async getToken(){return await y(),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 ny(){return{list:qo,get:Wo,create:Go,secretResources:{list:ua,create:pa,rotate:da,retry:ga,remove:ma,grant:fa,revoke:ya,setAccess:ha},updateName:Ko,branding:{get:Vo,update:Ho,uploadAsset:zo,removeAsset:Yo,reset:Jo},leave:ci,members:Qo,invite:Xo,removeMember:ii,updateMemberRole:ai,invites:Zo,cancelInvite:ei,resendInvite:ti,tokens:{list:Rp,create:Cp,revoke:Ip},connectedApps:{list:Tp,revoke:Ep},audit:{log:$p,export:Lp,webhooks:{list:Bp,create:Fp,update:Np,remove:qp}}}}function ry(){return{assignments:{list:ap,create:cp,revoke:lp},permissions:{list:up,forRole:Hu},roles:{list:Wu,create:Yu,update:Ju,setPermissions:Qu,remove:Xu,usage:zu},groups:{list:$u,get:Uu,create:Lu,update:Bu,remove:Fu,members:{list:Nu,add:qu,remove:Gu}},agentIdentities:Ku,oauthClients:{list:tp,get:np,create:rp,update:sp,rotateSecret:op,remove:ip},can:Zu,canBatch:ep}}function sy(){let e={signUp:_s,signInWithPassword:Ps,sendMagicLink:Ss,verifyOtp:xs,signInWithProvider:ws,exchangeCode:As,refresh:Kt,resetPassword:vs,updatePassword:ks,updateUserMetadata:Cs,signInWithSso:Is,mfa:Ts,user:Rs,signOut:Es,session:Ms},t=ny(),n=ry();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:ni,describe:ri,accept:si,decline:oi}}}var Yn=new Map,rg=new Map;function sg(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function oy(e){return Yn.get(sg(e))??null}function iy(){return[...Yn.values()].filter(e=>typeof e=="string")}function ay(e){return Yn.has(sg(e))}async function nt(e){let t=sg(e),n=Yn.get(t);if(n!==void 0)return n;let r=rg.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 Yn.set(t,i),i}catch{return null}finally{rg.delete(t)}})();return rg.set(t,s),s}function cy(e){let{apiBaseUrl:t}=e;return ay(t)||nt(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:oy(t)}}function ly(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 _(`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),cy({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function uy(e,t){let n=null;async function r(){n||(n=Ln(e,t,{showErrors:!1}).then(s=>{let o=fl(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 Jn=new Map;function py(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 wt=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 Vt={url:null,sandboxId:null,dbSandboxId:null,version:0},Sk=new Set;function dy(e,t=null,n=null){if(!(Vt.url===e&&Vt.sandboxId===t&&Vt.dbSandboxId===n)){Vt={url:e,sandboxId:t,dbSandboxId:n,version:Vt.version+1};for(let r of Sk)r()}}function gy(){return Vt.url}function my(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await Xe(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 Xe(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 _(py(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new _("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Qe(c);return dy(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function fy(e,t,n){let r=null;function s(){if(r)return r;let p=vf(e,t);return p&&(r=p),r}let o=my(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=nt(k().backendUrl??n.backendUrl).catch(()=>null),y=`${e}
15
+ ${t}`,h=Jn.get(y);if(h)return r=await h,await m,r;let w=o(g);Jn.set(y,w);try{return r=await w,await m,r}finally{Jn.get(y)===w&&Jn.delete(y)}}function a(p){let d=s();if(!d)throw new wt(p);return d}function c(){r=null,Rf(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:c}}var K=["directory","workspace"],yy=["messageID","model","agent","noReply","tools","format","system","variant","parts"],I=(e,t,n=K,r=[],s)=>({method:e,path:t,query:n,body:r,bodyParam:s}),xk={"session.list":I("GET","/session",[...K,"scope","path","roots","start","search","limit"]),"session.get":I("GET","/session/{sessionID}"),"session.create":I("POST","/session",K,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":I("DELETE","/session/{sessionID}"),"session.update":I("PATCH","/session/{sessionID}",K,["title","metadata","permission","time"]),"session.status":I("GET","/session/status"),"session.messages":I("GET","/session/{sessionID}/message",[...K,"limit","before"]),"session.prompt":I("POST","/session/{sessionID}/message",K,yy),"session.promptAsync":I("POST","/session/{sessionID}/prompt_async",K,yy),"session.abort":I("POST","/session/{sessionID}/abort"),"session.revert":I("POST","/session/{sessionID}/revert",K,["messageID","partID"]),"session.unrevert":I("POST","/session/{sessionID}/unrevert"),"session.summarize":I("POST","/session/{sessionID}/summarize",K,["providerID","modelID","auto"]),"session.command":I("POST","/session/{sessionID}/command",K,["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",K,["messageID"]),"session.diff":I("GET","/session/{sessionID}/diff",[...K,"messageID"]),"session.todo":I("GET","/session/{sessionID}/todo"),"permission.list":I("GET","/permission"),"permission.reply":I("POST","/permission/{requestID}/reply",K,["reply","message"]),"question.list":I("GET","/question"),"question.reply":I("POST","/question/{requestID}/reply",K,["answers"]),"question.reject":I("POST","/question/{requestID}/reject"),"part.update":I("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",K,[],"part"),"part.delete":I("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":I("GET","/file",[...K,"path"]),"file.read":I("GET","/file/content",[...K,"path"]),"find.files":I("GET","/find/file",[...K,"query","dirs","type","limit"]),"vcs.diff":I("GET","/vcs/diff",[...K,"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",K,["method","inputs"]),"provider.oauth.callback":I("POST","/provider/{providerID}/oauth/callback",K,["method","code"]),"auth.set":I("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":I("GET","/agent"),"app.skills":I("GET","/skill"),"app.log":I("POST","/log",K,["service","level","message","extra"]),"command.list":I("GET","/command"),"tool.ids":I("GET","/experimental/tool/ids"),"tool.list":I("GET","/experimental/tool",[...K,"provider","model"]),"mcp.status":I("GET","/mcp"),"mcp.add":I("POST","/mcp",K,["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",K,["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 wk(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 Ak(e,t,n={},r={}){let s=xk[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}${wk(s,n)}`,{method:s.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function vk(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 kk(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=vk(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 og(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: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
- `);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??""}
19
+ `);a=d.pop()??"";for(let g of d){let m={},y=[];for(let h of g.split(`
20
+ `))if(h.startsWith("data:"))y.push(h.replace(/^data:\s*/,""));else if(h.startsWith("id:"))m.id=h.replace(/^id:\s*/,"");else if(h.startsWith("retry:")){let w=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(w)||(m.retry=w)}y.length&&(m.data=y.join(`
21
+ `)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*Rk(e,t,n){let r=e.eventTransport??og(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 Qn(e){let t=s=>(o,i)=>kk(e,Ak(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:Rk(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 hy=200;async function Ck(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 At(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 _(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function by(e){let t=e.runtimeUrl.replace(/\/$/,""),n=Qn({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=w=>e.fetch(new Request(`${t}${w}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),y=await m("/beeuni/runtime");if((y.status===404||(y.headers.get("content-type")??"").startsWith("text/html"))&&(y=await m("/beeuni/opencode")),!y.ok)throw new _(`Reading the session transcript failed: ${await Ck(y)}`,{status:y.status,response:y});let h=await y.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,hy),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,hy),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=>At(i,"Reading the session status failed")),n.permission.list().then(i=>At(i,"Reading permission requests failed")),n.question.list().then(i=>At(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{At(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){At(await n.question.reject({requestID:r}),"Dismissing the question failed");return}At(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 _("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return At(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function _y(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return by({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 Py(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await ml(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Ht=BigInt(4096),Fe=BigInt(0xffffffffffff),Sy=Fe+BigInt(1),Ik=Sy/BigInt(2),rt=BigInt(3600*1e3)*Ht,Os=120*1e3,xy=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,Tk=/^msg_([0-9a-f]{12})/,wy="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function vt(e){let t=Tk.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function zt(e){return BigInt(Math.trunc(e))*Ht&Fe}function kt(e,t){let n=e-t&Fe;return n>=Ik&&(n-=Sy),n}function ig(e){let t=null;for(let n of e)n!=null&&(t===null||kt(n,t)>BigInt(0))&&(t=n);return t}function Ay(e,t){let n=vt(e);return n===null?!1:kt(n,zt(t))>rt}function vy(e,t){let n=t===void 0?null:zt(t);return ky(e,r=>n===null||kt(r,n)<=rt)}function ky(e,t){let n=[];for(let r of e){let s=vt(r);s!==null&&t(s)&&n.push(s)}return ig(n)}function Ek(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=wy[n%62])}return e}function ag(e){let t=e.random,n=zt(e.nowMs-(e.backdateMs??Os)),r=e.newestKnownTime??null;if(r!==null){let o=kt(r,n);o>=BigInt(0)&&o<=rt&&(n=r+BigInt(1)&Fe)}let s="";if(t)for(let o=0;o<14;o++)s+=wy[Math.min(61,Math.floor(t()*62))];else s=Ek();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function Ds(e={}){let t=e.nowMs??Date.now(),n=zt(t-Os),r=ky(e.after??[],s=>{let o=kt(s,n);return o>=BigInt(0)&&o<=rt});return ag({nowMs:t,newestKnownTime:r}).id}function Ry(e){return{scope:()=>dl(e.projectId,e.sessionId),providerSecretPool:{list:()=>_a(e.projectId,e.sessionId),get:t=>ba(e.projectId,e.sessionId,t),set:(t,n)=>Pa(e.projectId,e.sessionId,t,n)},rescope:t=>gl(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=Ds(),p=await Bn(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 _("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var Rt="beeuni.transcript.v1",Cy=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function cg(e){return typeof e=="string"&&Cy.includes(e)}var Mk=["once","always","reject"],Ok=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var Iy=async function*(e){let t=k().eventStreamTransport;if(!t){yield*og(((s,o)=>j(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await Br(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function Ne(){let e=gy();return e||(k().billingEnabled??!1?"":Cf())}async function lg(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function ug(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function pg(e){let t=ug(e),n=await j(`${t}/env`);if(!n.ok)throw new Error(await lg(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function dg(e,t,n){let r=ug(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 lg(s,"Failed to save secret"))}async function gg(e,t){let n=ug(e),r=await j(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await lg(r,"Failed to delete secret"))}var Ty={list:pg,set:dg,delete:gg};async function Ey(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 js(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function Xn(e){if(!e)throw new Error("[beeuni-pty] Server URL not ready \u2014 sandbox is still loading");return ce(e)}async function fg(e){let t=Xn(e),n=await j(`${t}/beeuni/pty`);if(!n.ok)throw new Error(await js(n,"Failed to list terminals"));return n.json()}async function yg(e,t){let n=Xn(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 js(r,"Failed to create terminal"));return r.json()}async function hg(e,t,n){let r=Xn(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 js(s,"Failed to update terminal"));return s.json()}async function bg(e,t){let n=Xn(e),r=await j(`${n}/beeuni/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await js(r,"Failed to remove terminal"))}async function _g(e,t,n){let r=Xn(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:"),ce(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/beeuni/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await Ye();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${o}${o.includes("?")?"&":"?"}${c}`:o}function My(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 st="\x1B",Oy="\x07",Dk="\0",mg=`(?:${Oy}|${st}\\\\)`,jk=[new RegExp(`${st}\\]697;[^${Oy}${st}]*${mg}`,"g"),new RegExp(`${Dk}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${st}\\][0-9]+;rgb:[0-9a-fA-F/]+${mg}`,"g"),new RegExp(`${st}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${mg}`,"g"),new RegExp(`${st}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${st}\\[\\d+;\\d+R`,"g"),new RegExp(`${st}\\[\\?[0-9;]*c`,"g")];function Dy(e){let t=e;for(let n of jk)t=t.replace(n,"");return t}var jy={list:fg,create:yg,update:hg,remove:bg,webSocketUrl:_g};async function T(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 $k(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 T(e,`/beeuni/tasks${r}`)}async function Uk(e,t){return T(e,`/beeuni/tasks/${encodeURIComponent(t)}`)}async function Lk(e,t){return T(e,`/beeuni/tasks/${encodeURIComponent(t)}/events`)}async function Bk(e,t){return T(e,`/beeuni/tasks/${encodeURIComponent(t)}/status`)}async function Fk(e,t){return T(e,"/beeuni/tasks",{method:"POST",body:JSON.stringify(t)})}async function Nk(e,t,n){return T(e,`/beeuni/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function qk(e,t){return T(e,`/beeuni/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function Gk(e,t){return T(e,`/beeuni/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function Wk(e,t){return T(e,`/beeuni/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Kk(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return T(e,`/beeuni/tickets${n}`)}async function Vk(e,t){return T(e,`/beeuni/tickets/${encodeURIComponent(t)}`)}async function Hk(e,t){return T(e,`/beeuni/tickets/${encodeURIComponent(t)}/events`)}async function zk(e,t){return T(e,"/beeuni/tickets",{method:"POST",body:JSON.stringify(t)})}async function Yk(e,t,n){return T(e,`/beeuni/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function Jk(e,t,n){return T(e,`/beeuni/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function Qk(e,t,n){return T(e,`/beeuni/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function Xk(e,t,n){return T(e,`/beeuni/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function Zk(e,t,n){return T(e,`/beeuni/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function eR(e,t){return T(e,`/beeuni/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function tR(e,t){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/columns`)}async function nR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function rR(e,t){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/fields`)}async function sR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function oR(e,t){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/templates`)}async function iR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function aR(e,t){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function cR(e,t){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/agents`)}async function lR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function uR(e,t,n,r){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function pR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function dR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function gR(e,t,n=200){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function mR(e){return T(e,"/beeuni/projects")}async function fR(e,t){return T(e,`/beeuni/projects/${encodeURIComponent(t)}`)}async function yR(e,t){return T(e,`/beeuni/projects/by-session/${encodeURIComponent(t)}`)}async function hR(e,t){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/sessions`)}async function bR(e,t){return T(e,`/beeuni/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function _R(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function PR(e,t,n="all"){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function SR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function xR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function wR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function AR(e,t,n,r){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function vR(e,t,n,r){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function kR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function RR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function CR(e,t){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials`)}async function IR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function TR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function ER(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function MR(e,t,n){return T(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var OR=1e4,DR={retryOnAuthError:!1};function Yt(e,t,n){return T(e,t,{signal:AbortSignal.timeout(OR),...n},DR)}async function jR(e,t=!1){return(await Yt(e,`/beeuni/services${t?"?all=true":""}`)).services??[]}async function $R(e){return(await Yt(e,"/beeuni/services/templates")).templates??[]}async function UR(e,t){return(await Yt(e,`/beeuni/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function LR(e,t,n){let r=n==="delete",s=r?`/beeuni/services/${encodeURIComponent(t)}`:`/beeuni/services/${encodeURIComponent(t)}/${n}`;return Yt(e,s,{method:r?"DELETE":"POST"})}async function BR(e,t){return Yt(e,`/beeuni/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function FR(e,t){return Yt(e,"/beeuni/services/register",{method:"POST",body:JSON.stringify(t)})}var qe=new Map,NR=256,Jt=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function ot(){let e=Ne();if(!e)throw new Jt;return Ae(e)}function Ae(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=qe.get(e);if(t)return qe.delete(e),qe.set(e,t),t;if(!Mr())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureBeeuni()/createBeeuni() before talking to a sandbox runtime.");let n=Qn({baseUrl:e,fetch:j,eventTransport:Iy});return qe.set(e,n),qe.size>NR&&qe.delete(qe.keys().next().value),n}function qR(e){qe.delete(e)}function GR(){qe.clear()}var $s=new Map;function WR(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=$s.get(e);if(t)return t;let n=Qn({baseUrl:e,fetch});return $s.set(e,n),n}function KR(e){$s.delete(e)}function VR(){$s.clear()}async function HR(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 zR(e){let t=Ne();if(!t)throw new _("[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 _(`System reload failed (${r.status}): ${await HR(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new _(`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 _(`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 $y="frontend";function Us(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${$y}] ${t}`,...n?[n]:[]);try{ot().app.log({service:$y,level:e,message:t,extra:n})}catch{}}var it={debug:(e,t)=>Us("debug",e,t),info:(e,t)=>Us("info",e,t),warn:(e,t)=>Us("warn",e,t),error:(e,t)=>Us("error",e,t)};function Uy(e){return{type:"heartbeat-gap",gapMs:e}}function Ly(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 YR={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},JR=16,QR=8,XR=6e4,ZR=5e3,eC=250,tC=1e3,nC=3e4,rC=5,sC=1e4,oC=4,iC=.5,aC=3e3,cC=3e4,lC=2e4,uC=2e3,pC=8;function dC(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function gC(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 By(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 Zn=new WeakMap;function mC(e,t,n){let r=t.timers??YR,s=t.connectTimeoutMs??lC,o=t.heartbeatTimeoutMs??XR,i=t.maxConsecutiveHardFailures??pC,a=new AbortController;function c(b,...S){for(let O of n){let C=b(O);if(C)try{C(...S)}catch(P){console.warn("[opencode-events] subscriber handler threw, skipping",P)}}}let p=null,d=!1,g=b=>{p!==b&&(p=b,b&&c(S=>S.onConnectionChange,b))},m=r.now(),y=null,h=[],w,M=0,B=new Map,F=()=>{if(w&&r.clearTimeout(w),w=void 0,h.length===0)return;let b=h;h=[],B.clear(),M=r.now(),m=r.now();for(let S of b)S&&c(O=>O.onEvent,S.event)},f=()=>{if(w)return;let b=r.now()-M;w=r.setTimeout(F,Math.max(0,JR-b))};return(async()=>{let b=0,S=0,O=0;for(;!a.signal.aborted;){let C=!1,P=!1,x,v,R=null,$=r.now(),D=new AbortController;g("connecting");let E=By(a.signal);E.promise.then(()=>D.abort());try{let ee=await new Promise((Et,gt)=>{let ue=!1;v=r.setTimeout(()=>{ue||(ue=!0,it.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:s}),D.abort(),gt(new Error(`SSE connect timed out after ${s}ms`)))},s),e.global.event({signal:D.signal,sseDefaultRetryDelay:aC,sseMaxRetryDelay:cC,sseMaxRetryAttempts:1}).then(Te=>{ue||(ue=!0,r.clearTimeout(v),Et(Te))},Te=>{ue||(ue=!0,r.clearTimeout(v),gt(Te))})}),{stream:pt}=ee;if(y){let Et=r.now()-y.lastActivityAt,gt=y.eventful;y=null,(gt||Et>ZR)&&c(ue=>ue.onGapRehydrate,Et)}m=r.now();let dt=()=>{r.clearTimeout(x),x=r.setTimeout(()=>{it.warn("SSE heartbeat timeout, forcing reconnect"),D.abort()},o)};dt();let Ir=r.now(),aS=pt[Symbol.asyncIterator]();for(;!D.signal.aborted;){let Et=aS.next().then(Ee=>({kind:"next",result:Ee}),Ee=>({kind:"error",error:Ee})),gt=By(D.signal),ue=await Promise.race([Et,gt.promise.then(()=>({kind:"aborted"}))]);if(gt.cleanup(),ue.kind==="aborted")break;if(ue.kind==="error")throw ue.error;if(ue.result.done)break;g("open"),dt();let Te=ue.result.value,Mt=Te&&typeof Te=="object"&&"payload"in Te?Te.payload:Te;if(!Mt?.type)continue;Mt.type!=="server.connected"&&(C=!0);let wo=gC(h[h.length-1]?.event,Mt);if(wo)h[h.length-1]={type:wo.type,event:wo};else{let Ee=dC(Mt);if(Ee){let Fm=B.get(Ee);Fm!==void 0&&(h[Fm]=void 0),B.set(Ee,h.length)}h.push({type:Mt.type,event:Mt})}f(),!(r.now()-Ir<QR)&&(Ir=r.now(),await new Promise(Ee=>r.setTimeout(Ee,0)))}P=C}catch(ee){if(a.signal.aborted)break;R=ee;let pt=String(ee),dt=Ot(ee)||Ot(ee?.cause);if(it.error("SSE event stream error",{error:pt,retryCount:b,isAuthError:dt}),dt)try{Wr(),await Ye(),it.info("SSE: refreshed auth token after auth error")}catch(Ir){it.error("SSE: failed to refresh auth token",{error:String(Ir)})}}finally{r.clearTimeout(x),r.clearTimeout(v),D.abort(),E.cleanup(),F()}if(a.signal.aborted)break;let q=r.now()-$,Q=R?.cause?.status;if(S=!C&&(typeof Q=="number"&&Q>=400||q<uC)?S+1:0,S>=i){it.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:S,lastError:String(R)}),p=null,d=!0,c(ee=>ee.onParked,{consecutiveFailures:S,lastError:R});break}g("lost"),y={lastActivityAt:m,eventful:(y?.eventful??!1)||C},O=P&&q<sC?O+1:0;let Ce=P&&O<=oC;Ce?b=0:(b++,b>1&&it.warn("SSE event stream reconnecting",{retryCount:b}));let Pn=Ce?eC:Math.min(tC*2**Math.min(b-1,rC),nC),Ie=Math.round(Pn*(1+iC*(r.random?.()??0)));await new Promise(ee=>{let pt=r.setTimeout(ee,Ie),dt=()=>{r.clearTimeout(pt),ee()};a.signal.addEventListener("abort",dt,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),w&&r.clearTimeout(w)}}}function Ls(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?Ae(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=Zn.get(i);if(c?.isParked()&&(Zn.delete(i),c=void 0),!c)c=mC(i,e,new Set([a])),Zn.set(i,c);else{c.subscribers.add(a);let y=c.connectionState();y&&s?.(y)}let p=c,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),Zn.get(i)===p&&Zn.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function Fy(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Ae(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Ae(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Ae(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return Ls({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Wy(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 _(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Zt(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 te(e){let t=(e??Ne()).trim();if(!t)throw new Jt;return t}async function Fs(e,t){let n=await j(`${te(t)}${e}`);if(!n.ok)throw new _(await Zt(n),{status:n.status,response:n});return n.json()}var Ns=["/workspace","/tmp","/home","/opt"],fC=Ns.filter(e=>e!=="/workspace");function xg(e){return Ns.some(t=>e===t||e.startsWith(`${t}/`))}function en(e){return xg(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function at(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(fC.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var wg=at;async function tn(e,t){let n=te(t),r=at(e)||".";return(await Fs(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function nn(e,t){let n=te(t),r=at(e),s=await j(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!s.ok)throw new _(await Zt(s),{status:s.status,response:s});return s.json()}async function yC(e,t,n){let r=te(n),s=at(e),o=await j(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new _(await Zt(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new _("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 hC=8,Bs=0,Ky=[];async function bC(){if(Bs<hC){Bs++;return}await new Promise(e=>Ky.push(e)),Bs++}function _C(){Bs--,Ky.shift()?.()}function Vy(e,t){let n=te(t);return Mn(`${n}/file/raw?path=${encodeURIComponent(at(e))}`)}async function rn(e,t){await bC();try{let n=te(t);try{return await yC(e,void 0,n)}catch{}let r=await nn(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{_C()}}async function nr(e){return Fs("/file/status",te(e))}async function rr(e,t,n){let r=te(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),Fs(`/find/file?${s.toString()}`,r)}async function sr(e,t){let n=te(t);return(await Fs(`/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 er=[400,1200],PC=e=>e===408||e===429||e===502||e===503||e===504,Ny=e=>new Promise(t=>setTimeout(t,e));function SC(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Pg=3e4,Hy=15*6e4,xC=256;function Qt(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Pg;let t=Pg+e/xC;return Math.min(Hy,Math.max(Pg,Math.round(t)))}async function wC(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 tr(e,t){let n;for(let s=0;s<=er.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,SC(a)||s===er.length)break;await Ny(er[s]);continue}if(o.ok)return o.json();let i=await wC(o);if(n=new _(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!PC(o.status)||s===er.length)throw n;await Ny(er[s])}if(n instanceof _)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new _(`Upload failed: ${r}`)}var Sg=8*1024*1024;function AC(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new _(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function qy(e,t){try{e?.onProgress?.(t)}catch{}}function Gy(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 vC(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function sn(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=te(o),c=Qt(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Sg){let y=await tr(()=>Gy(e,t,p),h=>j(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return AC(y[0],e.size),qy(i,{loadedBytes:e.size,totalBytes:e.size}),y}let g=(await tr(()=>Gy(new Blob([],{type:e.type}),t,p),y=>j(`${a}/file/upload`,{method:"POST",body:y},{timeoutMs:Qt(0)})))[0]?.path;if(!g)throw new _("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=vC(g);if(!m.name)throw new _(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let y=0;y<e.size;y+=Sg){let h=Math.min(e.size,y+Sg),w=e.slice(y,h,e.type),M=await tr(()=>{let B=new FormData;return m.parent&&B.append("path",m.parent),B.append("filename",m.name),B.append("first",y===0?"true":"false"),B.append("offset",String(y)),B.append("file",w,m.name),B},B=>j(`${a}/file/append`,{method:"POST",body:B},{timeoutMs:Qt(w.size)}));if(M.path!==g||M.size!==h)throw new _(`Upload verification failed for ${g}: expected ${h} bytes, received ${M.size}`,{code:"UPLOAD_SIZE_MISMATCH"});qy(i,{loadedBytes:h,totalBytes:e.size})}}catch(y){throw await Ct(g,a).catch(()=>{}),y}return[{path:g,size:e.size}]}function zy(e,t,n){let r=te(n);return tr(()=>{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:kC}))}var kC=Hy;function RC(e,t,n){let r=te(n),s=Qt(t.size);return tr(()=>{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 Xt=class extends _{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 or(e,t){let n=te(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",c=en(`${a}/${i}`),p=[];try{p=await tn(Yy(c),n)}catch(g){if(!(g instanceof _&&g.status===404))throw g}if(p.some(g=>g.name===Jy(c)))throw new Xt(c);let d=await Qy(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function ir(e,t,n){let r=te(n);return RC(t,await rn(e,r),r)}function CC(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Yy(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Jy(e){return e.slice(e.lastIndexOf("/")+1)}function IC(){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 ar(e,t,n){let r=te(n),s=en(CC(e.trim()));return Qy(s,t,r,{overwrite:!0})}async function Qy(e,t,n,r){let s=Jy(e);if(!s)throw new _(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=Yy(e);await on(o,n).catch(()=>{});let i=IC(),a=await sn(t,o,`.${s}.beeuni-write-${i}`,n),c=a[0]?.path;if(!c)throw new _(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=en(c);try{await Xy(p,e,n,r.overwrite)}catch(g){throw await Ct(p,n).catch(()=>{}),!r.overwrite&&g instanceof _&&g.status===409?new Xt(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Ct(e,t){let n=await j(`${te(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new _(`Delete failed (${n.status}): ${await Zt(n)}`,{status:n.status,response:n});return n.json()}async function on(e,t){let n=await j(`${te(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new _(`Mkdir failed (${n.status}): ${await Zt(n)}`,{status:n.status,response:n});return n.json()}async function cr(e,t,n){return Xy(e,t,te(n),!0)}async function Xy(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 _(`Rename failed (${s.status}): ${await Zt(s)}`,{status:s.status,response:s});return s.json()}async function Ag(){return Wy(await ot().project.current())}async function qs(){return Wy(await ot().global.health())}async function vg(){try{return(await qs()).healthy===!0}catch{return!1}}var Zy={list:tn,read:nn,readBlob:rn,status:nr,findFiles:rr,findText:sr,upload:sn,write:ar,create:or,copy:ir,remove:Ct,mkdir:on,rename:cr,currentProject:Ag,health:qs,isReachable:vg,toDaemonPath:at,toSandboxAbsolutePath:en,toWorkspaceRelative:wg};function eh(e){return{list:async t=>tn(t,(await e()).runtimeUrl),read:async t=>nn(t,(await e()).runtimeUrl),readBlob:async t=>rn(t,(await e()).runtimeUrl),status:async()=>nr((await e()).runtimeUrl),findFiles:async(t,n)=>rr(t,n,(await e()).runtimeUrl),findText:async t=>sr(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>sn(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>ar(t,n,(await e()).runtimeUrl),create:async t=>or(t,(await e()).runtimeUrl),copy:async(t,n)=>ir(t,n,(await e()).runtimeUrl),remove:async t=>Ct(t,(await e()).runtimeUrl),mkdir:async t=>on(t,(await e()).runtimeUrl),rename:async(t,n)=>cr(t,n,(await e()).runtimeUrl)}}function th(e){return{get:t=>Ln(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:()=>Gn(e.sessionId,{projectId:e.projectId}),update:t=>al(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),cl(e.projectId,e.sessionId)),start:(...t)=>Xe(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Rl(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Fn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Nn(e.projectId,e.sessionId)),configState:()=>ll(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),ul(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),pl(e.projectId,e.sessionId,...t)),setSharing:t=>Nc(e.projectId,e.sessionId,t),previews:()=>Kc(e.projectId,e.sessionId),participants:()=>qc(e.projectId,e.sessionId),watch:()=>Gc(e.projectId,e.sessionId),setWatch:t=>Wc(e.projectId,e.sessionId,t),commit:t=>Dc(e.projectId,e.sessionId,t),publicShares:{list:()=>Vc(e.projectId,e.sessionId),create:(...t)=>Hc(e.projectId,e.sessionId,...t),revoke:(...t)=>zc(e.projectId,e.sessionId,...t)}}}function nh(e){return{reminders:{list:()=>xp(e.projectId,e.sessionId),create:t=>wp(e.projectId,e.sessionId,t),update:(t,n)=>ps(e.projectId,e.sessionId,t,n),remove:t=>ds(e.projectId,e.sessionId,t)},audit:(t,n)=>Qc(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Qd(e.projectId,e.sessionId,t,n),read:(t,n)=>Xd(`beeuni-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Xc(e.projectId,e.sessionId,t),messageAuthors:()=>yl(e.projectId,e.sessionId),modelUsage:()=>hl(e.projectId,e.sessionId),transcriptSync:t=>Zc(e.projectId,e.sessionId,t),turn:()=>el(e.projectId,e.sessionId),prompts:{create:t=>Bn(e.projectId,e.sessionId,t),list:()=>tl(e.projectId,e.sessionId),remove:t=>nl(e.projectId,e.sessionId,t),retry:t=>ol(e.projectId,e.sessionId,t),edit:(t,n)=>rl(e.projectId,e.sessionId,t,n),interrupt:t=>sl(e.projectId,e.sessionId,t),hold:t=>il(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function rh(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var EC=["control_plane","provider_ingress","daemon","upstream_port"];function kg(e){return typeof e=="string"&&EC.includes(e)?e:null}function Rg(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 Cg(e,t){let n=(e===void 0?Ne():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=kg(r.headers.get("X-Beeuni-Proxy-Hop"))??kg(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 sh=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,oh=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,ih=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,ah=new Set([22,4096,parseInt(Be.BEEUNI_MASTER,10)]);function MC(e){return oh.test(e)}function Gs(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 OC(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var DC=new Set(["'",'"',"`","<","(","["]),jC=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function $C(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&&DC.has(e[t]);)t++;for(;n>t&&jC.has(e[n-1]);)n--;return e.slice(t,n)}function UC(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var LC=/^\/proxy\/(\d{1,5})(\/.*)?$/,BC=/^\/(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 ch(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:BC.test(t.pathname)}catch{return!1}}function ur(e){if(!e)return null;let t=$C(OC(e.trim())),n=Tg(t);if(n){let r=Gs(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(Be.BEEUNI_MASTER,10);if(s===i){let c=r.pathname.match(LC);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return s=p,o=Gs(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=Gs(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=UC(e);return r&&r!==e?ur(r):null}}function FC(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 NC(e,t){return t.some(([n,r])=>e>=n&&e<r)}function lh(e){let t=[],n=new Set,r=FC(e);sh.lastIndex=0;let s;for(;(s=sh.exec(e))!==null;){let o=ur(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:c}=o;a<1||a>65535||ah.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:NC(s.index,r)}))}return t}function qC(e){return lh(e).length>0}function GC(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function uh(e){return e.trim().toLowerCase().split("_").join("-")}function ph(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function WC(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(uh(n.sandboxId));return`${ph(s)}${t}`}function dh(e){return e.sandboxId.trim().length>0}function ct(e,t,n){let r=Gs(t);if(!dh(n))return yh(e,r);let s=WC(e,r,n);return s||(GC(n.apiBaseUrl)?`http://p${e}-${uh(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${ph(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function KC(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return ct(3211,`/open?path=/workspace/${r}`,t)}function gh(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function VC(e){return`http://localhost:3211${gh(e)}`}function mh(){return"/health"}function HC(e){return ct(3211,mh(),e)}function zC(e,t){return ct(e,"/",t)}function fh(e){let t=ur(e);return!(!t||ah.has(t.port)||ch(e))}function Ig(e,t){if(!e)return e;let n=ur(e);return n?fh(n.originalUrl)?ct(n.port,n.path,t):n.originalUrl:e}function yh(e,t="/"){return`http://localhost:${e}${t}`}var hh=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function Tg(e){let t=e.match(oh);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(ih);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(hh);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 YC(e){try{let t=Tg(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function JC(e){return MC(e)||ih.test(e)||hh.test(e)}function QC(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var lr="/web-proxy/";function XC(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${lr}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(Be.BEEUNI_MASTER,10);return`${ct(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function ZC(e){try{let t=new URL(e),n=t.pathname.indexOf(lr);if(n===-1)return null;let s=t.pathname.slice(n+lr.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 eI(e){try{return new URL(e).pathname.includes(lr)}catch{return e.includes(lr)}}function tI(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 nI(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 bh(e){return{health:t=>Cg(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>ct(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>Ig(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Qe(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Eg(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=uy(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=fy(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return s},set model(y){s=y},get agent(){return o},set agent(y){o=y},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...th(m),...nh(m),...bh(m),...Py(m),...Ry(m),...Fy(m),files:eh(c),..._y(m),get runtime(){return Ae(d("runtime").runtimeUrl)}}}function _h(e){return{apps:{list:()=>Zp(e),create:t=>ed(e,t),get:t=>gs(e,t),update:(...t)=>td(e,...t),access:{get:(...t)=>od(e,...t),update:(...t)=>ad(e,...t),session:(...t)=>cd(e,...t),agents:t=>id(e,t)},remove:t=>nd(e,t),token:t=>rd(e,t),authEnv:t=>sd(e,t),artifacts:{register:t=>ms(e,t),uploadArchive:(...t)=>ld(e,...t),finalize:(...t)=>fs(e,...t)},deployments:{create:(...t)=>ud(e,...t),list:t=>pd(e,t),get:(...t)=>dd(e,...t),logs:(...t)=>gd(e,...t),remove:(...t)=>yd(e,...t)},start:t=>md(e,t),stop:t=>fd(e,t),rollback:(...t)=>hd(e,...t),machines:{list:t=>bd(e,t),start:(t,n)=>Pd(e,t,n),stop:(t,n)=>Sd(e,t,n),restart:(t,n)=>xd(e,t,n),destroy:(t,n)=>wd(e,t,n)},scale:(t,n)=>Ad(e,t,n),exec:(...t)=>vd(e,...t),volumes:{list:t=>kd(e,t),create:(...t)=>Rd(e,...t),update:(...t)=>Cd(e,...t),destroy:(...t)=>Id(e,...t),snapshots:(...t)=>Td(e,...t),snapshot:(...t)=>Ed(e,...t),restore:(...t)=>Md(e,...t),fork:(...t)=>Od(e,...t)}}}}function Ph(e){return{list:()=>$i(e),invite:(...t)=>Bi(e,...t),update:(...t)=>Ui(e,...t),revoke:t=>Li(e,t),pendingInvites:()=>Fi(e),resendInvite:(...t)=>qi(e,...t),revokeInvite:(...t)=>Ni(e,...t),requests:()=>Oi(e),approveRequest:(...t)=>Di(e,...t),rejectRequest:(...t)=>ji(e,...t),groupGrants:()=>Gi(e),attachGroupGrant:(...t)=>Wi(e,...t),updateGroupGrant:(...t)=>Ki(e,...t),detachGroupGrant:t=>Vi(e,t),resourceGrants:{list:()=>Hi(e),create:t=>zi(e,t),remove:t=>Yi(e,t)}}}function Sh(e){return{tokens:{list:()=>Mp(e),create:t=>Op(e,t),revoke:t=>Dp(e,t)},setupLinks:{requestSecret:t=>Gp(e,t),requestConnector:t=>Wp(e,t)},validateManifest:t=>di(e,t),gitToken:()=>gi(e),agentIdentities:()=>Vu(e),secrets:{list:()=>Zi(e),upsert:t=>ea(e,t),setStrategy:(...t)=>ta(e,...t),broker:(...t)=>na(e,...t),remove:t=>ia(e,t),setPersonal:(...t)=>aa(e,...t),removePersonal:t=>ca(e,t),setGitCredential:t=>oa(e,t),listProviderOAuth:()=>ra(e),startProviderOAuth:(...t)=>qr(e,...t),pollProviderOAuth:(...t)=>Gr(e,...t),removeProviderOAuth:t=>sa(e,t)},access:Ph(e)}}function xh(e){return{list:()=>xa(e),listAll:()=>wa(e),reconcile:(...t)=>Aa(e,...t),reconcileMember:(...t)=>va(e,...t),updateCredential:(...t)=>ka(e,...t),revoke:(...t)=>Ra(e,...t),activate:(...t)=>Ca(e,...t),setDefault:(...t)=>Ia(e,...t),rename:(...t)=>Ta(e,...t),share:(...t)=>Ma(e,...t),addComputer:(...t)=>Ea(e,...t),connect:(...t)=>Oa(e,...t),finalize:(...t)=>Da(e,...t)}}function Ws(e){return{catalog:t=>Ut(e,t),tools:()=>Vr(e),search:(...t)=>Sa(e,...t),describe:(...t)=>Hr(e,...t),call:(...t)=>ht(e,...t),callAction:(t,n,r,s)=>ht(e,`${t}.${n}`,r,s),accounts:(...t)=>zr(e,...t),uploadAttachment:(...t)=>Yr(e,...t)}}function Mg(e,t){return{slug:t,run:(r,s,o)=>es(e,t,r,s,o),call:(r,s,o)=>ht(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?Hr(e,`${t}.${r}`):(await Ut(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>zr(e,t),paginate:(r,s,o)=>Za(e,t,r,s,o),uploadAttachment:(r,s)=>Yr(e,r,{...s,connector:t})}}var rI=100,sI=0,oI=new Set(["attachment_size_mismatch","attachment_failed"]),wh=()=>new _("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 Og(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(f=>!f.handedOff);function g(f,b){f.removalDeleted||(f.removalDeleted=!0,Lt(e,b).catch(()=>{}))}function m(){c&&clearTimeout(c);let f=d().map(({item:S})=>S);(f.length!==p.attachments.length||f.some((S,O)=>S!==p.attachments[O]))&&(p={attachments:f});let b=Math.min(...f.filter(S=>S.status==="ready").map(S=>Date.parse(S.attachment.expires_at)));Number.isFinite(b)&&!a&&(c=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:wh()});m()},Math.min(2147483647,Math.max(0,b-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let S of s)S();for(let S of[...o])S()}function y(){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(f){y();let b=d();if(b.length+f.length>20)throw new Error("A message can contain up to 20 attachments");if(f.some(O=>!Number.isSafeInteger(O)||O<=0||O>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(b.reduce((O,C)=>O+C.item.size,0)+f.reduce((O,C)=>O+C,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function w(){for(let f of r.values()){if(i>=n)break;if(f.item.status!=="pending"||!f.item.file||a&&!f.handedOff)continue;let b=f.item.file;i++;let S=++f.generation,O=new AbortController;f.abort=O,f.item={...f.item,status:"uploading",error:void 0};let C=()=>(!a||f.handedOff===!0)&&r.get(f.item.id)===f&&f.generation===S,P,x=0,v,R=()=>{v=void 0,!(!C()||f.item.status!=="uploading"||P===void 0)&&(f.item={...f.item,receivedBytes:P},P=void 0,x=Date.now(),m())},$=D=>Math.floor(D*100/f.item.size);jn(e,b,{resume:f.upload,signal:O.signal,onUpload:D=>{f.upload=D,f.removed&&(O.abort(),g(f,D.attachment_id))},onProgress:D=>{if(!C()||$(D)===$(f.item.receivedBytes)||(P=D,v))return;let E=x+rI-Date.now();if(E<=0)return R();v=setTimeout(R,E),typeof v=="object"&&"unref"in v&&v.unref()},onProcessing:()=>{v&&clearTimeout(v),v=void 0,P=void 0,C()&&(f.item={...f.item,status:"processing",receivedBytes:f.item.size},m())}}).then(D=>{C()&&(f.item={...f.item,status:"ready",attachment:Ah(D),receivedBytes:D.size})}).catch(D=>{D instanceof _&&oI.has(D.code??"")&&(f.upload=void 0),C()&&(f.item={...f.item,status:D instanceof _&&D.code==="ABORTED"?"aborted":"error",error:D instanceof Error?D:new Error(String(D))})}).finally(()=>{i--,v&&clearTimeout(v),f.abort===O&&(f.abort=void 0),m(),w()})}m()}function M(f){h(f.map(S=>S.size));let b=f.map(S=>{let O=`attachment-${++sI}`;return r.set(O,{generation:0,item:{id:O,file:S,filename:S.name,mime:S.type||"application/octet-stream",size:S.size,status:"pending",receivedBytes:0}}),O});return m(),w(),b}function B(f){let b=r.get(f);!b||b.item.status==="ready"||(b.generation++,b.abort?.abort(),b.item={...b.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function F(f,{signal:b}={}){let S=[...f];return new Promise((O,C)=>{let P=()=>{o.delete(R),b?.removeEventListener("abort",v)},x=$=>{P(),C($)},v=()=>x(_e()),R=()=>{let $=!1;for(let E of S){let q=r.get(E);if(!q)return x(new Error("Attachment was removed before it was sent"));if(a&&!q.handedOff)return x(new Error("Attachment controller is disposed"));if(q.item.status==="error"||q.item.status==="aborted")return x(q.item.error??new Error("Attachment upload failed"));q.item.status!=="ready"&&($=!0)}if($)return;let D;try{D=S.map(E=>{let q=Ah(r.get(E).item.attachment);return{type:"file",attachment_id:q.attachment_id,filename:q.filename,mime:q.mime}})}catch(E){return x(E instanceof Error?E:new Error(String(E)))}P(),O(D)};if(b?.aborted)return v();o.add(R),b?.addEventListener("abort",v,{once:!0}),R()})}return{add:f=>M([f])[0],addMany:M,retry(f){let b=r.get(f);if(b?.handedOff||y(),!(!b||b.item.status==="ready"||b.item.status==="uploading"||b.item.status==="processing"||b.item.status==="pending")){if(!b.item.file||b.upload&&Date.parse(b.upload.expires_at)<=Date.now())throw wh();b.item={...b.item,status:"pending",error:void 0},w()}},async remove(f){let b=r.get(f);if(!b)return;b.removed=!0,b.generation++,r.delete(f);let S=b.upload?.attachment_id??b.item.attachment?.attachment_id;S&&b.abort?.abort(),m(),w(),S&&g(b,S)},abort:B,submit(f){if(!a){for(let b of f){let S=r.get(b);S&&(S.handedOff=!0)}m()}},reclaim(f){if(!a){for(let b of f){let S=r.get(b);S&&(S.handedOff=!1)}m()}},whenReady:F,forget(f=d().map(b=>b.item.id)){for(let b of f){let S=r.get(b);S&&(S.generation++,S.abort?.abort(),r.delete(b))}m(),w()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let f of r.values()){if(f.handedOff)continue;f.generation++,f.abort?.abort();let b=f.upload?.attachment_id??f.item.attachment?.attachment_id;b&&e&&Lt(e,b).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(f){return s.add(f),()=>{s.delete(f)}}}}function vh(e){return{attachments:{upload:(...t)=>jn(e,...t),delete:(...t)=>Lt(e,...t),createController:t=>Og(e,t)},get:t=>An(e,t),detail:()=>vn(e),skills:{create:(...t)=>Si(e,...t)},audit:t=>Up(e,t),update:t=>Cn(e,t),archive:()=>In(e),llmCatalog:()=>kn(e),modelPicker:()=>Rn(e),modelAccess:()=>Wn(e),setModelAccess:t=>Kn(e,t),sandboxHealth:()=>En(e),onboardingComplete:(...t)=>Pi(e,...t)}}function kh(e){return{sessions:{list:t=>_t(e,t),listPage:t=>Fc(e,t),create:t=>Pt(e,t),ensureWarm:()=>Yc(e),claimWarm:t=>Jc(e,t)},review:{list:t=>pp(e,t),get:t=>dp(e,t),submit:t=>gp(e,t),act:(...t)=>mp(e,...t),bulkAct:t=>fp(e,t)},approvals:{list:t=>Ji(e,t),resolve:(...t)=>Xi(e,...t),sessionsNeedingInput:t=>Qi(e,t)}}}function Rh(e){return{files:{list:t=>pc(e,t),listDirectory:t=>dc(e,t),read:(t,n)=>mc(e,t,n),search:(...t)=>gc(e,...t),archive:(...t)=>fc(e,...t),archiveRequest:(...t)=>yc(e,...t),history:(...t)=>wc(e,...t)},git:{commits:()=>Pc(e),commit:t=>Sc(e,t),commitDiff:t=>xc(e,t),branches:()=>_c(e),versionDiff:(...t)=>Ac(e,...t),inviteCollaborator:(...t)=>pi(e,...t)},changeRequests:{list:()=>vc(e),get:t=>kc(e,t),update:(...t)=>jc(e,...t),diff:t=>Rc(e,t),mergePreview:t=>Cc(e,t),open:(...t)=>Ic(e,...t),merge:(...t)=>Tc(e,...t),close:(...t)=>Ec(e,...t),reopen:(...t)=>Mc(e,...t),requestChanges:(...t)=>Oc(e,...t)},...kh(e)}}function Ch(e){return{policies:{list:()=>ec(e),set:(...t)=>tc(e,...t)},reminders:{list:()=>kp(e),updateMany:(...t)=>Ap(e,...t),removeMany:(...t)=>vp(e,...t)},triggers:{list:()=>bl(e),eventApps:()=>vl(e),eventTypes:(...t)=>Al(e,...t),create:(...t)=>_l(e,...t),update:(...t)=>Pl(e,...t),remove:(...t)=>Sl(e,...t),fire:(...t)=>wl(e,...t),setActivation:(...t)=>xl(e,...t)},...Rh(e)}}function Ih(e,t){return{connectors:{...Ws(e),list:()=>ja(e),config:(...n)=>qa(e,...n),create:(...n)=>Ka(e,...n),remove:(...n)=>Ha(e,...n),sync:()=>$a(e),auth:{discover:(...n)=>Va(e,...n)},setName:(...n)=>Ga(e,...n),setCredentialMode:(...n)=>Ua(e,...n),setAuthorizationStrategy:(...n)=>La(e,...n),setCredential:(...n)=>Ja(e,...n),deleteCredential:(...n)=>Qa(e,...n),setSensitive:(...n)=>Ba(e,...n),connections:t,policies:{get:(...n)=>Fa(e,...n),set:(...n)=>Na(e,...n)},connect:(...n)=>Wa(e,...n),finalize:(...n)=>Xa(e,...n),discover:{list:(...n)=>Jr(e,...n),sections:(...n)=>za(e,...n),detail:(...n)=>Qr(e,...n)}},...Ch(e)}}function Th(e){return{gateway:{logs:t=>xu(e,t),log:t=>wu(e,t),overview:t=>Au(e,t),series:t=>vu(e,t),breakdown:t=>ku(e,t),sessions:t=>Ru(e,t),errors:t=>Cu(e,t),budgets:()=>Iu(e),setBudget:t=>Tu(e,t),deleteBudget:t=>Eu(e,t),keys:()=>Mu(e),createKey:t=>Ou(e,t),revokeKey:t=>Du(e,t),routing:{get:()=>bu(e),set:t=>_u(e,t),reset:()=>Pu(e),preview:t=>Su(e,t)},playground:(t,n,r)=>ju(e,t,n,r)}}}function Eh(e){return{modelDefaults:{get:()=>Cl(e),set:t=>Il(e,t),clear:t=>Tl(e,t)},setDefaultAgent:t=>Ol(e,t),sandbox:{list:()=>uc(e),snapshots:()=>rc(e),rebuildSnapshot:t=>sc(e,t),fixWithAgent:()=>oc(e),createTemplate:t=>ic(e,t),updateTemplate:(...t)=>ac(e,...t),removeTemplate:t=>cc(e,t),buildTemplate:t=>lc(e,t),setProvider:t=>_i(e,t)},setAgentScope:(...t)=>El(e,...t)}}function Mh(e){return{channels:{slack:{installation:()=>ru(e),connect:t=>su(e,t),mode:()=>ou(e),completeInstall:t=>iu(e,t),manifest:()=>cu(e),disconnect:()=>lu(e),getFile:t=>uu(e,t),uploadFile:t=>pu(e,t)},teams:{completeInstall:t=>au(e,t)},email:{installation:t=>gu(e,t),mode:()=>mu(e),connect:t=>fu(e,t),disconnect:t=>yu(e,t),updatePolicy:(...t)=>hu(e,...t)}},updateFeatureFlag:(...t)=>hi(e,...t),updateExperimentalFeature:(...t)=>bi(e,...t),...Eh(e)}}async function Dg(e){let t=e?.fetch??k().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??k().backendUrl,r=await t(`${St(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new _(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var iI=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function aI(e,t){let n=o=>{let i=iI.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 cI(){return ot()}var Oh=null,Dh=!1;function lI(e){let t=Oh;Oh=e,!(Dh||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(Dh=!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 jh(e,t){t?.global!==!1&&lI(e),Er(e,t);let n=ly(e),{auth:r,accounts:s,iam:o,accountInvites:i}=sy(),{billing:a,sandboxShares:c}=ty(),{projects:p,github:d,connectStatus:g,marketplace:m}=ey();function y(h){let w=xh(h);return{...vh(h),..._h(h),...Sh(h),...Ih(h,w),...Th(h),...Mh(h),connector:M=>Mg(h,M),session:M=>Eg(h,M,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:Ws(),connector:h=>Mg(void 0,h),project:y,session:(h,w)=>Eg(h,w,e,n),github:d,billing:a,sandboxShares:c,connectStatus:g,marketplace:m,notifications:{registerDeviceToken:jd,unregisterDeviceToken:$d,list:Ud,markRead:Ld,preferences:Bd,updatePreferences:Fd,webPushPublicKey:Nd,registerWebPushSubscription:qd,unregisterWebPushSubscription:Gd},mobileClientPolicy:Dg,validateToken:li,runtime:cI}}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 Uh(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function an(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function Lh(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function Bh(e){if(an(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 Fh(e){let t=an(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function Nh(e,t){let n=an(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 qh(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 Gh(e,t){return an(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 Wh(e,t,n){return an(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 Kh(e,t,n){let r=an(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 jg={thinking:!1,toolDetails:!0,assistantMetadata:!0};function uI(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function pI(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 dI(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 gI(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?uI(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=pI(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 mI(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+=gI(e,n.assistantMetadata);for(let s of t)r+=dI(s,n);return r}function Vh(e,t,n=jg){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,30 @@ ${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+=mI(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 Hh(e,t){return`session-${e}.md`}var $g="An error occurred";var fI=["message","error","detail","error_description","msg","errors","data"];function Ug(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 cn(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function yI(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=cn(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function hI(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=bI(e,t);if(n)return n;let r=PI(e,t);return r?r.slice(0,200):void 0}function Qh(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function zh(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function bI(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!Qh(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 _I=["script","style"];function PI(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=_I.find(i=>t.startsWith(`<${i}`,s)&&Qh(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:zh(e,i);continue}r=zh(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function SI(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 xI(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function Yh(e,t,n){if(typeof e=="string")return Ks(e,t,n);if(e&&typeof e=="object")return Vs(e,t,n)}function Ks(e,t,n=new WeakSet){let r=Ug(e);if(!r)return;if(t>=4)return r;let s=SI(r);if(s)return s;let o=cn(r);if(o!==void 0)return typeof o=="string"?Ks(o,t+1,n):o&&typeof o=="object"?Vs(o,t+1,n):String(o);let i=Xh(r);if(i){let a=cn(i);if(a&&typeof a=="object"){let c=Vs(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=yI(r);if(a)return Ks(a,t+1,n)??a}return hI(r)??r}function Vs(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=Yh(i,t,n);if(a)return a}return}let r=e;for(let i of fI){let a=Yh(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return xI(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function he(e){return e?typeof e=="string"?Ks(e,0)??$g:typeof e=="object"?Vs(e,0)??$g:String(e):$g}function Lg(e){let t=wI(e)?.trim();if(!t)return;let n=he(e);if(!(t===n||Ug(t)===n))return t}function wI(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 Xh(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function AI(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 vI(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 Jh(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=vI(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||AI(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function be(e){if(e==null)return;if(typeof e=="string"){let a=Ug(e),c=cn(a)??cn(Xh(a));return c!==void 0?be(c):void 0}if(typeof e!="object")return;let t=e,n=Jh(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=Jh(s);if(a)return a}let o=t.data;if(o&&typeof o.responseBody=="string"){let a=cn(o.responseBody);if(a!==void 0){let c=be(a);if(c)return c}}if(o&&typeof o.message=="string"){let a=be(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=be(a);if(c)return c}}return n}var tb="beeuni-v1-import",kI={harness:tb,harness_version:Rt,adapter_version:"1"},Bg={schema:$e,v:1},RI={opencode:"[Tool execution was interrupted]",pi:"No result provided"},CI="[Old tool result content cleared]",II="The following tool was executed by the user",TI=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"})),EI=e=>TI.get(e)??(e.includes("_")?"mcp":"other"),MI=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),OI=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),X=e=>typeof e=="string"?e:void 0,Ge=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Js=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,nb=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),ln=e=>Ge(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,un=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function Fg(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)=>Fg(r,t[s]));if(!N(e)||!N(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=>Fg(e[r],Js(t,r)))}function zs(e,t){if(Fg(e,t))return;if(e===void 0)return{del:!0};if(!N(e)||!N(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let s=zs(Js(e,r),Js(t,r));s&&nb(n,r,s)}return{sub:n}}function Ys(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=N(e)?{...e}:{};for(let[r,s]of Object.entries(t.sub)){let o=Ys(Js(n,r),s);o===void 0?delete n[r]:nb(n,r,o)}return n}var pr=e=>Object.values(e??{}).find(t=>t.version===Rt),Qs=(e,t)=>({[e]:{version:Rt,...t}}),rb=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},Zh=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),DI=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID});function jI(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=un(e.started_at)??t.created,i=un(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:Zh(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,...rb(d,t)}]:[]),p=un(r?.cleared_at);return{status:"completed",...s,output:Zh(r?.content),title:e.title??"",metadata:a,time:{start:o,end:i,...p!==void 0&&{compacted:p}},...c.length&&{attachments:c}}}function sb(e,t){let n=DI(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},...rb(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:jI(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 $I(e){return cg(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function ob(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:OI.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:un(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:$I(e.error)},...n}}function ib(e,t){return e.role==="assistant"?ob(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 ab(e,t,n){let r=`${e.message_id}-summary`;return{info:ob({...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 UI(e,t,n){let r=n||e.producer.harness===tb;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=pr(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:un(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=sb(d,i);return g===void 0?[]:[Ys(g,pr(d.ext)?.data)]}),c=[{runtime_session_id:o,info:Ys(ib(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=Ys(ab(e,p,i),s?.summary);c.push({runtime_session_id:o,info:d.info,parts:d.parts})}return c}var Ng=e=>Ge(N(e.info)&&N(e.info.time)?e.info.time.created:void 0)??-1/0,Hs=e=>String(N(e.info)?e.info.id:""),cb=(e,t)=>Ng(e)-Ng(t)||(Hs(e)<Hs(t)?-1:Hs(e)>Hs(t)?1:0),eb=e=>{let t=pr(e.ext);return t?t.native_id??null:e.thread_id};function lb(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=>UI(a,eb(i),pr(i.ext)!==void 0))),s=pr(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?eb(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(cb)}}function LI(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:N(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 BI(e){if(!N(e.tokens))return null;let t=e.tokens,n=N(t.cache)?t.cache:{};return{input:Ge(t.input)??0,output:Ge(t.output)??0,cache_read:Ge(n.read)??0,cache_write:Ge(n.write)??0,...Ge(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Ge(e.cost)!==void 0&&{cost:e.cost}}}var FI=e=>({code:X(e.code)||X(e.name)||"UnknownError",message:X(N(e.data)?e.data.message:void 0)??""});function ub(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 NI(e,t,n,r){let s=e.state,o=N(s.time)?s.time:{};N(s.input)||r.tool_input++;let i=N(s.metadata)&&Ge(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(N).map(h=>{let{bytes:w,...M}=ub(h,n,r);return{type:"attachment",...M}}),y=ln(o.compacted);a="complete",c={content:[...X(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...y&&{model_content:[{type:"text",text:CI}],cleared_at:y}}}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)&&!(N(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=RI[n.h];a="error",c={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=ln(o.start),g=ln(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:EI(e.tool),input:p,status:a,...c&&{result:c},...X(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function qI(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:II}});if(!N(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,...ub(e,s,o),...X(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&N(e.state)?NI(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 GI(e){let t=e.map((s,o)=>N(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 WI(e,t,n,r,s,o){let i=N(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],c=i.role==="user"?a.find(v=>N(v)&&v.type==="compaction"):void 0,p=t&&N(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&&N(g.error)?g.error:void 0,y=m?.name==="MessageAbortedError",h=g&&N(g.time)?ln(g.time.completed):null,w=o.live?"streaming":"interrupted",M=g?m?y?"aborted":"error":h?"complete":w:c?w:"complete",B=ln(N(i.time)?i.time.created:void 0)??"",F=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(v=>N(v)&&v.type==="text"&&typeof v.text=="string"?[v.text]:[]).join(""):null,f={tool_input:0,cut_point:0,attachment:0},b=GI(a),S=a.map((v,R)=>qI(v,b[R],c,F,o,f)),O=S.some(v=>v.type==="text"||v.type==="attachment"||v.type==="tool_call"||v.type==="harness"&&v.model_visible),C=!s&&d!=="system"&&(c?M==="complete":!m||y&&O),P=s?"superseded":C||!m?void 0:y?"aborted":"failed_attempt";return c&&N(c)&&X(c.tail_start_id)===void 0&&f.cut_point++,{m:{...Bg,message_id:X(i.id)??"",thread_id:n,seq:r,role:d,kind:c?"compaction":"turn",status:M,in_context:C,...P&&{hidden_reason:P},agent:X(i.agent)??null,...d==="assistant"&&{reply_to:X(i.parentID)??null},model:LI(i),usage:g?BI(g):null,finish:!g||c?null:y?"aborted":m?"error":MI.get(i.finish)??null,error:m?FI(m):null,created_at:B,completed_at:g||c?h:B||null,producer:kI,blocks:S},lost:f}}function KI(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:un(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=zs(t.parts[d],sb(p,i));g&&(p.ext=Qs(s,{data:g}))}):o.parts=t.parts;let a=zs(t.info,ib(e,i));a&&(o.info=a);let c=e.blocks.find(p=>p.type==="compaction");if(n&&c){let p=zs({info:n.info,parts:n.parts},ab(e,c,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Qs(s,{data:o}))}function VI(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(!(!N(o)||o.type!=="tool"||!N(o.state))&&(r?N(o.state.metadata)&&o.state.metadata.sessionId===t:n(o.state).includes(t)))return{row:s,part:o}}}}function pb(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(cb),s=new Map;for(let f of r){let b=s.get(f.runtime_session_id);b?b.push(f):s.set(f.runtime_session_id,[f])}let o=e.root_id,i=s.has(o),a=new Map,c=f=>a.get(f)??(a.set(f,JSON.stringify(f)),a.get(f)),p=new Map;for(let f of s.keys()){let b=i&&f===o?void 0:VI(r,f,c);b&&p.set(f,b)}let d=[...r].reverse().find(f=>f.runtime_session_id===null||!p.has(f.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,y=f=>f!==null&&p.has(f)?f:m,h=ln(r.map(Ng).find(Number.isFinite))??"",w=[];for(let[f,b]of s){if(f!==g&&(f===null||!p.has(f)))continue;let S=f===g,O=S?r.filter(E=>E.runtime_session_id!==g&&y(E.runtime_session_id)===m):[],C=[...O,...b],P=new Set(O),x=new Map,v=new Set;for(let E of C){let q=N(E.info)?E.info:{};if(q.role!=="user"||!Array.isArray(E.parts)||!E.parts.some(V=>N(V)&&V.type==="compaction"))continue;let Q=C.find(V=>!v.has(V)&&V.runtime_session_id===E.runtime_session_id&&N(V.info)&&V.info.role==="assistant"&&V.info.summary===!0&&V.info.parentID===q.id);Q&&(x.set(E,Q),v.add(Q))}let R=[];for(let E of C){if(v.has(E))continue;let q=x.get(E),{m:Q,lost:V}=WI(E,q,S?m:f,R.length+1,P.has(E),n);if(KI(Q,E,q,f,n.h),Q.in_context)for(let _n of["tool_input","cut_point","attachment"])n.counts[_n]+=V[_n];R.push(Q)}let $=f===null?void 0:p.get(f),D=R.find(E=>E.role==="user"&&E.kind==="turn");w.push({...Bg,thread_id:S?m:f,parent_thread_id:$?y($.row.runtime_session_id):null,spawned_by:$&&typeof $.part.callID=="string"?{message_id:X($.row.info?.id)??"",call_id:$.part.callID}:null,agent:D?.agent??null,title:null,created_at:R[0]?.created_at||h,messages:R,ext:Qs(n.h,f===null?{}:{native_id:f})})}w.sort((f,b)=>f.parent_thread_id===null?-1:b.parent_thread_id===null?1:F(f)-F(b));let M=w[0]?.messages.filter(f=>f.role==="user"&&f.kind==="turn").at(-1),B=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...Bg,session_id:e.session_id,title:null,created_at:h,restore_grade:B?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:M?.agent??null,model:M?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:w,...g!==o&&{ext:Qs(n.h,{data:{root_id:o}})}};function F(f){return r.findIndex(b=>b.runtime_session_id===f.thread_id)}}var qg={schema:$e,v:1},HI=Object.freeze({}),db=new WeakMap;function mb(e){let t=db.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=pb({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return db.set(e,{state:e.state,block:o}),o}var gb=new WeakMap;function We(e){let t=gb.get(e);if(t)return t;let n={...qg,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:Rt}},messages:[{...qg,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:r}=lb({...qg,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[n]}),s=r[0].parts[0];return gb.set(e,s),s}var Ke=e=>typeof e=="object"&&e!==null&&e.type==="tool_call";function fb(e){let t=We(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:HI}var yb={};function Y(e,t){for(let n of t)yb[n]=e}Y("read",["read"]);Y("list",["list","ls"]);Y("glob",["glob"]);Y("grep",["grep"]);Y("write",["write"]);Y("edit",["edit","multiedit","morph_edit"]);Y("apply_patch",["apply_patch","patch"]);Y("bash",["bash"]);Y("web_search",["web_search","websearch","image_search"]);Y("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);Y("media",["image_gen","video_gen"]);Y("show",["show","show_user","presentation_gen"]);Y("task",["task"]);Y("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"]);Y("todowrite",["todowrite","todo_write","todoread"]);Y("question",["question","ask"]);Y("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);Y("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"]);Y("automations",["triggers"]);Y("skill",["skill"]);Y("context",["prune","distill","compress","context_info"]);Y("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var zI=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function le(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=yb[t];if(n)return n;for(let[r,s]of zI)if(t.startsWith(r))return s;return"other"}function Ve(e){for(let t of[e?.filePath,e?.file_path,e?.path])if(typeof t=="string"&&t)return t}var YI=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function JI(){return new RegExp(`(^|\\s)([-+]?)(${YI.join("|")}):("[^"]*"|\\S+)`,"gi")}function QI(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function XI(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function ZI(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function eT(e){return ZI(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function hb(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function dr(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(JI(),(s,o,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=eT(c);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(QI(),"$1").replace(XI(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${hb(n)}`:r:n.length>0?hb(n):t}var tT=/\s/,nT=/\w/;function ge(e){return e!==void 0&&tT.test(e)}function gr(e){return e===`
75
+ `||e==="\r"||e==="\u2028"||e==="\u2029"}function Gg(e){return e!==void 0&&nT.test(e)}function It(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(rT(n.charCodeAt(0))):n;return t}function rT(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 He(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function bb(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return He(e.slice(t))}function mr(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 Wg(e,t){let n=mr(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 Kg(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 _b(e,t){let n=Kg(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function Pb(e,t){let n=Kg(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 Sb(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=Kg(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 xb(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 fr(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&&ge(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function wb(e,t,n){let r=It(t),s=It(n);for(let o of It(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 Ab(e,t){let n=It(e),r=t.map(It),s=e.length,o=c=>{let p=c;for(;p<s&&ge(e[p]);)p++;return p},i=c=>{for(let p=c;p<s;p++)if(gr(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&&!gr(e[m]);)m++;for(;m>g+1&&ge(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!gr(e[m]))return e[m];return null}}a=i(c)}return null}function vb(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=ge(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"||!ge(e[a-1]))continue;let c=a+1;if(ge(e[c])){for(;c<t&&ge(e[c]);)c++;Gg(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]+(gr(e[a])?1:0);let o=(a,c)=>s[c]===s[a],i=a=>{let c=a+1;for(;ge(e[c]);)c++;let p=c;for(;p<t&&Gg(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&&ge(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(!gr(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function kb(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&ge(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&ge(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!Gg(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&ge(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function Rb(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 Cb(e){return Rb(e,!0)}function Ib(e){return Rb(e,!1)}function sT(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Tb(e,t){let n=It(e),r=It(t),s=e.length,o=i=>{let a=i;for(;a<s&&ge(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(!ge(e[p])){p++;continue}let d=o(p);if(sT(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var Eb=new Set(["read","glob","grep","list"]);function Z(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function oT(e){return Eb.has(le(e))}function iT(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 Vg(e){if(!e)return"";let t=He(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Xs(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Zs(e){let n=(e.state??{}).input??{};switch(Z(e.tool)){case"read":case"edit":case"write":case"morph_edit":{let o=n.filePath??n.file_path??n.path;return o?Vg(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?`"${Xs(String(o),40)}" in ${Vg(String(i))}`:o?`"${Xs(String(o),60)}"`:""}case"list":return n.path?Vg(String(n.path)):"";case"bash":return Xs(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 Xs(o==="query"&&dr(i)||i,60)}return""}var Mb={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 aT(e,t={}){let n=Ke(e)?We(e):e,r={...Mb,...t},s=Z(n.tool),o=Zs(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 ve(e){return e.type==="text"}function ke(e){return e.type==="reasoning"}function oe(e){return e.type==="tool"}function zg(e){return e.type==="file"}function cT(e){return e.type==="agent"}function lT(e){return e.type==="compaction"}function uT(e){return e.type==="snapshot"}function pT(e){return e.type==="patch"}function dT(e){return e.type==="step-start"||e.type==="step-finish"}function gT(e){if(ve(e)||ke(e))return e.text}function mT(e){if(!zg(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function fT(e){let t=[],n=[];for(let r of e)zg(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function yT(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function hT(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var bT=new Set(["todoread","context_info"]);function Ob(e){return!bT.has(Ke(e)?e.name:e.tool)}var _T=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 Yg(e){let t=Ke(e)?We(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 PT(n,t.state)}function PT(e,t){let n=Z(e);if(_T.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 ST(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return he(n.error)}}function xT(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)oe(r)&&Ob(r)&&t.push(r);return t}function wT(e,t={}){switch(Z(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:$b(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 AT(e,t)}}function AT(e,t){switch(le(e)){case"read":return{icon:"glasses",title:"Read",subtitle:Db(Ve(t))};case"list":return{icon:"list",title:"List",subtitle:jb(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:Hg(Ve(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Hg(Ve(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function Db(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Hg(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 jb(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function vT(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 yr(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 $b(e){let t=yr(e.description);if(t)return t;let n=yr(e.title,80);if(n)return n;let r=yr(e.message);if(r)return r;let s=yr(e.prompt);if(s)return s;let o=yr(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function kT(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function RT(e,t){return e.find(n=>n.tool?.callID===t)}function CT(e,t){return e.find(n=>n.tool?.callID===t)}var IT=/\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 TT(e){return e?e.replace(IT,""):""}var ET={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"},MT={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 OT(e){return e.replace(/^oc[-_]/,"")}function Jg(e){return OT(e).replace(/-/g,"_")}function Qg(e){return Jg(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function eo(e){return{label:ET[Jg(e)]??Qg(e),category:MT[le(e)]}}var DT=256*1024;function jT(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function $T(e){if(e===void 0)return{};if(e.length>DT)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function UT(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?he(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var ae=e=>typeof e=="string"?e:void 0,to=e=>typeof e=="number"?e:void 0,no=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function Xg(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var LT=new Set(["add","update","delete","move"]);function BT(e,t,n){if(e==="apply_patch"){let c=(Array.isArray(n.files)?n.files:[]).flatMap(p=>{let d=no(p),g=d&&(ae(d.relativePath)||ae(d.filePath));if(!d||!g)return[];let m=ae(d.type);return[Xg({path:g,type:m&&LT.has(m)?m:void 0,before:ae(d.before),after:ae(d.after),patch:ae(d.patch)??ae(d.diff),additions:to(d.additions),deletions:to(d.deletions),movePath:ae(d.movePath)})]});return c.length?c:void 0}let r=Ve(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[Xg({path:r,after:ae(t.content)})];if(e!=="edit")return;let s=no(n.filediff),o=s?void 0:ae(n.patch),i=o?FT(o):void 0;return[Xg({path:r,before:ae(s?.before)??ae(t.oldString),after:ae(s?.after)??ae(t.newString),patch:o,additions:to(s?.additions)??i?.additions,deletions:to(s?.deletions)??i?.deletions})]}function FT(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 NT(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function Ub(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=$T(r),i=jT(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=UT(s);m&&(i="error",a=m)}let c=le(e),p=t.input??{},d="metadata"in t&&no(t.metadata)||{},g=no(d.diagnostics);return{name:e,kind:c,title:n||eo(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:BT(c,p,d),diff:ae(d.patch)??ae(d.diff),diagnostics:g,answers:c==="question"?NT(d):void 0,childSessionId:Yg({tool:e,state:t})}}function qT(e){let t=Ke(e)?We(e):e;return Ub(t.tool,t.state)}function GT(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function WT(e){return{kind:"reasoning",id:e.id,text:e.text}}function KT(e){return{kind:"tool",id:e.id,tool:Ub(e.tool,e.state)}}function VT(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 HT(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function zT(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function YT(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function JT(e){return{kind:"agent",id:e.id,name:e.name}}function QT(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:he(e.error),createdAt:e.time.created}}function XT(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function ZT(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function eE(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Zg(e){switch(e.type){case"text":return GT(e);case"reasoning":return WT(e);case"tool":return KT(e);case"file":return VT(e);case"subtask":return HT(e);case"patch":return zT(e);case"snapshot":return YT(e);case"agent":return JT(e);case"retry":return QT(e);case"compaction":return XT(e);case"step-start":return ZT(e);case"step-finish":return eE(e);default:return{kind:"unknown",raw:e}}}function tE(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=be(e);return{name:t,message:n?.message||he(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function nE(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function Lb(e){let t=e.parts.map(Zg),n=e.info.role==="assistant"?e.info.error:void 0,r=tE(n),s=!r&&!t.some(nE);return{parts:t,error:r,isEmpty:s}}var em=Fe+BigInt(1),Bb=em/BigInt(2);function ro(e){return BigInt(Math.trunc(e))*Ht}function tm(e,t){let r=t-(t&Fe)+e;return r-t>Bb?r-=em:t-r>Bb&&(r+=em),r}function Fb(e,t){let n=vt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return tm(n,t);let s=ro(r),o=tm(n,s);return(o>s?o-s:s-o)<=rt?o:s}function Nb(e){return vt(e)===null?1:0}function qb(e,t){return e<t?-1:e>t?1:0}function rE(e,t){return Gb(e,t,ro(Date.now()))}function sE(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 ro(t??Date.now())}function Gb(e,t,n){let r=Nb(e.info.id),s=Nb(t.info.id);if(r!==s)return r-s;if(r===0){let a=Fb(e,n),c=Fb(t,n);return a!==c?a<c?-1:1:qb(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:qb(e.info.id,t.info.id)}function oE(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=sE(e),s=[...e].sort((d,g)=>{let m=n.get(d.info.id),y=n.get(g.info.id);return m!==void 0&&y!==void 0?m-y:m!==void 0?1:y!==void 0?-1:Gb(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 y=i.get(g.parentID);if(y){y.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let y=c[c.length-1];y&&y.userMessage.info.id===g.parentID?y.assistantMessages.push(d):c.push({userMessage:aE(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 hr=new Map,iE=256;function aE(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=hr.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(hr.size>=iE){let a=hr.keys().next().value;a!==void 0&&hr.delete(a)}return hr.set(s,i),i}function cE(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function lE(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(ve(n)&&n.text?.trim())return n}}function uE(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function pE(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!oe(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 dE(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 gE(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 Wb(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(...Wb(e,s));return r}function Kb(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function mE(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&&Kb(n.error)}return!1}function so(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nm(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 fE(e){return!!e&&(nm(e)||Hb(e)!==null)}function rm(e){let t=Ke(e)?We(e):e,n=Vb.get(t);if(n&&n.state===t.state)return n.outcome;let r=yE(t);return Vb.set(t,{state:t.state,outcome:r}),r}var Vb=new WeakMap;function yE(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(nm(n))return"failed";let r=hE(n);return r===void 0?"ok":bE(r)?"failed":_E(r)}function hE(e){try{return JSON.parse(e)}catch{return}}function bE(e){return so(e)&&e.success===!1&&typeof e.error=="string"}function _E(e){let t=so(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 Hb(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!so(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=fr(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 PE(e){return kb(e).replace(/\s+/g," ").trim()||e.trim()}function SE(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!so(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=fr(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 zb=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),xE={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 wE(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&dr(t)||t}function AE(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 wE(r,s.trim())}}function sm(e){if(ke(e))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!oe(e))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let t=de(e.tool),n=xE[t],r=e.state?.input;return n?{verb:n.verb,running:n.running,object:AE(r,n.objectKeys),tier:zb.has(t)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:t,tier:"primary"}}function vE(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(sm(o).tier==="plumbing"){r=!0;continue}if(ke(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,oe(o)&&rm(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function om(e){return`${e} ${e===1?"step":"steps"}`}function kE(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${om(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${om(n)}`:s===0?`${om(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function RE(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 CE(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function IE(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 TE(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=Cb(n),n=Ib(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 EE(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=fr(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 br(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function oo(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(br(i[1]),br(i[2]),i[3]?br(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(br(i[2]),br(i[1])),n.length>=t)return n}return n}function Yb(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 io(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 im(e){if(!e)return[];let t=Yb(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)?io(s.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=io(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)?io(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=io(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=oo(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function ao(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function ME(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return ao(e)}}function OE(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function DE(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 Jb(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 Qb(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=Tb(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function jE(e,t){let n=Xb(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?Qb(r,Jb(t)):[]}function Xb(e){if(!e)return null;let t=Yb(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=oo(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 $E(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 UE={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 co(e){return UE[le(e)]}function Pr(e){let t=Z(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var LE={run:"Terminal",memory:"Memory"};function BE(e){let t=co(e);return(t==="hidden"?void 0:LE[t])??Pr(e)}function _r(e,t,n){return e===1?t:n}function am(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 t_(e){return e.length?Zs(e[0]):""}function Re(e){return(e.state??{}).input??{}}var FE={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 NE(e){let t=Z(e.tool);if(t==="agent_task_update"||t==="task_update")switch(Re(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return FE[t]??"message"}function Zb(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 qE(e){let t=Z(e.tool);if(t==="triggers"){let r=Re(e).action||"list";return Zb(r)}let n=t.match(/^trigger_(.+)$/);return Zb(n?n[1]:"list")}var GE={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 WE(e){return GE[Z(e.tool)]??"read"}var KE={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function VE(e){return KE[Z(e.tool)]??"open"}function pn(e){return e.every(t=>t===e[0])}var HE={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function zE(e){if(Z(e.tool)!=="memory")return"read";let n=Re(e).command;return n&&HE[n]||"unknown"}var YE={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},JE={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 QE(e){let t=He(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function XE(e){let t=Re(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 ZE(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return QE(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=$E(o);return i?ao(i):"a link"}return""}function ZE(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function eM(e){let t=Re(e).action;return t&&YE[t]||"Worked on an image"}function tM(e){let t=Re(e).action;return t&&JE[t]||"Worked on a presentation"}function nM(e){return e.slice(0,e.indexOf(":"))}var rM={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},sM={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 oM(e){let t=Z(e.tool);if(t==="image_gen"){let n=Re(e).action;return n&&rM[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=Re(e).action;return n&&sM[n]||"presentation:unknown"}return"shown:result"}var iM=new Set(["create_slide","export_pdf","export_pptx"]);function aM(e){let t=Z(e.tool);if(t==="image_gen")return"image";if(t==="video_gen")return"video";if(t==="presentation_gen"){let n=Re(e).action;return n?iM.has(n)?"presentation":null:"presentation"}return null}var cM={"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`},e_={image:"image",video:"video",presentation:"presentation",shown:"result"};function lM(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[nM(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${_r(s,e_[r],`${e_[r]}s`)}`)}),`Worked on ${am(n)}`}function cm(e,t){let n=t.length,r=t_(t);switch(e){case"explore":{let s=t.filter(o=>Z(o.tool)==="read").length;return s===n?`Read ${n} ${_r(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=>Ve(Re(i))).filter(Boolean)).size||n,o=t.every(i=>Z(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=c=>{let p=Z(c.tool);return p==="web_search"||p==="websearch"||p==="image_search"},o=t.filter(s).length;if(o===n)return`Searched the web \xB7 ${n} ${_r(n,"query","queries")}`;if(o===0)return`Read ${n} ${_r(n,"page","pages")}`;let i=new Set;for(let c of t)if(s(c)){let p=c.state?.output;for(let d of im(p).flatMap(g=>g.sources))d.url&&i.add(d.url)}else{let p=c.state?.input?.url;typeof p=="string"&&p&&i.add(p)}let a=i.size||n;return`Searched and read ${a} ${_r(a,"source","sources")}`}case"create":{if(n===1){let o=t[0],i=Z(o.tool);if(i==="image_gen")return eM(o);if(i==="video_gen")return"Made a video";if(i==="presentation_gen")return tM(o);let a=XE(o);return a?`Showed you ${a}`:"Showed you the result"}let s=t.map(oM);return pn(s)?cM[s[0]](n):lM(s)}case"plan":return n===1?"Planned the work":`Planned the work \xB7 ${n} steps`;case"delegate":{let s=t.map(NE);if(pn(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(zE);if(pn(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(WE);if(pn(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(qE);if(pn(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(VE);if(pn(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 ${Pr(t[0].tool)}`;let s=Array.from(new Set(t.map(o=>Pr(o.tool))));return s.length===1?`Used ${s[0]} \xB7 ${n} times`:`Used ${am(s)}`}}}function lm(e,t){let n=t_(t);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(t.length===1){let r=Z(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=>Pr(i.tool))));return`Couldn't finish using ${am(o)}`}}}function uM(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function pM(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 n_(e,t){let n=uM(t);return{id:t[0].callID,family:e,label:n==="error"?lm(e,t):cm(e,t),parts:t,status:n,durationMs:n==="running"?void 0:pM(t)}}function um(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(n_(n,r)),n=null,r=[]};for(let o of e){let i=co(o.tool);if(i!=="hidden"&&!ys(o)){if(Kd(o.tool)){s(),t.push(n_(i,[o]));continue}i!==n&&(s(),n=i),r.push(o)}}return s(),t}function r_(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function dM(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 um(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(ke(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=r_(a);continue}if(o(),oe(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 gM=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function mM(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 fM(e){let t=e.flatMap(s=>{let o=mM(s);return o?[o]:[]}).join(" ").trim();return t?gM.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function c_(e){return e?.info?.time??{}}function yM(e){let t=c_(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var lo=6e4,hM=10080*lo,s_=1440;function o_(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 bM(e,t){let n=t.getTime()-e.getTime(),r=n/lo,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<s_)return s(Math.round(r/60),"hour");let o=(n-(o_(t)-o_(e)))/lo;return s(Math.round(o/s_),"day")}function l_(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 i_=new Map;function _M(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=i_.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),i_.set(r,s)),s}function uo(e,t,n){return _M(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?PM(r.value,n):r.value).join("")}function PM(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function a_(e,t){return uo(e,{year:"numeric"},t)}function SM(e,t,n={}){let r=l_(e);if(!r)return"";let s=i=>uo(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<lo?"just now":o<hM?bM(r,new Date(t)):s(a_(r,n)!==a_(new Date(t),n))}function xM(e,t={}){let n=l_(e);if(!n)return"";let r=uo(n,{month:"long",day:"numeric",year:"numeric"},t),s=uo(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function wM(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!Vd(o)){if(ve(o)){s(),n.push({kind:"text",part:o});continue}if(oe(o)&&(Hd(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function AM(e){let t=de(e);return t==="show"||t==="show_user"}function vM(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"&&AM(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var kM=["title","description","path","url","content","language","aspect_ratio","attachment"];function u_(e,t){if(!t||typeof t!="object")return null;let n=t;if(Vn(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of kM){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function RM(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 CM(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=RM(s.items),i=o?o.map(a=>u_(n.callID,a)).filter(a=>!!a):[u_(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 pm(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var IM=e=>e.time?.completed;function TM(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function EM(e,t){let n=e.userMessage.info.id;return t.pendingTurnIds.has(n)||e.assistantMessages.length===0&&t.pendingPromptIds.has(n)}function MM(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=>EM(r,e));return n<=0?null:e.turns[n-1].userMessage.info.id}function OM(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function DM(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 jM(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:pm({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function $M(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 UM(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(!IM(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 LM(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 BM(e,t){return!t||!e?!1:e.type!=="idle"}function FM(e,t){return!e&&!!t}function NM(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return be(n.error)?.message||he(n.error)}}function qM(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Lg(n.error)}}function GM(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return be(n.error)}}function dm(e){if(e){if(oe(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(ke(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(ve(e))return"Gathering thoughts..."}}function WM(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,s=oe(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=dm(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let o=dm(r);if(o)return o}return"Figuring out what\u2019s next..."}function gm(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 KM(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 VM(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function HM(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function zM(e){if(!e||e.type!=="retry")return;let t=e,n=he(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:be(t.message)}}function YM(e){if(!(!e||e.type!=="retry"))return he(e.message)}function JM(e){return(e.info.summary?.diffs?.length??0)>0}function p_(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=de(e.part.tool);return t==="show"||t==="show_user"}function QM(e){return e.kind==="text"&&!e.part.text?.trim()}function XM(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(p_(o)||QM(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):p_(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function ZM(e){let t=e==null?"":gm(e);return t?`Worked for ${t}`:"Worked"}function d_(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>ve(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 oe(s)&&s.tool==="bash"}function eO(e){if(d_(e))return e.assistantMessages[0].parts[0]}function tO(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=Sb(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 nO(e){return e?e.split(`
82
+ `).filter(n=>n.trim()).length<=3:!1}function rO(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 sO(e){if(!e)return[];let t=[],n=e.split(`
84
+ `).filter(r=>r.trim());for(let r of n){let s=vb(r);if(s){let o=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...s,sessionId:o?.[0]})}}return t}var lt={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 oO(e,t){let n=lt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function iO(e,t){return t?"failed":e?"running":"done"}var aO={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function cO(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.beeuni\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function lO(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(wb(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
86
86
  `).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
87
87
  `)};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(`
88
+ `)){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 uO={add:{...lt.write,icon:"create"},delete:{...lt.delete,icon:"delete"},move:{...lt.rename,icon:"edit"},update:{...lt.edit,icon:"edit"}},g_={...lt.change,icon:"edit"};function pO(e){if(e.length===0)return g_;let t=m_(e[0]);for(let n=1;n<e.length;n++)if(m_(e[n])!==t)return g_;return uO[t]}function m_(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function dO(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 gO(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 mO(e){if(!e)return null;let t=mr(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=Wg(e,"content");if(r!==null){let o=r.split(`
89
89
  `).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(`
90
+ `);return{path:n,type:"file",content:o}}let s=Wg(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 fO(e){let t=Pb(e,"skill_content");return t!==null?t.trim():e}function f_(e){let t=mr(e,"<skill_files>","</skill_files>");return t===null?[]:xb(t,"<file>","</file>").map(n=>n.trim())}function yO(e){let t=_b(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 hO(e){return Ab(e,["Base directory","Directory","Skill directory"])?.trim()??""}function y_(e){return He(yO(e)||hO(e))}function bO(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return He(n.trim())}return""}var _O="skills";function PO(e){let t=bb(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?`${_O}/${r}`:""}function SO(e,t,n){let s=He(t?.trim()??"")||y_(e)||PO(n),o=f_(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 xO=4e3;function Sr(e,t=xO){return e.length>t?`${e.slice(0,t)}
92
+ \u2026`:e}function h_(e){if(e!==void 0)try{return Sr(JSON.stringify(e,null,2))}catch{return}}function H(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function Tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function wO(e){let t=H(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=Tt(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=Tt(o)??{};return{title:H(i.title)??"",url:H(i.url,i.link)??"",snippet:H(i.snippet,i.description,i.source)}});return{kind:"web-search",query:H(n.query)??t,results:s.length>0?s:void 0,answer:H(n.answer)}}var AO=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function fm(e){let t=e.match(AO);return t?Number(t[1]):void 0}function vO(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 kO=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function RO(e){let t=-1;for(let n of kO){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var CO=/\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 IO(e){return e.replace(CO,"")}function TO(e){let t=H(e.input?.command)??"",n=e.output??"",r=fm(n),o=IO(RO(vO(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 ym(e){return H(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function EO(e){let t=e.status==="error"?e.error:e.output&&Sr(e.output)||void 0;return{kind:"file-read",path:ym(e),preview:t}}function MO(e){let t=H(e.input?.content),n=e.status==="error"?e.error:Sr(t??e.output??"")||void 0;return{kind:"file-write",path:ym(e),preview:n}}var OO=256*1024;function DO(e,t){if(e.length+t.length>OO)return;let n=e.split(`
93
93
  `),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$);})();
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 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 jO(e){let t=H(e?.oldString),n=H(e?.newString);return t!==void 0&&n!==void 0?[[t,n]]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(s=>{let o=Tt(s),i=o&&H(o.oldText),a=o&&H(o.newText);return i!==void 0&&a!==void 0?[[i,a]]:[]})}function $O(e){let t=jO(e.input),n=t.map(([s,o])=>DO(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:ym(e),diff:r}}var __=/^Found\s+(\d+)\s+match/i,UO=/^(\/[^:]+?):\s*/,b_=/Line\s+(\d+):/g;function LO(e){let t=e.trim(),n=t.match(__),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(UO);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(b_.lastIndex=0;(g=b_.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 y=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,y).trim();s.push({path:c,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return s}function BO(e){return e.trim().split(`
95
+ `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function FO(e){let t=H(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=__.test(e.output.trim())?LO(e.output):BO(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function NO(e){let t=H(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=H(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function mm(e){let t=Tt(e)??{};return{content:H(t.content)??"",status:H(t.status)??"pending",priority:H(t.priority)}}function qO(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(mm)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(mm)};let n=Tt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(mm)}:{kind:"todo",items:[]}}function GO(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=Tt(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let c=Tt(a),p=c&&H(c.label);return p?[{label:p,description:c?H(c.description):void 0}]:[]});return{question:H(s.question)??"",header:H(s.header),options:i}})}}function WO(e){let n=e.input&&Object.keys(e.input).length>0?h_(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Sr(e.outputParsed):h_(e.outputParsed):e.outputText!==void 0?r=Sr(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function P_(e){switch(le(e.name)){case"web_search":return wO(e);case"bash":return TO(e);case"read":return EO(e);case"write":return MO(e);case"edit":return $O(e);case"grep":case"glob":return FO(e);case"task":return NO(e);case"todowrite":return qO(e);case"question":return GO(e);default:return WO(e)}}var KO=new Set(["AbortError","MessageAbortedError"]),VO=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],HO=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function S_(e){let t=e.toLowerCase();return HO.some(n=>t.includes(n))?!1:VO.some(n=>t.includes(n))}function zO(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 xr(e){if(typeof e=="string")return S_(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&KO.has(n))return!0;let r=zO(t);return typeof r=="string"?S_(r):!1}var x_=["user","runtime-disposed","orphan-finalized","wake"],YO=["orphan-finalized","wake"];function JO(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 x_.includes(n)?n:void 0}function Ar(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 hm(e){let t=Ar(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 QO=hm;function po(e){let t=hm(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var XO=po;function w_(e){return po(e)!==null}var ZO=w_,eD=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],tD=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],nD=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function A_(e){return nD.test(Ar(e))}function dn(e){let t=Ar(e);return t?A_(t)||eD.some(n=>n.test(t)):!1}var rD=/server url not ready|sandbox is still loading/i;function sD(e){return rD.test(Ar(e))||dn(e)}var wr=class extends Error{constructor(t){let n=t?.trim();super(n&&dn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function v_(e){let t=po(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=Ar(e);return dn(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 oD=v_;function bm(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`${tt()}/p/${e.external_id}/${Be.BEEUNI_MASTER}`}function iD(e,t){return e.external_id?`${tt()}/p/${e.external_id}/${t}`:null}async function aD(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function k_(e){let t=await xt();if(t)return{sandbox:t.sandbox,created:!1};let r=(await yt())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await Pt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await Xe(r.project_id,s.session_id))?.sandbox??null;return{sandbox:tg(r,s,o),created:!0}}async function cD(){return(await xt().catch(()=>null))?.sandbox??null}async function lD(e){return{sandbox:(await k_(e)).sandbox}}async function uD(e){let t=zn(e);return t?(await xt(t).catch(()=>null))?.sandbox??null:null}async function pD(e,t){throw await xt(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function dD(e){let t=zn(e);return(await ng().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function gD(){return null}async function mD(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await xt(e);if(!t)throw new Error("Project session sandbox not found");await Fn(t.project.project_id,t.session.session_id)}async function fD(e){if(!e)throw new Error("No sandbox selected to stop");let t=await xt(e);if(!t)throw new Error("Project session sandbox not found");await Nn(t.project.project_id,t.session.session_id)}async function yD(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function hD(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function _m(e,t,n){let r=bm(e),s=await j(`${ce(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 bD(e,t){return _m(e,`/beeuni/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function _D(e,t,n,r="member"){await _m(e,`/beeuni/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function PD(e,t,n){await _m(e,`/beeuni/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var Pm="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function SD(e){throw G("getInvite",Pm)}async function xD(e){throw G("acceptInvite",Pm)}async function wD(e){throw G("declineInvite",Pm)}async function AD(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function vD(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function kD(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function RD(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function CD(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function ID(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}async function R_(e){let t=e?`?channel=${e}`:"",r=await(await Me(`${tt()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await Sm(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function Sm(e){let t=e?`?channel=${e}`:"";return(await(await Me(`${tt()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function C_(){return(await Me(`${tt()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}var gn=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function I_(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 T_(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function E_(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 ie(e,t,n){let r=n?.body!==void 0,s=await fetch(`${St(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:I_(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 T_(s);if(!s.ok)throw new gn(E_(s,o),s.status,o);return o}function TD(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 M_(e,t){return ie(`/marketplace/items${TD(t)}`,e)}function O_(e){return ie("/marketplace/marketplaces",e)}function D_(e,t){return ie(`/marketplace/items/${encodeURIComponent(e)}`,t)}function j_(e,t,n){return ie(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function $_(e,t){return ie("/access/check-email",t,{method:"POST",body:{email:e}})}function U_(e,t){return ie("/access/request-access",t,{method:"POST",body:e})}function L_(e){return ie("/auth/logout",e,{method:"POST",body:{}})}function B_(e,t){return ie(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function F_(e,t){return ie("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function N_(e,t){return ie(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function q_(e,t){return ie(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function G_(e,t,n={}){return ie(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function W_(e,t){return ie(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function K_(e,t,n,r){return ie(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function V_(e,t){return ie(`/p/public-share/${encodeURIComponent(e)}`,t)}function H_(e,t,n){return ie(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function z_(e,t){return ie("/system/demo-request",t,{method:"POST",body:e})}async function Y_(e,t,n){let r=await fetch(`${St(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${qt(t)}`,{headers:I_(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await T_(r);throw new gn(E_(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 J_(e,t){throw G("buildPublicTemplateUrl")}async function Q_(e,t,n){throw G("getPublicTemplate")}var ED="beeuni:connect-link:";function xm(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`${ED}${t.toString(36)}${n.toString(36)}`}function MD(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(xm(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(xm(i));return}return c}catch{return}},o=(i,a)=>{if(t)try{t.setItem(xm(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 X_="Could not start the connect flow.";async function OD(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:X_}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:X_};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var Z_=3e3,eP=5e3,tP=5*6e4;function DD(e,t){let n=e===0?Z_:eP;return t+n>tP?null:n}function jD(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 bV="1";var $D="beeuni.query-cache";function rP(e){return!!e&&typeof e.then=="function"}function nP(e){return rP(e)?e:Promise.resolve()}function UD(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 LD(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=$D,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,y=null,h=Promise.resolve(),w=()=>{try{return nP(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},M=(C,P)=>{if(!P)return 0;let x;try{x=JSON.parse(P)}catch{return w(),0}if(!x||x.v!==s||x.user!==n||!Array.isArray(x.queries)||p()-x.at>o)return w(),0;let v=0;for(let R of x.queries){if(!R||!Array.isArray(R.k)||R.d===void 0||typeof R.t!="number"||p()-R.t>o||!r(R.k))continue;let $=C.getQueryState(R.k);$&&$.data!==void 0&&$.dataUpdatedAt>=R.t||(C.setQueryData(R.k,R.d,{updatedAt:R.t}),C.invalidateQueries?.({queryKey:R.k,exact:!0,refetchType:"none"}),v+=1)}return v},B=C=>C.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,x)=>x.t-P.t),F=(C,P)=>{let x=[],v=0;for(let R of C){let $=JSON.stringify(R).length+1;v+$>P||(x.push(R),v+=$)}return x},f=async C=>{let P=F(B(C),i);for(;;){let x={v:s,user:n,at:p(),queries:P};try{await nP(t.setItem(d,JSON.stringify(x)));return}catch{if(P.length===0)return;P=P.slice(0,Math.floor(P.length/2))}}},b=()=>{y!==null&&(clearTimeout(y),y=null)},S=()=>{b();let C=g;return!C||!m||(m=!1,h=h.then(()=>f(C)).catch(()=>{})),h},O=()=>{m=!0,y===null&&(y=setTimeout(()=>{y=null,S()},a))};return{storageKey:d,restore(C){let P;try{P=t.getItem(d)}catch{return 0}return rP(P)?P.then(x=>M(C,x)).catch(()=>0):M(C,P)},persist(C){g=C,m=!0;let P=C.getQueryCache().subscribe(x=>{x.type!=="updated"&&x.type!=="removed"&&x.type!=="added"||r(x.query.queryKey)&&O()});return()=>{P(),g===C&&(g=null,b())}},flush(){return S()},async clear(){b(),g=null,m=!1,await h,await w()}}}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 sP="/beeuni/part/";function oP(e){return typeof e=="string"&&e.startsWith(sP)}async function FD(e){if(!oP(e))throw new Error(`not an attachment part reference: ${e}`);let t=Ne();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 iP(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 ND(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 wm(e,t){return ND(e,t)?(t?iP(t):null)??iP(e):null}function vr(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 Am(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var qD=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function GD(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(GD).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function KD(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function aP(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function VD(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:qD.test(n.hostname)?t.backendUrls.some(r=>{let s=KD(r);return s!==null&&aP(s)===aP(n)}):t.templates.some(r=>WD(n.origin,r))}async function cP(e,t={}){if(!vr(e))return!1;let n=k().backendUrl;n&&await nt(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return VD(e,{templates:iy(),backendUrls:r})}async function lP(e,t={}){let n=wm(e,t.serverUrl||k().backendUrl||void 0);if(!n)return!1;let r=await Ye();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 HD(e,t={}){if(vr(e)){if(!await cP(e,t))return e;let n=await Ye();return n?Am(e,n):e}return await lP(e,t),e}var zD=3e3;function uP(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 YD(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 uP(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function JD(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function QD(e,t){throw G("buildPresentationTemplatePdfUrl")}function XD(e,t){throw G("buildPresentationTemplateImageUrl")}function pP(e,t){return`${JD(e)}/presentation/convert-to-${t}`}async function ZD(e,t,n,r){let s=pP(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,w)=>{let M=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(M),w(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),y=p.statusText;try{let h=JSON.parse(m);y=String(h.error||h.detail||h.message||y)}catch{m&&(y=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${y} (HTTP ${p.status})`)}}function ej(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 tj(e){return e==="unreachable"}function nj(e){return!e||e.status===0?"unknown":e.ok&&Rg(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var dP=1e4,rj={connection:"unknown",faultSinceMs:null};function sj(e,t,n,r=dP){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 gP({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<go,c=!!t&&i-t.atMs<yo;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<=mo,streamFresh:!!s&&i-s.atMs<=mn,inboxFresh:!!n&&i-n.atMs<=fo,activityFresh:!!o&&i-o.atMs<=mn}}function fn(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function vm(e,t,n){if(!t)return!1;let r=fn(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=fn(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function oj(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"&&!vm(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function ij(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,c=i?s.turns.filter(g=>!vm(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:fn(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function aj(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 y=r?.drainedAtMs;return i&&r.pending===0&&y!=null&&!m&&!(p&&s.atMs>=y)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:y,serverOpenTurnToken:n}:null}function cj(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:y,receiptTurnId:h}=t,w=c&&!n&&s.atMs>=p,M=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(w&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:fn(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(M)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(y)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let B=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:B.source,turnId:null,since:B.atMs,serverOpenTurnToken:r}}function mP(e){let t=gP(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=oj(e,t,s,o);if(i)return i;let{result:a,openTurn:c}=ij(e,t,s,o);return a??aj(e,t,o)??cj(e,t,c,o)}var go=6e4,mo=45e3,mn=45e3,fo=1e4,lj=3e3,yo=15e3;function uj(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function pj(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 dj(e){return mP(e)}function gj(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,c=[null,t?t.atMs+go:null,n?n.atMs+yo:null,r?r.atMs+fo:null,s?s.atMs+mo:null,o?o.atMs+mn:null,i?i.atMs+mn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function fP(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||xr({name:s.name??void 0,message:s.message})?null:s}var mj="SandboxMemoryGuard";function fj(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=fP(e,t);if(r?.message){if(r.name!==mj)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 yj=6e4;function hj(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function bj(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var yP=9e4;function _j(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+yP}var Pj=75e3,Sj=2,xj=2e4;function km(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function wj(e){return e.filter(t=>t!=null).join("|")}function Aj(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function vj(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...km(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...km(),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 y=Aj(e.attempts,s);return y?{...g,status:"escalating",dispatch:y,attempts:[...e.attempts,{step:y,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var kj={"retry-start":"retrying",restart:"restarting"};function Rj(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${kj[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function Cj(e){return e===1?"once":e===2?"twice":`${e} times`}function Ij(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 ${Cj(t)}`),`Tried: ${r.join(", then ")}.`}var Tj={"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 hP(e){return!!(e.metadata??{}).legacy_migration}function Ej(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 hP(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function Mj(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 Oj={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 Dj(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function ho(e){return e.runtime_sessions??e.opencode_sessions??[]}function bP(e){let t=ho(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 jj(e){let t=bP(e);return t?ho(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 $j(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=>ho(r).some(s=>s.id===t))??null)}var Uj=new Set;function _P(e){for(let t of[...Uj])try{t(e)}catch{}}function Lj(e){return e==="TIMEOUT"||e==="request_deadline"}function Bj(e){let t=SP(e)?e.code:void 0;return typeof t=="string"?t:void 0}var SP=e=>typeof e=="object"&&e!==null;function PP(e){let t=e?.metadata;return!!SP(t)&&t.warm===!0}var Fj=5,Nj=2e3,qj=e=>new Promise(t=>setTimeout(t,e));async function Gj(e,{attempts:t=Fj,delayMs:n=Nj,sleep:r=qj}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function Wj(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 y=null;try{let h=await e.ensure(c,p);if(g!==i)return;s.has(h.sessionId)?y=h.sessionId:n.set(c,h)}catch{}finally{g===i&&r.delete(c)}y&&d>0&&await a(c,y,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 Lj(Bj(g))?Gj(async()=>!PP(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(PP(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 Kj=12e4,bo=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},Vj=1e3,Hj=15e3,xP=100,zj=50,Yj=10;function wP(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 wr(`session ${c.status}`):new _(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function AP(e){return Jj(wP(e))}function vP(e){return new Rm({...e,loadPage:wP(e)})}async function Jj(e){let t=[],n=new Set,r;do{let i=await e({limit:xP,...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 Qj={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Rm=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??Qj,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??Kj,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 bo;if(!r&&xr(n))return;if(r||this.update({freshness:dn(n)?"loading":"error"}),n instanceof _&&(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(Vj*2**this.retryAttempt,Hj);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"?zj:xP,...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 bo(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<Yj&&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()}}};function kP(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 RP(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function Xj(e){throw G("buildTunnelEventStreamUrl")}function Zj(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,y="";function h(f,b){o?.(f,b);let S=d.get(f);if(S)for(let O of S)try{O(b)}catch{}}async function w(){if(m)return;let f=new AbortController;g=f,p&&(p.aborted?f.abort():p.addEventListener("abort",()=>f.abort(),{once:!0}));let b=f.signal;try{let S={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(S["Content-Type"]="application/json"),y&&(S["Last-Event-ID"]=y);let O=await fetch(t,{method:r,headers:S,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:b,credentials:"include"});if(!O.ok)throw new Error(`SSE connection failed: ${O.status} ${O.statusText}`);if(!O.body)throw new Error("SSE response has no body");i?.();let C=O.body.getReader(),P=new TextDecoder,x="",v="message",R=[],$=E=>{if(E===""){R.length>0&&h(v,R.join(`
96
+ `)),v="message",R=[];return}if(E.startsWith(":"))return;let q=E.indexOf(":"),Q=q===-1?E:E.slice(0,q),V=q===-1?"":E.slice(q+1);V.startsWith(" ")&&(V=V.slice(1)),Q==="event"?v=V.trim()||"message":Q==="data"?R.push(V):Q==="id"&&!V.includes("\0")&&(y=V)},D=E=>{let q="";!E&&x.endsWith("\r")&&(q="\r",x=x.slice(0,-1));let Q=x.split(/\r\n|\n|\r/);x=(Q.pop()??"")+q;for(let V of Q)$(V)};for(;!m;){let{done:E,value:q}=await C.read();if(E)break;x+=P.decode(q,{stream:!0}),D(!1)}m||(x+=P.decode(),D(!0),c?.())}catch(S){if(m||S instanceof DOMException&&S.name==="AbortError")return;a?.(S instanceof Error?S:new Error(String(S)))}}function M(){m=!0,g?.abort(),g=null,d.clear()}function B(f,b){let S=d.get(f)??new Set;S.add(b),d.set(f,S)}function F(f,b){d.get(f)?.delete(b)}return{connect:w,close:M,addEventListener:B,removeEventListener:F}}function e$(e,t){throw G("createTunnelEventStream")}var CP="/_beeuni/viewer",_o=6e4,yn=new Map;function IP(){yn.clear(),kr.clear()}async function t$(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 Cm(e={}){let t=e.path??CP,n=e.fetch??((o,i)=>fetch(o,i)),r=yn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=t$(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-_o:Date.now()+_o;return yn.set(t,{session:o,expiresAt:a}),o});return yn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function TP(e={}){let t=e.path??CP;return Object.assign(async()=>(await Cm(e))?.access_token??null,{invalidate:n=>{let r=yn.get(t);r&&!r.inflight&&r.session?.access_token===n&&yn.delete(t)}})}var kr=new Map;async function n$(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 kr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-_o:Date.now()+_o}),r.token}catch{return null}}function Im(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=kr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=n$(n,r).then(a=>(a===null&&kr.delete(n),a));return kr.set(n,i),i}}function EP(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:`${ce(n)}/_beeuni/apps/${encodeURIComponent(e)}`,token:Im({audience:e,fetch:t.fetch})}}var ut=class extends Error{code;constructor(t,n){super(n),this.name="BeeuniMemberError",this.code=t}},ye=e=>typeof e=="string"&&e.length>0?e:null;function MP(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 Po(e){if(!e||typeof e!="object")return null;let t=e,n=ye(t.sub)??ye(t.subject)??ye(t.user_id)??ye(t.userId);return n?{userId:n,email:ye(t.email),name:ye(t.name),picture:ye(t.picture)??ye(t.pictureUrl),groups:MP(t.groups),groupIds:MP(t.group_ids??t.groupIds),role:ye(t.role),accountId:ye(t.account_id)??ye(t.accountId),projectId:ye(t.project_id)??ye(t.projectId)}:null}function DP(e,t={}){let n=Po(e);if(!n)throw new ut("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 ut("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new ut("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var r$=60,Tm=new Map;function jP(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 OP(e){return JSON.parse(new TextDecoder().decode(jP(e)))}async function s$(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=Tm.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(()=>Tm.delete(e)),Tm.set(e,n)),n}return JSON.parse(e)}async function $P(e,t={}){let n=f=>{throw new ut("unauthenticated",`Beeuni sign-in token refused: ${f}.`)},r=t.jwks??et("BEEUNI_AUTH_JWKS"),s=t.issuer??et("BEEUNI_AUTH_ISSUER"),o=t.audience??et("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=OP(a),g=OP(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await s$(r,t.fetch??((f,b)=>fetch(f,b)))}catch{return n("key set unavailable")}let y=(m.keys??[]).filter(f=>f.kty==="EC"&&(d.kid===void 0||f.kid===d.kid));if(y.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${c}`),w;try{w=jP(p)}catch{return n("malformed")}let M=!1;for(let f of y)try{let{kid:b,alg:S,use:O,key_ops:C,...P}=f,x=await crypto.subtle.importKey("jwk",P,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},x,w,h)){M=!0;break}}catch{}if(!M)return n("bad signature");let B=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+r$<B)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let f=g.aud;if(!(f===o||Array.isArray(f)&&f.includes(o)))return n("wrong audience")}let F=Po(g);return F||n("no subject")}function Em(e){let t=e.agents.map(o$),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$(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function Mm(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>bs(n?{...r,mode:null}:r))}function UP(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=Mm(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 LP=Em;function BP(e){return e.providerID==="beeuni"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Om(e){return{providerID:"beeuni",modelID:e}}function FP(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 Om(n)}var Dm=[{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:"lowrouter",env:["LOWROUTER_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:"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:"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:"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:"aixy",env:["AIXY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]}];function jm(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function a$(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"beeuni":e.id.slice(0,t)}function NP(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 me(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 qP(e){return e.reduce((t,n)=>{let r=jm(n)??0,s=jm(t)??0;return r!==s?r>s?n:t:me(n.id)>me(t.id)?n:t})}function $m(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of NP(e,a$)){let a=[...NP(o,p=>p.family||p.id).values()].map(qP),c=a.filter(p=>{let d=jm(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[qP(a)])s.add(p.id)}return s}function So(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=>me(r.id)>0)?n.filter(r=>me(r.id)>0):n}function Rr(e){let t;for(let n of So(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&me(n.id)>me(t.id))&&(t=n)}return t}var c$={"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 GP(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var l$=(()=>{let e=new Map;for(let{id:n,env:r}of Dm)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=>GP(o)===n)??s[0])}return t})();function WP(e){let t=c$[e.id];if(t)return t;let n=e.env??[],r=n.length===1?l$.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[GP(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function Um(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var u$=["low","medium","high"];function KP(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:[...u$]}: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 VP=Dm;var p$=[{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"}}],FH=new Map(p$.map(e=>[e.id,e]));var HP=["gpt-6-astra","gpt-6-sol"],zP="gpt-6-astra",YP="gpt-6-sol";var QP=VP.map(e=>({id:e.id,authRequirement:WP(e)})),Cr=new Set(["beeuni"]),Lm=new Set(["beeuni"]);function hn(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 d$(e){if(!e)return!1;let t=hn(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 g$(e){let t=hn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(s=>!Lm.has(s.id)),connected:r.filter(s=>!Lm.has(s))}}function m$(e,t,n){let r=hn(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)&&Um(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 f$=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function y$(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 Bm="opencode";function h$(e){return e.cost?.input===0&&e.cost?.output===0}function JP(e){return e===Bm?Number.MAX_SAFE_INTEGER:f$.get(e)??Number.MAX_SAFE_INTEGER-1}function b$(e,t){let n=P$(t),r={},s=(e.providers??[]).map(o=>{let i=(o.models??[]).filter(a=>a.status!=="deprecated");return o.id===Bm&&!n.has(Bm)?{...o,models:i.filter(h$),keyless:!0}:{...o,models:i,keyless:!1}}).filter(o=>(o.keyless||n.has(o.id))&&!Lm.has(o.id)&&(o.models?.length??0)>0).sort((o,i)=>JP(o.id)-JP(i.id)).map(o=>{let i=[...o.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||me(p.id)-me(c.id)),a=Rr(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=y$(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 _$(e,t){if(!e)return t;if(!t)return e;let n=hn(e),r=hn(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 P$(e){let t=new Set;for(let n of QP)Um(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 S$(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=KP({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 x$(e,t){return g$(m$(hn(e),t,QP))}function XP(e){if(e.gatewayEnabled)return e.modelPicker?S$(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?x$(e.runtimeProviders,t):void 0;return _$(e.llmCatalogProviders?b$(e.llmCatalogProviders,t):void 0,d$(n)?n:void 0)}function w$(e){return"capabilities"in e&&e.capabilities!=null}function xo(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function ZP(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"?!Cr.has(i.id):Cr.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="beeuni/auto")continue;let p;if(w$(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:BP({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 eS(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var A$=new Set([zP]),v$="beeuni",tS="codex",k$=new Set(HP);function R$(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function bn(e){return A$.has(e.modelID)}function C$(e){return $m(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function nS(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=C$(e.catalogModels),s=eS(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===v$){let d=R$(i.modelID,i.provider),g=d===tS?t?.has(tS)??!1:t?.has(d)??!1;if(k$.has(i.modelID))return!n||i.modelID===YP;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return bn(i);try{let y=new Date(m.releaseDate);if(Number.isNaN(y.getTime()))return bn(i)}catch{return bn(i)}return!1}if(c==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return bn(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return bn(i)}catch{return bn(i)}return!1}}function rS(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 sS(e,t){if(!e||Cr.has(e.providerID)||me(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>me(i.modelID)>0))return e;let r=i=>me(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??Rr(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!o||o===e.modelID?e:{...e,modelID:o}}function oS(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?Om(n):void 0}function iS(e){let{models:t,providers:n}=e,r=c=>xo(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 y=c[m.id];if(y){let h={providerID:m.id,modelID:y};if(r(h))return h}for(let h of So(Object.keys(m.models).map(w=>({id:w})))){let w={providerID:m.id,modelID:h.id};if(r(w))return w}}}})(),i=s(e.picks??[]),a=i??s([e.serverDefault,e.globalDefault,e.agentModel,o]);return{model:sS(a,t),explicit:i,fallback:o}}return gS(I$);})();