@beeuni/sdk 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -10
- package/dist/beeuni.esm.min.js +37 -35
- package/dist/beeuni.global.js +37 -35
- package/dist/browser/cache/idb-sync-cache.js +15 -5
- package/dist/browser/session-sync/server-transcript-mirror.d.ts +7 -1
- package/dist/browser/session-sync/server-transcript-mirror.js +30 -24
- package/dist/browser/session-sync/session-sync-registry.d.ts +3 -1
- package/dist/browser/session-sync/session-sync-registry.js +48 -3
- package/dist/browser/stores/sync-store/keep-unchanged.d.ts +4 -0
- package/dist/browser/stores/sync-store/keep-unchanged.js +34 -0
- package/dist/browser/stores/sync-store.d.ts +1 -0
- package/dist/browser/stores/sync-store.js +72 -16
- package/dist/core/attachments/prompt-attachments.d.ts +4 -0
- package/dist/core/attachments/prompt-attachments.js +34 -0
- package/dist/core/capture/rules.d.ts +17 -0
- package/dist/core/capture/rules.js +27 -0
- package/dist/core/client/beeuni.d.ts +92 -5
- package/dist/core/client/beeuni.js +2 -0
- package/dist/core/client/capture.d.ts +105 -0
- package/dist/core/client/capture.js +48 -0
- package/dist/core/client/facade-identity.d.ts +1 -0
- package/dist/core/client/facade-identity.js +1 -0
- package/dist/core/client/project-access-resources.d.ts +3 -1
- package/dist/core/client/project-access-resources.js +1 -1
- package/dist/core/client/project-operations-admin.d.ts +4 -4
- package/dist/core/client/project-operations-review.d.ts +2 -3
- package/dist/core/client/project-operations-review.js +1 -0
- package/dist/core/client/project-operations-workspace.d.ts +4 -4
- package/dist/core/client/project-operations-workspace.js +1 -1
- package/dist/core/client/project-operations.d.ts +5 -4
- package/dist/core/client/session-context.d.ts +2 -0
- package/dist/core/client/session-handle.d.ts +13 -0
- package/dist/core/client/session-lifecycle-resources.d.ts +11 -0
- package/dist/core/client/session-lifecycle-resources.js +4 -0
- package/dist/core/client/session-lifecycle-security.d.ts +2 -0
- package/dist/core/client/session-lifecycle-security.js +1 -0
- package/dist/core/client/session-readiness.d.ts +2 -0
- package/dist/core/client/session-readiness.js +20 -1
- package/dist/core/http/api-client.d.ts +1 -0
- package/dist/core/http/api-client.js +1 -0
- package/dist/core/http/config.d.ts +2 -0
- package/dist/core/http/response-error.js +26 -11
- package/dist/core/http/transport.js +6 -1
- package/dist/core/models/composer-model.d.ts +14 -0
- package/dist/core/models/composer-model.js +21 -1
- package/dist/core/rest/platform-client/capture.d.ts +363 -0
- package/dist/core/rest/platform-client/capture.js +116 -0
- package/dist/core/rest/platform-client/index.d.ts +1 -0
- package/dist/core/rest/platform-client/index.js +1 -0
- package/dist/core/rest/platform-client/lifecycle.js +18 -12
- package/dist/core/rest/platform-client/shared.d.ts +5 -0
- package/dist/core/rest/platform-client/shared.js +18 -0
- package/dist/core/rest/projects-client/account-secret-resources.d.ts +2 -1
- package/dist/core/rest/projects-client/accounts.d.ts +34 -0
- package/dist/core/rest/projects-client/accounts.js +10 -0
- package/dist/core/rest/projects-client/admin-providers.d.ts +0 -61
- package/dist/core/rest/projects-client/admin-providers.js +0 -6
- package/dist/core/rest/projects-client/agent-config.d.ts +3 -0
- package/dist/core/rest/projects-client/apps-fleet.d.ts +5 -1
- package/dist/core/rest/projects-client/apps-fleet.js +2 -2
- package/dist/core/rest/projects-client/apps.d.ts +3 -0
- package/dist/core/rest/projects-client/change-requests.d.ts +2 -0
- package/dist/core/rest/projects-client/change-requests.js +2 -0
- package/dist/core/rest/projects-client/connectors.d.ts +7 -0
- package/dist/core/rest/projects-client/connectors.js +3 -0
- package/dist/core/rest/projects-client/files.d.ts +3 -0
- package/dist/core/rest/projects-client/files.js +4 -0
- package/dist/core/rest/projects-client/gateway.d.ts +5 -0
- package/dist/core/rest/projects-client/iam-actions.d.ts +76 -0
- package/dist/core/rest/projects-client/iam-actions.js +101 -0
- package/dist/core/rest/projects-client/iam.d.ts +1 -0
- package/dist/core/rest/projects-client/iam.js +1 -0
- package/dist/core/rest/projects-client/notifications.d.ts +1 -1
- package/dist/core/rest/projects-client/notifications.js +4 -0
- package/dist/core/rest/projects-client/projects.d.ts +3 -2
- package/dist/core/rest/projects-client/projects.js +2 -3
- package/dist/core/rest/projects-client/review-items.d.ts +2 -0
- package/dist/core/rest/projects-client/review-items.js +4 -0
- package/dist/core/rest/projects-client/review.d.ts +17 -3
- package/dist/core/rest/projects-client/review.js +11 -0
- package/dist/core/rest/projects-client/secrets.d.ts +3 -0
- package/dist/core/rest/projects-client/session-attachments.js +14 -1
- package/dist/core/rest/projects-client/sessions.d.ts +29 -2
- package/dist/core/rest/projects-client/sessions.js +34 -4
- package/dist/core/runtime/runtime-rest-client.js +1 -1
- package/dist/core/runtime/runtime-types.d.ts +1 -0
- package/dist/core/session/open-bundle.d.ts +4 -4
- package/dist/core/session/open-bundle.js +29 -46
- package/dist/core/session/turn-end-watch.d.ts +47 -0
- package/dist/core/session/turn-end-watch.js +141 -0
- package/dist/core/session-log/index.d.ts +4 -0
- package/dist/core/session-log/index.js +3 -0
- package/dist/core/session-log/tool-call.d.ts +7 -2
- package/dist/core/session-log/tool-call.js +25 -6
- package/dist/core/session-log/turns/blocks.d.ts +60 -0
- package/dist/core/session-log/turns/blocks.js +124 -0
- package/dist/core/session-log/turns/history.d.ts +32 -0
- package/dist/core/session-log/turns/history.js +99 -0
- package/dist/core/session-log/turns/index.d.ts +4 -0
- package/dist/core/session-log/turns/index.js +4 -0
- package/dist/core/session-log/turns/metrics.d.ts +21 -0
- package/dist/core/session-log/turns/metrics.js +29 -0
- package/dist/core/session-log/turns/turn.d.ts +55 -0
- package/dist/core/session-log/turns/turn.js +279 -0
- package/dist/core/session-log/turns/v1-parts.d.ts +8 -0
- package/dist/core/session-log/turns/v1-parts.js +43 -0
- package/dist/core/session-log/v1-view.d.ts +5 -2
- package/dist/core/session-log/v1-view.js +86 -22
- package/dist/core/session-log/v1.js +10 -3
- package/dist/core/session-sync/saved-transcript.d.ts +15 -1
- package/dist/core/session-sync/saved-transcript.js +55 -0
- package/dist/core/session-sync/session-sync-controller.js +3 -0
- package/dist/core/stream/event-stream.js +3 -3
- package/dist/core/turns/classify.js +4 -2
- package/dist/core/turns/edit-blocks.d.ts +1 -0
- package/dist/core/turns/edit-blocks.js +15 -0
- package/dist/core/turns/segments/burst-summary.d.ts +1 -0
- package/dist/core/turns/segments/burst-summary.js +24 -0
- package/dist/core/turns/segments/group-steps.d.ts +4 -3
- package/dist/core/turns/segments/group-steps.js +9 -6
- package/dist/core/turns/segments/narration.d.ts +5 -4
- package/dist/core/turns/segments/narration.js +12 -3
- package/dist/core/turns/segments/session-activity-groups.d.ts +2 -1
- package/dist/core/turns/segments/session-activity-groups.js +3 -1
- package/dist/core/turns/segments/step-label.d.ts +2 -1
- package/dist/core/turns/segments/step-label.js +3 -1
- package/dist/core/turns/segments/working-turn.d.ts +4 -2
- package/dist/core/turns/segments/working-turn.js +9 -8
- package/dist/core/turns/tool-kind.d.ts +1 -1
- package/dist/core/turns/tool-kind.js +3 -2
- package/dist/core/turns/tool-registry.js +1 -0
- package/dist/core/turns/tools/tool-meta.d.ts +1 -1
- package/dist/core/turns/tools/tool-meta.js +3 -2
- package/dist/core/turns/view-model.js +1 -13
- package/dist/genui/catalog.d.ts +28 -0
- package/dist/genui/catalog.js +396 -0
- package/dist/genui/expansion.d.ts +3 -0
- package/dist/genui/expansion.js +295 -0
- package/dist/genui/fence-entry.d.ts +2 -0
- package/dist/genui/fence-entry.js +1 -0
- package/dist/genui/fence.d.ts +21 -0
- package/dist/genui/fence.js +138 -0
- package/dist/genui/index.d.ts +6 -0
- package/dist/genui/index.js +6 -0
- package/dist/genui/markdown.d.ts +12 -0
- package/dist/genui/markdown.js +104 -0
- package/dist/genui/parse.d.ts +6 -0
- package/dist/genui/parse.js +75 -0
- package/dist/genui/prompt.d.ts +2 -0
- package/dist/genui/prompt.js +206 -0
- package/dist/genui/react/default-components.d.ts +2 -0
- package/dist/genui/react/default-components.js +72 -0
- package/dist/genui/react/default-components.test.d.ts +1 -0
- package/dist/genui/react/default-components.test.js +94 -0
- package/dist/genui/react/genui-block-disabled.test.d.ts +1 -0
- package/dist/genui/react/genui-block-disabled.test.js +50 -0
- package/dist/genui/react/genui-block.d.ts +28 -0
- package/dist/genui/react/genui-block.js +91 -0
- package/dist/genui/react/genui-block.test.d.ts +1 -0
- package/dist/genui/react/genui-block.test.js +205 -0
- package/dist/genui/react/index.d.ts +2 -0
- package/dist/genui/react/index.js +2 -0
- package/dist/genui/share.d.ts +5 -0
- package/dist/genui/share.js +30 -0
- package/dist/genui/test-fixtures.d.ts +2 -0
- package/dist/genui/test-fixtures.js +16 -0
- package/dist/genui/types.d.ts +29 -0
- package/dist/genui/types.js +1 -0
- package/dist/genui/urls.d.ts +1 -0
- package/dist/genui/urls.js +18 -0
- package/dist/genui/validate.d.ts +9 -0
- package/dist/genui/validate.js +116 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/internal/connector-catalog.d.ts +1 -0
- package/dist/platform/ui.d.ts +8 -2
- package/dist/platform/ui.js +19 -4
- package/dist/react/chat/use-chat-turns.d.ts +1 -1
- package/dist/react/human-presence.d.ts +9 -0
- package/dist/react/human-presence.js +12 -0
- package/dist/react/index.d.ts +4 -0
- package/dist/react/index.js +4 -0
- package/dist/react/opencode.d.ts +1 -1
- package/dist/react/opencode.js +1 -1
- package/dist/react/query-contracts.d.ts +6 -0
- package/dist/react/query-contracts.js +6 -0
- package/dist/react/query-keys.d.ts +17 -1
- package/dist/react/query-keys.js +24 -1
- package/dist/react/reset-identity-state.js +2 -0
- package/dist/react/session-cache-write.d.ts +1 -0
- package/dist/react/session-cache-write.js +20 -0
- package/dist/react/session-transcript-subscription.js +1 -1
- package/dist/react/sign-in-with-beeuni.d.ts +5 -5
- package/dist/react/turn-end-handoff.d.ts +13 -0
- package/dist/react/turn-end-handoff.js +101 -0
- package/dist/react/use-admin-providers.d.ts +0 -3
- package/dist/react/use-admin-providers.js +1 -11
- package/dist/react/use-capture.d.ts +47 -0
- package/dist/react/use-capture.js +173 -0
- package/dist/react/use-feature-flag.js +1 -0
- package/dist/react/use-opencode-events/handle-interaction-event.js +8 -3
- package/dist/react/use-opencode-events/handle-session-event.js +13 -8
- package/dist/react/use-opencode-events/handler-context.d.ts +1 -0
- package/dist/react/use-opencode-events/helpers.d.ts +1 -0
- package/dist/react/use-opencode-events/helpers.js +11 -1
- package/dist/react/use-opencode-local.d.ts +5 -1
- package/dist/react/use-opencode-local.js +15 -2
- package/dist/react/use-opencode-sessions/commands.d.ts +11 -1
- package/dist/react/use-opencode-sessions/commands.js +21 -1
- package/dist/react/use-opencode-sessions/permissions.js +28 -1
- package/dist/react/use-project-sessions.d.ts +1 -1
- package/dist/react/use-project-sessions.js +6 -5
- package/dist/react/use-prompt-attachments.js +1 -0
- package/dist/react/use-review-summary.d.ts +13 -0
- package/dist/react/use-review-summary.js +32 -0
- package/dist/react/use-runtime-reconnect.js +2 -2
- package/dist/react/use-session-list-state.d.ts +6 -0
- package/dist/react/use-session-list-state.js +33 -0
- package/dist/react/use-session-log.d.ts +3 -2
- package/dist/react/use-session-log.js +26 -17
- package/dist/react/use-session-messages.d.ts +2 -1
- package/dist/react/use-session-messages.js +15 -14
- package/dist/react/use-session-stream.js +12 -1
- package/dist/react/use-session-sync.d.ts +2 -2
- package/dist/react/use-session-sync.js +10 -8
- package/dist/react/use-session-transcript-history.js +2 -12
- package/dist/react/use-session-working.d.ts +2 -0
- package/dist/react/use-session-working.js +10 -0
- package/dist/react/use-session.d.ts +6 -0
- package/dist/react/use-session.js +87 -7
- package/package.json +49 -3
package/dist/beeuni.global.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
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(`
|
|
1
|
+
"use strict";var Beeuni=(()=>{var li=Object.defineProperty;var Yw=Object.getOwnPropertyDescriptor;var Jw=Object.getOwnPropertyNames;var Qw=Object.prototype.hasOwnProperty;var Xw=(e,t)=>{for(var n in t)li(e,n,{get:t[n],enumerable:!0})},Zw=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Jw(t))!Qw.call(e,s)&&s!==n&&li(e,s,{get:()=>t[s],enumerable:!(r=Yw(t,s))||r.enumerable});return e};var ev=e=>Zw(li({},"__esModule",{value:!0}),e);var nU={};Xw(nU,{ABORT_REASONS:()=>uP,ABORT_REASONS_NOT_YET_EMITTED:()=>UL,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>Pi,ANALYTICS_UNAVAILABLE_CODE:()=>Si,ATTACHMENT_PART_REF_PREFIX:()=>VP,ApiError:()=>x,AuthError:()=>oe,BEEUNI_TRANSCRIPT_SCHEMA:()=>ke,BeeuniMemberError:()=>bt,BillingError:()=>rt,CAPTURE_DEVICE_DEFAULTS:()=>NT,CAPTURE_EXCLUSION_GROUPS:()=>$T,CAPTURE_FRAME_INTERVALS_MS:()=>UT,CAPTURE_LAYERS:()=>LT,CAPTURE_MAX_HEIGHTS:()=>FT,CAPTURE_RETENTION_LIMITS:()=>BT,CONNECTION_FAULT_GRACE_MS:()=>ex,CONNECTOR_POLL_FIRST_DELAY_MS:()=>NP,CONNECTOR_POLL_INTERVAL_MS:()=>qP,CONNECTOR_POLL_WINDOW_MS:()=>GP,CONTEXT_TOOLS:()=>bS,ConnectorApprovalPendingError:()=>Ps,ConnectorCallError:()=>Fn,ConnectorPageLimitError:()=>xs,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>SS,DEFAULT_NOTIFICATION_PREFERENCES:()=>KC,DEFAULT_TRANSCRIPT_OPTIONS:()=>af,FEATURE_DISABLED_CODE:()=>ns,FEATURE_FLAG_KEYS:()=>Bv,FEATURE_NOT_SUPPORTED_CODE:()=>yi,FILE_VERBS:()=>ht,FileExistsError:()=>cn,HeadlessAuthError:()=>Zt,HostBoundaryError:()=>vn,INBOX_NOTIFICATION_KINDS:()=>WC,INBOX_OBSERVATION_MAX_MS:()=>Yo,INITIAL_SETTLED_CONNECTION:()=>H$,KNOWN_TOOL_KINDS:()=>Yy,MAX_PROMPT_ATTACHMENTS_BYTES:()=>DA,MAX_PROMPT_ATTACHMENT_BYTES:()=>nl,MAX_PROMPT_ATTACHMENT_FILES:()=>Gy,MEMORY_VERBS:()=>Zj,MODEL_NOT_SERVABLE_CODE:()=>hi,NO_GROUP_ACTIVITY_TOOLS:()=>n_,OPTIMISTIC_ABORT_MAX_MS:()=>Jo,OPTIMISTIC_COMPACTION_MAX_MS:()=>i0,OPTIMISTIC_RECEIPT_MAX_MS:()=>Ho,PERSISTED_QUERY_CACHE_VERSION:()=>y2,PLUMBING_TOOLS:()=>qS,PREVIEW_PROBE_TIMEOUT_MS:()=>B$,PROJECT_ACTIONS:()=>Q,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>hk,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>yk,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>ch,PROVISION_IN_FLIGHT_CODE:()=>_i,PublicSessionShareError:()=>js,REVIEW_CONTROL_ACTIONS:()=>SR,RUNTIME_NOT_READY_MARKERS:()=>KL,RUNTIME_PERMISSION_CAPABILITIES:()=>YC,RUNTIME_PERMISSION_REPLIES:()=>zC,RequestTooLargeError:()=>wt,RuntimeNotReadyError:()=>on,SANDBOX_FS_ROOTS:()=>wo,SANDBOX_PORTS:()=>Je,SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE:()=>bi,SERVER_COMPACTION_REVALIDATE_MS:()=>sx,SERVER_OBSERVATION_MAX_MS:()=>zo,SESSION_LIST_STATUS:()=>S0,SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES:()=>ti,SESSION_LOG_MINOR:()=>Pe,SESSION_LOG_SCHEMA:()=>pe,SESSION_NOTICE:()=>w0,STANDALONE_TOOLS:()=>r_,STREAM_OBSERVATION_MAX_MS:()=>An,SandboxNotReadyError:()=>qr,SessionNotReadyError:()=>Mt,SessionStartError:()=>Es,TRIGGER_CONTROL_ACTIONS:()=>_R,TURN_END_LEDGER_LAG_MS:()=>Z$,TURN_ERROR_CODES:()=>$h,WAKE_ESCALATION_COOLDOWN_MS:()=>d0,WAKE_MAX_RESTARTS:()=>p0,WAKE_NO_PROGRESS_MS:()=>u0,WIRE_ID_BACKDATE_MS:()=>fo,WIRE_ID_CLOCK_TOLERANCE:()=>pt,WIRE_ID_TIME_MASK:()=>Qe,WIRE_ID_TIME_SCALE:()=>nn,WIRE_MESSAGE_ID:()=>C_,__getConfigResolver:()=>rv,__setConfigResolver:()=>nv,abortErrorReason:()=>FL,acceptAccountInvite:()=>us,acceptAccountInviteAndLand:()=>Gi,acceptInvite:()=>d$,accountInviteLanding:()=>Uy,actReviewItem:()=>ad,activateConnection:()=>gc,addComputerToProject:()=>yc,addGroupMembers:()=>Dp,addMarketplaceSource:()=>Nd,advanceWakeEscalation:()=>f0,allDescendantIds:()=>IS,appendPreviewToken:()=>Zf,approveCaptureDeviceGrant:()=>bm,approveCaptureEnrollment:()=>am,approveProjectAccessRequest:()=>ba,approveTask:()=>yE,archiveProject:()=>Un,assignTicket:()=>vE,attachGroupToProject:()=>Ta,authMfa:()=>uo,authUser:()=>ao,authenticatedFetch:()=>j,authenticatedRequest:()=>qn,authorizePreviewUrl:()=>$$,backendApi:()=>l,beeuniAppViewerToken:()=>yw,beeuniBinding:()=>hw,beeuniPty:()=>F_,beeuniToken:()=>fy,bindSlackIdentity:()=>Kk,bindTeamsIdentity:()=>Vk,brokerProjectSecretRequest:()=>Na,browserKeyValueStorage:()=>T$,buildPresentationTemplateImageUrl:()=>q$,buildPresentationTemplatePdfUrl:()=>N$,buildPreviewAuthEndpoint:()=>Xf,buildPublicTemplateUrl:()=>BP,buildRuntimePresentationConversionUrl:()=>ZP,buildSandboxTemplate:()=>zc,buildScrapeFailureResults:()=>$S,buildStaticFileHealthPreviewUrl:()=>SM,buildStaticFileLocalUrl:()=>bM,buildStaticFilePreviewUrl:()=>_M,buildStaticFileServicePath:()=>_b,buildTunnelEventStreamUrl:()=>vB,buildWebProxyUrl:()=>AM,bulkActReviewItems:()=>cd,bulkDeletePolicies:()=>ER,bulkImportPolicies:()=>IR,burstSummary:()=>qo,burstSummaryLabel:()=>GS,burstWorkLabel:()=>Tf,callConnector:()=>Rt,cancelAccountDeletion:()=>Ch,cancelAccountInvite:()=>Ui,cancelSandbox:()=>i$,cancelScheduledChange:()=>Lu,cancelSubscription:()=>Ou,captureHealthBucket:()=>KT,changeRequestControlsFrom:()=>Ah,checkAccessEmail:()=>vP,checkMcpServerSignIn:()=>wA,childMapByParent:()=>fD,claimNext:()=>Wb,claimPerSeatBilling:()=>Fk,claimWarmProjectSession:()=>$l,classifyPart:()=>Sf,classifyPreviewProbeStatus:()=>XP,classifyPtyClose:()=>$_,classifySessionLogMessage:()=>qx,classifyTurn:()=>jo,cleanErrorMessage:()=>xD,cleanResultSnippet:()=>kD,cleanWorkerOutput:()=>Hj,clearBeeuniAppViewerCache:()=>fw,clearModelDefault:()=>_u,clearSessionFresh:()=>zA,closeChangeRequest:()=>yl,closeMilestone:()=>XE,collectTurnParts:()=>pD,commentTicket:()=>kE,commitSessionChanges:()=>bl,compactionExpiryAtMs:()=>c0,compactionTurnInfo:()=>lj,compareMessagesForDisplay:()=>iD,compareSemver:()=>OM,completeInFlight:()=>Kb,completeSlackInstall:()=>zu,completeTeamsInstall:()=>Yu,composerSelectableAgents:()=>_y,computeStatusFromPart:()=>$f,configureAutoTopup:()=>Fu,configureBeeuni:()=>Xr,confirmCheckoutSession:()=>Iu,connectEmail:()=>rp,connectSlack:()=>Vu,connectionFromHealth:()=>V$,connectionIsFaulted:()=>K$,connectionSharedWithEveryone:()=>lA,connectorConnect:()=>Tc,connectorConnectConnection:()=>_c,connectorFinalize:()=>$c,connectorFinalizeConnection:()=>bc,connectorHeadline:()=>A$,contextLabelForTool:()=>jD,contextToolSummary:()=>uO,contextToolTrigger:()=>pO,convertPresentationToGoogleSlides:()=>mC,convertRuntimePresentation:()=>G$,copyFile:()=>xr,costExportUrl:()=>qu,countLiveInboxPrompts:()=>t0,countReviewItemsBySegment:()=>iR,createAccount:()=>Ci,createAccountAuditWebhook:()=>Ed,createAccountSecretResource:()=>Ja,createAccountToken:()=>_d,createApp:()=>Wd,createAppAccessSession:()=>Xd,createAppDeployment:()=>eg,createAppToken:()=>Hd,createAppVolume:()=>hg,createAppVolumeSnapshot:()=>Pg,createArtifactKind:()=>rj,createAssignment:()=>ed,createAuditWebhook:()=>iC,createBackup:()=>f$,createBeeuni:()=>Fb,createBeeuniPty:()=>Fm,createBeeuniSession:()=>go,createCaptureEnrollmentToken:()=>sm,createCheckoutSession:()=>Eu,createConnector:()=>Ec,createConnectorLinkInfoCache:()=>x$,createFile:()=>Pr,createGatewayKey:()=>Pp,createGroup:()=>Ep,createHttpSessionSyncController:()=>iw,createMarketplaceInstallSession:()=>PC,createMilestone:()=>JE,createModelVisibility:()=>Nw,createOAuthClient:()=>Yp,createPerSeatCheckout:()=>Uk,createPersistedQueryCache:()=>C$,createPolicy:()=>RR,createPortalSession:()=>Mu,createProject:()=>Zi,createProjectAgent:()=>LE,createProjectCliToken:()=>wd,createProjectRepo:()=>ea,createProjectResourceGrant:()=>Oa,createProjectSession:()=>Et,createProjectSkill:()=>ia,createProjectTrigger:()=>iu,createPromptAttachmentController:()=>sf,createRole:()=>Np,createSSEStream:()=>AB,createSandbox:()=>ZL,createSandboxShare:()=>ud,createSandboxTemplate:()=>Kc,createSavedCopyStore:()=>dk,createScimToken:()=>jR,createServiceAccountApi:()=>nC,createSessionPrompt:()=>Qn,createSessionPublicShare:()=>Dl,createSessionQueue:()=>qb,createSessionReminder:()=>gd,createSsoGroupMapping:()=>HR,createTask:()=>gE,createTicket:()=>PE,createTunnelEventStream:()=>kB,createWarmSessionPool:()=>pB,currentSavedCopyStore:()=>vl,declineAccountInvite:()=>Wi,declineInvite:()=>g$,deleteAccountImmediately:()=>Th,deleteAccountSecretResource:()=>Za,deleteApp:()=>Vd,deleteAppDeployment:()=>ig,deleteAuditWebhook:()=>cC,deleteBackup:()=>h$,deleteBeeuniProject:()=>KE,deleteConnector:()=>Mc,deleteConnectorCredential:()=>Lc,deleteCredential:()=>oI,deleteDriveFile:()=>UC,deleteEnv:()=>$m,deleteFile:()=>Lt,deleteGatewayBudget:()=>bp,deleteGitHubInstallation:()=>ha,deleteGroup:()=>Mp,deleteMilestone:()=>eI,deleteOAuthClient:()=>Xp,deletePersonalProjectSecret:()=>Ha,deletePolicy:()=>TR,deleteProjectAgent:()=>BE,deleteProjectProviderOAuth:()=>Ga,deleteProjectResourceGrant:()=>Da,deleteProjectSecret:()=>Ka,deleteProjectSession:()=>zl,deleteProjectTrigger:()=>cu,deletePromptAttachment:()=>Ht,deleteRole:()=>Wp,deleteSandboxTemplate:()=>Hc,deleteServiceAccountApi:()=>sC,deleteSessionPrompt:()=>ql,deleteSessionReminder:()=>$s,deleteSessionReminders:()=>fd,deleteSsoGroupMapping:()=>zR,deleteSsoProvider:()=>KR,deleteTask:()=>hE,deleteTicket:()=>RE,denyCaptureDeviceGrant:()=>Sm,denyCaptureEnrollment:()=>cm,describeAccountInvite:()=>qi,describeConnectorTool:()=>ys,destroyAppMachine:()=>gg,destroyAppVolume:()=>bg,detachGroupFromProject:()=>Ia,detectLocalhostUrls:()=>mb,directSubsessions:()=>A0,disableServiceAccountApi:()=>rC,disconnectEmail:()=>sp,disconnectSlack:()=>Qu,discoverConnectionOAuth2:()=>gA,discoverConnectionOAuth2Resource:()=>mA,discoverConnectorAuth:()=>Ic,discoverLocalSandbox:()=>r$,dismissDriveConflict:()=>MC,downloadAccountAudit:()=>$P,downloadDriveFile:()=>DC,dropClientForUrl:()=>fI,dropPublicClientForUrl:()=>_I,editQueued:()=>Yb,editSessionPrompt:()=>Gl,enqueue:()=>Gb,ensurePmSession:()=>DE,ensurePreviewSessionCookie:()=>QP,ensureProjectConnectorConnection:()=>uA,ensureSandbox:()=>mP,ensureWarmProjectSession:()=>Ll,env:()=>j_,exchangeCode:()=>so,execInApp:()=>fg,exportAccountAudit:()=>Cd,extractGatewayErrorDetails:()=>we,extractSkillBaseDir:()=>sP,extractSkillContent:()=>iL,extractSkillFiles:()=>rP,extractWorkerPreview:()=>Yj,failInFlight:()=>Vb,fallbackBusyRowAfterTurnId:()=>Cj,familyForTool:()=>Sn,featureDisabledKey:()=>gi,featureFlags:()=>Xg,fetchAccountStateWithToken:()=>Lk,fetchAccountsWithToken:()=>$v,fetchAttachmentPart:()=>E$,fetchBeeuniAppViewer:()=>my,fetchCostExportCsv:()=>Wk,fetchProjectArchive:()=>el,fetchProjectFileRaw:()=>OA,fetchProjectsForAccountWithToken:()=>Hv,fetchSessionAttachment:()=>Jg,fileDownloadRequest:()=>Q_,filePhase:()=>Xj,fileVerb:()=>Qj,files:()=>sb,finalizeAppArtifact:()=>Fs,finalizeConnectorSetupLink:()=>IP,findActiveTranscriptShare:()=>bk,findFiles:()=>br,findLastTextPart:()=>dD,findSessionAttachments:()=>IT,findText:()=>Sr,fireProjectTrigger:()=>uu,fixSandboxWithAgent:()=>Wc,flattenModels:()=>Bw,flattenThought:()=>mj,forkAppVolume:()=>wg,formatBillingErrorForUI:()=>fi,formatCost:()=>Uj,formatDuration:()=>Uf,formatJsonFailureOutput:()=>wD,formatMessageDay:()=>Sj,formatMessageExact:()=>Pj,formatOpenCodeRuntimeError:()=>YL,formatRawOutput:()=>AD,formatRuntimeError:()=>gP,formatTokens:()=>Fj,formatTranscript:()=>Qb,freshSendHint:()=>Mj,generateSessionId:()=>Nb,getAccount:()=>Ti,getAccountBranding:()=>Ii,getAccountDeletionStatus:()=>kh,getAccountState:()=>wu,getAccountStateMinimal:()=>vu,getAgentCardLabel:()=>wS,getAgentConfig:()=>Ik,getAgentPersona:()=>UE,getAllVersions:()=>yP,getAnsweredQuestionParts:()=>mD,getApp:()=>Bs,getAppAccess:()=>Yd,getAppAuthEnv:()=>zd,getAppDeployment:()=>ng,getAppDeploymentLogs:()=>rg,getApprovalLink:()=>SC,getAuthToken:()=>st,getAuthTokenWithRetry:()=>nA,getAutoTopupSettings:()=>Uu,getAutoTopupSetupStatus:()=>Bk,getBeeuniProject:()=>qE,getBeeuniProjectBySession:()=>GE,getBeeuniPtyWebSocketUrl:()=>Gm,getBillingCreditBreakdown:()=>Ru,getBillingTierConfigurations:()=>Tu,getBillingTransactionsSummary:()=>ku,getBillingUsageHistory:()=>Cu,getCaptureAssetUrl:()=>hm,getCaptureChunkMedia:()=>ym,getCaptureDays:()=>gm,getCaptureDeviceGrant:()=>_m,getCaptureFrame:()=>fm,getCapturePolicy:()=>lm,getCaptureTimeline:()=>pm,getCaptureTimelineItems:()=>dm,getCaptureWorkspace:()=>Pm,getChangeRequest:()=>pl,getChangeRequestDiff:()=>dl,getChangeRequestMergePreview:()=>gl,getChildSessionError:()=>AO,getChildSessionId:()=>Or,getChildSessionToolParts:()=>kO,getClient:()=>gt,getClientForUrl:()=>Oe,getConnectStatus:()=>Dc,getConnectionOAuth2Application:()=>dA,getConnectionOAuth2Status:()=>bA,getConnectionPolicies:()=>SA,getConnectorCatalog:()=>Vt,getConnectorConfig:()=>Rc,getConnectorPolicies:()=>Ac,getConnectorSetupLink:()=>TP,getCostSummary:()=>Gk,getCurrentProject:()=>zm,getDefaultAccountState:()=>xu,getDiagnostics:()=>EO,getDirectory:()=>xS,getDiscoverConnector:()=>Ss,getDiscoverIntegration:()=>RA,getDriveFileUrl:()=>vg,getEmailInstallation:()=>tp,getEmailMode:()=>np,getEnterpriseDemo:()=>uC,getFileStatus:()=>_r,getFileWithDir:()=>mf,getFilename:()=>PS,getFolderAccess:()=>RC,getFullChangelog:()=>Jf,getGatewayBreakdown:()=>mp,getGatewayBudgets:()=>hp,getGatewayErrors:()=>yp,getGatewayKeys:()=>Sp,getGatewayLog:()=>pp,getGatewayOverview:()=>dp,getGatewayRoutingPolicy:()=>ip,getGatewaySeries:()=>gp,getGatewaySessions:()=>fp,getGitHubInstallation:()=>la,getGoogleAuthUrl:()=>gC,getGroup:()=>Tp,getHiddenToolParts:()=>SO,getInvite:()=>p$,getLatestSandboxVersion:()=>fP,getManagedGitBackend:()=>Yv,getManagedGitStatus:()=>Gv,getMarketplaceCatalogItem:()=>Bd,getMarketplaceCatalogItemFile:()=>Ud,getMfaRequired:()=>$R,getMilestone:()=>zE,getMobileClientPolicy:()=>of,getModelDefaults:()=>yu,getMyCaptureFrame:()=>Am,getMyCaptureTimeline:()=>vm,getNotificationPreferences:()=>Tg,getOAuthClient:()=>zp,getOAuthConsentRequest:()=>RP,getOpenCodeConfigInvalidError:()=>qL,getPartText:()=>hO,getPatPolicy:()=>ZR,getPermissionForTool:()=>IO,getProject:()=>kt,getProjectActivity:()=>FE,getProjectCommit:()=>il,getProjectCommitDiff:()=>al,getProjectDetail:()=>jn,getProjectDrive:()=>kC,getProjectFileHistory:()=>cl,getProjectGitToken:()=>Xi,getProjectLlmCatalog:()=>Ln,getProjectLlmCatalogProviders:()=>Fv,getProjectModelAccess:()=>rr,getProjectModelPicker:()=>$n,getProjectSandboxHealth:()=>Nn,getProjectSandboxProviderTransition:()=>Wv,getProjectSession:()=>zn,getProjectSessionConfigState:()=>Ql,getProjectSessionScope:()=>eu,getProrationPreview:()=>$u,getProviders:()=>QL,getProxyBaseUrl:()=>PM,getPublicClientForUrl:()=>hI,getPublicMarketplaceItem:()=>xP,getPublicMarketplaceItemFile:()=>wP,getPublicSessionShare:()=>fC,getPublicSessionShareMessages:()=>yC,getPublicShareByToken:()=>DP,getPublicTemplate:()=>UP,getQuestionForTool:()=>MO,getReferralCode:()=>eR,getReferralStats:()=>rR,getRetryInfo:()=>Nj,getRetryMessage:()=>qj,getReviewItem:()=>od,getReviewSummary:()=>sd,getRolePermissions:()=>Up,getRoleUsage:()=>Fp,getRuntimeConfigInvalidError:()=>Vo,getSSHConnection:()=>b$,getSandbox:()=>XL,getSandboxById:()=>e$,getSandboxPortUrl:()=>JL,getSandboxUrl:()=>Hf,getSandboxUrlForExternalId:()=>Ie,getSecretSetupLink:()=>MP,getServerHealth:()=>vo,getServiceLogs:()=>uI,getSessionAudit:()=>Bl,getSessionCostRecord:()=>nr,getSessionDrives:()=>jh,getSessionHealth:()=>Xm,getSessionLogPage:()=>Fl,getSessionMessageAuthors:()=>ru,getSessionModelUsage:()=>su,getSessionOpenBundle:()=>Sk,getSessionOversight:()=>FR,getSessionParticipants:()=>Rl,getSessionPolicy:()=>YR,getSessionPreviewCandidates:()=>Ml,getSessionProviderSecretPool:()=>rc,getSessionTranscript:()=>Ul,getSessionTranscriptSync:()=>Yn,getSessionTurn:()=>Jn,getSessionWatch:()=>Cl,getShellModePart:()=>Vj,getSlackChannelFile:()=>Xu,getSlackInstallation:()=>Ku,getSlackManifest:()=>Ju,getSlackMode:()=>Hu,getSsoProvider:()=>qR,getStaticFileHealthPath:()=>bb,getTask:()=>uE,getTaskStatus:()=>dE,getTemplate:()=>xC,getTicket:()=>bE,getToolInfo:()=>RO,getToolPrimaryArg:()=>Eo,getTranscriptFilename:()=>Xb,getTurnError:()=>Lj,getTurnErrorDetails:()=>Bj,getTurnErrorRawText:()=>$j,getTurnStatus:()=>Bf,getTurnTokens:()=>Ff,getUsageRollup:()=>Nu,getVersionDiff:()=>ll,getWebPushPublicKey:()=>Ig,getWorkingState:()=>Dj,grantAccountSecretResource:()=>ec,grantSandboxProjectAccess:()=>l$,grantSecretToAgent:()=>Ok,groupMessagesIntoTurns:()=>cD,groupShowSegments:()=>Of,groupSteps:()=>Ef,hasDiffs:()=>Gj,hasLocalhostUrls:()=>fM,hasPreviewTarget:()=>hb,hasRetryingAssistantTurn:()=>wf,heartbeatGapEvent:()=>q_,holdSessionPrompts:()=>Vl,humanizeReviewActionPath:()=>Rp,humanizeSearchQuery:()=>Cr,humanizeToolName:()=>hf,importSsoProviderFromMetadata:()=>GR,inboxObservationSupersedes:()=>e0,initialWakeEscalationState:()=>ty,inputPath:()=>et,installTemplate:()=>wC,interruptSessionPrompt:()=>Wl,invalidateTokenCache:()=>gs,inviteAccountMember:()=>$i,inviteProjectMember:()=>va,inviteRepoCollaborator:()=>Ji,isAbortError:()=>Nr,isAgentPart:()=>dO,isAppRouteUrl:()=>gb,isAttachment:()=>_O,isAttachmentPartRef:()=>HP,isAuthFailure:()=>Nt,isBillingError:()=>mi,isCompactionPart:()=>gO,isConfigured:()=>Zr,isContextTool:()=>lO,isEmptyConversation:()=>gy,isEmptyShowPart:()=>zs,isErrorOutput:()=>hD,isExternalUrl:()=>CM,isFeatureDisabledError:()=>di,isFilePart:()=>ff,isInternalLocalhostUrl:()=>vM,isInvisibleActivityPart:()=>Wg,isInviteSent:()=>Qv,isLastUserMessage:()=>Oj,isLegacyMigratedSession:()=>ox,isManagedGithubProject:()=>Uv,isNoGroupActivityTool:()=>Gg,isOfferedModel:()=>ai,isOpenCodeConfigInvalidError:()=>GL,isPaintableSavedCopy:()=>rh,isPatchPart:()=>fO,isPersistableQueryKey:()=>R$,isPreviewUrl:()=>wM,isProxiableLocalhostUrl:()=>Sb,isQuestionTool:()=>qg,isReasoningPart:()=>Ae,isRetryableTurnError:()=>MS,isRuntimeConfigInvalidError:()=>pP,isRuntimeNotReadyResponse:()=>dP,isRuntimeReady:()=>Qm,isRuntimeStartingError:()=>zL,isSandboxNotReadyError:()=>wn,isSelectableAgent:()=>Js,isServerReachable:()=>Ym,isSessionAttachmentRef:()=>vT,isSessionFresh:()=>Pl,isSessionLogRestoreNote:()=>Vx,isSessionStartError:()=>kk,isShellActivityTool:()=>bT,isShellMode:()=>eP,isShortOutput:()=>zj,isShowContentUnavailable:()=>VC,isShowPayloadEmpty:()=>or,isSnapshotPart:()=>mO,isStandaloneActivityTool:()=>Kg,isStepPart:()=>yO,isSubdomainPreviewUrl:()=>Wr,isTextPart:()=>De,isToolPart:()=>te,isToolPartHidden:()=>PO,isTurnErrorCode:()=>jg,isUnderSandboxRoot:()=>Vm,isWebProxyUrl:()=>RM,isWireIdAheadOf:()=>E_,latestPromptModel:()=>Kw,leaveAccount:()=>Hi,linkCaptureDevice:()=>nm,linkGitHubInstallation:()=>fa,linkRepository:()=>aa,listAccountAudit:()=>kd,listAccountAuditWebhooks:()=>Td,listAccountInvites:()=>Bi,listAccountMembers:()=>Li,listAccountResourceGrants:()=>AR,listAccountSecretResources:()=>Ya,listAccountSessions:()=>QR,listAccountTokens:()=>hd,listAccounts:()=>Ri,listActions:()=>MR,listAgentIdentities:()=>$p,listAllConnections:()=>cc,listAppAgents:()=>Jd,listAppDeployments:()=>tg,listAppMachines:()=>cg,listAppVolumeSnapshots:()=>Sg,listAppVolumes:()=>yg,listApps:()=>Gd,listAssignments:()=>Zp,listAuditEvents:()=>lC,listAuditWebhooks:()=>oC,listBackups:()=>m$,listBeeuniProjectSessions:()=>WE,listBeeuniProjects:()=>NE,listBeeuniPty:()=>Um,listBillingTransactions:()=>Au,listCaptureDevices:()=>em,listCaptureEnrollmentTokens:()=>rm,listCaptureEnrollments:()=>im,listChangeRequests:()=>ul,listChannelBindings:()=>Qk,listColumns:()=>CE,listConnectSections:()=>AA,listConnectToolkits:()=>vA,listConnections:()=>ac,listConnectorAccounts:()=>hs,listConnectorTools:()=>fs,listConnectors:()=>Sc,listCostByProject:()=>qk,listCredentialEvents:()=>nI,listCredentials:()=>tI,listDiscoverConnectors:()=>bs,listDiscoverIntegrations:()=>kA,listDiscoverSections:()=>Oc,listDriveConflicts:()=>IC,listDriveFiles:()=>OC,listDriveFolder:()=>Dh,listDriveVersions:()=>FC,listEnv:()=>jm,listFeaturedMarketplaces:()=>$d,listFields:()=>EE,listFiles:()=>pn,listFolderPrincipals:()=>EC,listGatewayLogs:()=>up,listGitHubInstallations:()=>ua,listGitHubRepositories:()=>da,listGitHubRepositoryBranches:()=>ga,listGroupMembers:()=>Op,listGroupProjectGrants:()=>xR,listGroups:()=>Cp,listLinkableGitHubInstallations:()=>pa,listMarketplaceCatalogItems:()=>jd,listMarketplaceSources:()=>Fd,listMarketplaces:()=>Ld,listMemberGroups:()=>wR,listMemberProjectAccess:()=>vR,listMilestoneEvents:()=>YE,listMilestones:()=>HE,listMyAccountInvites:()=>Ni,listNotifications:()=>Rg,listOAuthClients:()=>Hp,listOAuthGrants:()=>Sd,listPendingApprovals:()=>ja,listPendingProjectInvites:()=>Aa,listPermissions:()=>nd,listPolicies:()=>kR,listProjectAccess:()=>Pa,listProjectAccessRequests:()=>_a,listProjectAgentIdentities:()=>Bp,listProjectAgents:()=>jE,listProjectAudit:()=>Rd,listProjectBranches:()=>sl,listProjectCliTokens:()=>xd,listProjectCommits:()=>ol,listProjectDirectory:()=>Qc,listProjectFiles:()=>Jc,listProjectGroupGrants:()=>Ca,listProjectPolicies:()=>Uc,listProjectProviderOAuth:()=>qa,listProjectReminders:()=>yd,listProjectResourceGrants:()=>Ma,listProjectSandboxTemplates:()=>Nc,listProjectSandboxes:()=>Yc,listProjectSecrets:()=>Ba,listProjectSessions:()=>Tt,listProjectSessionsPage:()=>Al,listProjectSnapshots:()=>qc,listProjectTriggerEventApps:()=>du,listProjectTriggerEventTypes:()=>pu,listProjectTriggers:()=>ou,listProjects:()=>At,listProjectsForAccount:()=>Yi,listPublicMarketplaceItems:()=>SP,listPublicMarketplaces:()=>PP,listReferrals:()=>sR,listReviewItems:()=>rd,listRoles:()=>Lp,listSandboxProjectMembers:()=>c$,listSandboxShares:()=>ld,listSandboxes:()=>n$,listScimTokens:()=>DR,listServiceAccountsApi:()=>tC,listServiceTemplates:()=>lI,listServices:()=>cI,listSessionConnectRequests:()=>xA,listSessionCosts:()=>Wu,listSessionDrives:()=>GC,listSessionPrompts:()=>Nl,listSessionProviderSecretPools:()=>sc,listSessionPublicShares:()=>Ol,listSessionReminders:()=>dd,listSessionsNeedingInput:()=>La,listSignedInDevices:()=>_C,listSsoGroupMappings:()=>VR,listTaskEvents:()=>pE,listTasks:()=>lE,listTemplates:()=>ME,listTicketEvents:()=>SE,listTickets:()=>_E,loadHttpSessionHistory:()=>ow,loadPreviewUrlTemplate:()=>ut,looksLikeError:()=>vf,looksLikeHtml:()=>ED,looksLikeJsonPayload:()=>vD,makeDriveFolder:()=>$C,mapApiReviewItem:()=>hR,markNotificationsRead:()=>Cg,markSessionFresh:()=>Vn,maxWireIdClock:()=>Im,memoryRelPath:()=>eL,mergeBurstSteps:()=>If,mergeChangeRequest:()=>fl,messageCreatedAt:()=>fj,messageTime:()=>YS,mintWireMessageId:()=>yo,mintWireMessageIdAbove:()=>Mm,mkdir:()=>fn,modelInDefaultView:()=>qw,modelRefToKey:()=>oi,moveDriveFile:()=>BC,narrateFailedStep:()=>Rf,narrateStep:()=>Br,narrationToolName:()=>$r,narrowChatEvent:()=>G_,newestWireIdClock:()=>I_,nextConnectorPollDelay:()=>v$,normalizeActivityToolName:()=>he,normalizeCaptureAppId:()=>WT,normalizeCaptureDomain:()=>GT,normalizeExternalInput:()=>TM,normalizeName:()=>ee,normalizeToolName:()=>yf,notifyHostSignal:()=>ax,openChangeRequest:()=>ml,openEventStream:()=>So,paginateConnector:()=>Bc,parseBillingError:()=>On,parseEmbeddedFailure:()=>RD,parseFlagOverride:()=>OT,parseJsonFailure:()=>DS,parseLocalhostUrl:()=>kr,parseMemoryView:()=>tL,parseOpenCodeErrorPayload:()=>NL,parsePresentationOutput:()=>sL,parseProxyHop:()=>Jm,parseQuestionAnswersFromOutput:()=>qf,parseReadOutput:()=>oL,parseRuntimeErrorPayload:()=>Vf,parseScrapeInputUrls:()=>LS,parseScrapeOutput:()=>BS,parseSubdomainUrl:()=>ef,parseTaskRows:()=>Jj,parseWebProxyUrl:()=>kM,parseWebSearchOutput:()=>Af,partOutcome:()=>Bo,patchBeeuniProject:()=>VE,patchVerb:()=>rL,pickerProviderList:()=>$w,platformConfig:()=>C,pollConnectionOAuth2DeviceAuthorization:()=>_A,pollProjectProviderOAuth:()=>ds,previewGatewayRoute:()=>lp,previewMfaRequired:()=>BR,previewSlackIdentity:()=>Hk,previewTeamsIdentity:()=>zk,probeEffectivePermission:()=>Kp,probeEffectivePermissions:()=>Vp,probePreviewPort:()=>U$,projectArchiveRequest:()=>tl,projectCompacting:()=>a0,projectConfigAgentsToOpenCodeAgents:()=>vw,projectConfigAgentsToRuntimeAgents:()=>hy,projectSessionConnection:()=>W$,projectSessionForRuntimeId:()=>k0,projectSessionStartSeed:()=>mu,projectWorking:()=>n0,provisionProject:()=>ta,provisionProjectStream:()=>qv,provisionProjectWithToken:()=>zv,proxyLocalhostUrl:()=>Zm,proxyUrlToInternal:()=>xM,purchaseCredits:()=>Bu,putConnectionOAuth2Application:()=>pA,rawErrorText:()=>Rr,reactivateSandbox:()=>a$,reactivateSubscription:()=>Du,readBeeuniMember:()=>si,readBlob:()=>gn,readDriveFile:()=>jC,readFile:()=>dn,readProjectFile:()=>Zc,readSavedSessionCopy:()=>gw,reasoningIsRunning:()=>Go,rebuildProjectSnapshot:()=>Gc,reconcileConnection:()=>lc,reconcileMemberConnection:()=>uc,reconcileServices:()=>dI,recordPlatformLogout:()=>kP,recoverLinkResults:()=>Uo,recoverProjectSession:()=>Yl,refreshReferralCode:()=>tR,refreshSession:()=>en,registerAppArtifact:()=>Us,registerConnectionOAuth2Client:()=>fA,registerDeviceToken:()=>Ag,registerService:()=>gI,registerWebPushSubscription:()=>Mg,rejectProjectAccessRequest:()=>Sa,relativizePath:()=>TO,reloadProjectSessionConfig:()=>Xl,reloadProjectSessionConfigStream:()=>Zl,removeAccountAuditWebhook:()=>Md,removeAccountBrandingAsset:()=>Di,removeAccountMember:()=>Ki,removeBeeuniPty:()=>qm,removeGroupMember:()=>jp,removeMarketplaceSource:()=>qd,removeQueued:()=>zb,renameConnection:()=>fc,renameFile:()=>vr,renameSandbox:()=>t$,reopenChangeRequest:()=>hl,reopenMilestone:()=>ZE,reorderQueued:()=>Jb,replaceColumns:()=>TE,replaceFields:()=>IE,replaceProjectRepository:()=>ca,replaceTemplates:()=>OE,requestAccountDeletion:()=>Rh,requestChangesOnChangeRequest:()=>_l,requestProjectAccess:()=>Jv,requestProjectConnector:()=>Dd,requestProjectSecret:()=>Od,requestTopUp:()=>$k,requireBeeuniMember:()=>Sw,resendAccountInvite:()=>Fi,resendPendingProjectInvite:()=>Ra,resetAccountBranding:()=>ji,resetClient:()=>yI,resetGatewayRoutingPolicy:()=>cp,resetPassword:()=>oo,resetPublicClient:()=>bI,resolveApproval:()=>$a,resolveComposerAgent:()=>ww,resolveComposerModel:()=>Hw,resolveConnectorStart:()=>w$,resolveModelDefault:()=>Ww,resolvePublicShareUrl:()=>_k,resolveScrapeResults:()=>ID,resolveWorkingTurn:()=>Lf,resolvedPlan:()=>jk,restartAppMachine:()=>dg,restartProjectSession:()=>Xn,restartSandbox:()=>s$,restoreAppVolume:()=>xg,restoreBackup:()=>y$,restoreDriveVersion:()=>NC,restoreProjectSession:()=>Jl,retryAccountSecretResource:()=>Xa,retryFailed:()=>Hb,retrySessionPrompt:()=>Kl,revealCredential:()=>sI,reviewItemTarget:()=>kp,reviewSegmentForStatus:()=>vh,reviewVerdictAllowed:()=>PR,reviewVerdictForStatus:()=>aR,revokeAccountSecretResourceGrant:()=>tc,revokeAccountSession:()=>XR,revokeAccountToken:()=>bd,revokeAssignment:()=>td,revokeCaptureDevice:()=>tm,revokeCaptureEnrollmentToken:()=>om,revokeConnection:()=>dc,revokeGatewayKey:()=>xp,revokeOAuthGrant:()=>Pd,revokePendingProjectInvite:()=>ka,revokeProjectAccess:()=>wa,revokeProjectCliToken:()=>vd,revokeSandboxProjectAccess:()=>u$,revokeSandboxShare:()=>pd,revokeScimToken:()=>LR,revokeSessionPublicShare:()=>jl,rewriteLocalhostUrl:()=>yt,rollbackApp:()=>ag,rootRuntimeSession:()=>ix,rotateAccountSecretResource:()=>Qa,rotateOAuthClientSecret:()=>Qp,runConnector:()=>ws,runGatewayPlayground:()=>wp,runProjectProviderOAuthFlow:()=>tA,runtimeSessionsOf:()=>Qo,runtimeSupports:()=>cb,sanitizePtyChunk:()=>U_,saveGitHubInstallation:()=>ma,savedCopyEmptyRoot:()=>dy,scaleApp:()=>mg,scheduleDowngrade:()=>ju,searchCapture:()=>mm,searchConnectorTools:()=>ic,searchMyCapture:()=>wm,searchProjectFiles:()=>Xc,segmentTurn:()=>Mf,selectableProjectAgents:()=>jT,sendMagicLink:()=>to,sendReferralEmails:()=>oR,serverCompactionRevalidateAtMs:()=>l0,serviceAction:()=>pI,sessionConnectionLabel:()=>x0,sessionListStatus:()=>P0,sessionLogActivityText:()=>jx,sessionLogAnsweredQuestionCall:()=>Nx,sessionLogBurstRunning:()=>Bx,sessionLogBurstSteps:()=>Dx,sessionLogBurstSummary:()=>Lx,sessionLogBurstWorkLabel:()=>$x,sessionLogCallStatus:()=>Rx,sessionLogFullTextAction:()=>Xx,sessionLogFullTextPlan:()=>Zx,sessionLogHarnessSwitches:()=>Hx,sessionLogOfV1Rows:()=>hx,sessionLogOpenCall:()=>Ux,sessionLogPromptMessage:()=>Cx,sessionLogReferencedTexts:()=>Jx,sessionLogRestoreNotice:()=>zx,sessionLogRetrying:()=>cy,sessionLogShowGroupCall:()=>Fx,sessionLogThreadMetrics:()=>Wx,sessionLogTurnSegments:()=>Mx,sessionLogTurns:()=>ei,sessionLogWithFullTexts:()=>ew,sessionModelCandidates:()=>Vw,sessionModelPin:()=>er,sessionParentId:()=>fk,sessionPromptActions:()=>wk,sessionStartKey:()=>Ck,setAccountSecretResourceAccess:()=>nc,setAgentScope:()=>bu,setBootstrapAuthToken:()=>sA,setCachedAuthToken:()=>rA,setCaptureEnabled:()=>xm,setCapturePolicy:()=>um,setConnectionPolicies:()=>PA,setConnectorAuthorizationStrategy:()=>wc,setConnectorCredential:()=>jc,setConnectorCredentialMode:()=>xc,setConnectorName:()=>Cc,setConnectorPolicies:()=>kc,setConnectorSecretBinding:()=>CA,setConnectorSensitive:()=>vc,setDefaultConnection:()=>mc,setEnterpriseDemo:()=>pC,setEnv:()=>Lm,setGatewayBudget:()=>_p,setGatewayRoutingPolicy:()=>ap,setMemberSuperAdmin:()=>OR,setMfaRequired:()=>UR,setModelDefault:()=>hu,setPersonalProjectSecret:()=>Va,setProjectModelAccess:()=>sr,setProjectModelEnablement:()=>Tk,setProjectOnboardingComplete:()=>oa,setProjectOnboardingProfile:()=>Vv,setProjectPolicies:()=>Fc,setProjectSecretStrategy:()=>Fa,setProjectSessionModel:()=>nu,setProjectSessionScope:()=>tu,setProjectSessionSharing:()=>kl,setProjectTriggersActivation:()=>lu,setSavedCopyStore:()=>gk,setSessionArchived:()=>Il,setSessionOversight:()=>NR,setSessionPinned:()=>El,setSessionProviderSecretPool:()=>oc,setSessionWatch:()=>Tl,settleSessionConnection:()=>z$,setupSSH:()=>_$,shareConnection:()=>hc,shareFolder:()=>CC,shellActivityGroupLabel:()=>ST,shellExitCode:()=>Wf,shouldHideResponsePart:()=>jj,shouldShowToolPart:()=>_n,shouldSuppressWorkingTurnBusy:()=>kj,showGroupItems:()=>Df,showTurnBusyIndicator:()=>jf,signInWithPassword:()=>eo,signInWithProvider:()=>ro,signInWithSso:()=>lo,signOut:()=>po,signOutDevice:()=>bC,signUp:()=>Zs,skillDocumentPath:()=>dL,skillInputDir:()=>lL,sortSessions:()=>yD,splitSessionLogTurnWork:()=>Ox,splitTurnWork:()=>Nf,splitUserParts:()=>bO,startApp:()=>sg,startAppMachine:()=>ug,startConnectionOAuth2Authorization:()=>yA,startConnectionOAuth2DeviceAuthorization:()=>hA,startConnectorSetupLink:()=>EP,startProjectProviderOAuth:()=>ps,startProjectSession:()=>it,startProjectSessionOrThrow:()=>fu,startSessionWithToken:()=>jP,startTask:()=>fE,stepLabel:()=>Pn,stopApp:()=>og,stopAppMachine:()=>pg,stopProjectSession:()=>Zn,stopSandbox:()=>o$,storeGitHubUserToken:()=>ya,stripAnsi:()=>DO,stripTrailingSlashes:()=>de,subAgentCalls:()=>Gx,submitAccessRequest:()=>AP,submitDemoRequest:()=>LP,submitOAuthConsent:()=>CP,submitReviewItem:()=>id,submitSecretSetupLink:()=>OP,syncConnectors:()=>Pc,syncSubscription:()=>Nk,systemReload:()=>PI,toDaemonPath:()=>ft,toInternalUrl:()=>Pb,toSandboxAbsolutePath:()=>un,toToolView:()=>bf,toWorkspaceRelative:()=>Hm,toolCallBlock:()=>ar,toolCallError:()=>t_,toolCallMetadata:()=>Qh,toolCallRawOutput:()=>e_,toolCallStatus:()=>Zh,toolInfo:()=>Mo,toolKind:()=>le,toolViewModel:()=>cP,triggerControlsFrom:()=>bR,triggersRequest:()=>L_,turnEndCause:()=>rx,turnEndNotice:()=>o0,turnHasSteps:()=>gD,turnIsConfirmedActive:()=>Tj,turnRendersQueued:()=>Ej,turnRetryLabel:()=>v0,unassignTicket:()=>AE,unregisterDeviceToken:()=>kg,unregisterWebPushSubscription:()=>Og,unshareFolder:()=>TC,unwrapError:()=>_e,updateAccountAuditWebhook:()=>Id,updateAccountBranding:()=>Mi,updateAccountMemberRole:()=>Vi,updateAccountName:()=>Ei,updateAgentConfig:()=>Mk,updateApp:()=>Kd,updateAppAccess:()=>Qd,updateAppVolume:()=>_g,updateAuditWebhook:()=>aC,updateBeeuniPty:()=>Nm,updateChangeRequest:()=>Sl,updateChannelBinding:()=>Xk,updateConnectionCredential:()=>pc,updateEmailPolicy:()=>op,updateExperimentalFeature:()=>ra,updateFeatureFlag:()=>na,updateGroup:()=>Ip,updateMilestone:()=>QE,updateNotificationPreferences:()=>Eg,updateOAuthClient:()=>Jp,updatePassword:()=>io,updatePatPolicy:()=>eC,updatePolicy:()=>CR,updateProject:()=>Bn,updateProjectAccess:()=>xa,updateProjectAgent:()=>$E,updateProjectDefaultAgent:()=>Pu,updateProjectGroupGrant:()=>Ea,updateProjectSandboxProvider:()=>sa,updateProjectSession:()=>Hl,updateProjectTrigger:()=>au,updateRole:()=>qp,updateRolePermissions:()=>Gp,updateSandboxTemplate:()=>Vc,updateSessionPolicy:()=>JR,updateSessionReminder:()=>Ls,updateSessionReminders:()=>md,updateTask:()=>mE,updateTemplateWarmPool:()=>Kv,updateTicket:()=>xE,updateTicketStatus:()=>wE,updateUserMetadata:()=>co,uploadAccountBrandingAsset:()=>Oi,uploadAppArtifactArchive:()=>Zd,uploadConnectorAttachment:()=>_s,uploadDriveFile:()=>LC,uploadFile:()=>mn,uploadNativeFile:()=>Z_,uploadPromptAttachment:()=>Kn,uploadSessionAttachment:()=>Yg,uploadSlackChannelFile:()=>Zu,uploadTimeoutMsForBytes:()=>an,upsertCredential:()=>rI,upsertProjectGitCredential:()=>Wa,upsertProjectSecret:()=>Ua,validateProjectManifest:()=>Qi,validateReferralCode:()=>nR,validateToken:()=>zi,verifyBeeuniToken:()=>xw,verifyGatewayProvider:()=>Zk,verifyOtp:()=>no,verifySsoDomain:()=>WR,wakeEscalationAttemptSummary:()=>b0,wakeEscalationNote:()=>h0,wakeProgressFingerprint:()=>g0,wireIdClock:()=>Dt,wireIdClockAt:()=>rn,wireIdClockDelta:()=>jt,workedForLabel:()=>Kj,workingExpiryAtMs:()=>r0,workingTurnDrawsBusyRow:()=>Ij,writeActivityGroupLabel:()=>PT,writeFile:()=>wr,wsDomain:()=>No,wsFavicon:()=>TD,wsRootDomain:()=>CD});var tv={backendUrl:"",getToken:async()=>null},ui=null,Qr=null;function nv(e){Qr=e}function rv(){return Qr}function Xr(e,t){t?.global!==!1&&(ui=e)}function C(){return Qr?.()??ui??tv}function Zr(){return ui!==null||Qr?.()!==void 0}function sv(e){return new Promise(t=>setTimeout(t,e))}async function es(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(o&&n?.(),s>0&&await sv(s)),i=await e(),i)return i;return i}var pi=12e4;function ov(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Ry(e,t,n=pi){let r=e instanceof Request?e.signal:t?.signal;if(ov(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function ts(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var x=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},oe=class extends x{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},rt=class extends x{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},wt=class extends x{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},iv="ENDPOINT_RETIRED";function G(e,t){let n=t?` ${t}`:"";return new x(`${e}() is retired: the Beeuni API no longer serves this endpoint.${n}`,{code:iv})}var ns="feature_disabled";function Cy(e){if(!(e instanceof x)||e.status!==403||e.code!==ns)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function di(e){let t=Cy(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function gi(e){let t=Cy(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function On(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new rt(t,{message:r?.message||e.message||"Billing error",...r},void 0,{code:e.code,details:e.details,data:e.data,response:e.response,url:e.url,endpoint:e.endpoint})}function mi(e){return e instanceof rt}function Nt(e){if(e instanceof oe)return!0;let t=e?.status;return t===401||t===403}function fi(e){if(!(e instanceof rt))return null;let t=e.detail?.message?.toLowerCase()||"";return t.includes("credit")||t.includes("balance")||t.includes("insufficient")?{alertTitle:"You ran out of credits",alertSubtitle:"Upgrade your plan to get more credits and continue using the AI assistant."}:{alertTitle:"Billing check failed",alertSubtitle:e.detail?.message||"Please upgrade to continue."}}function Re(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function Ce(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(Re())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function rs(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(Re())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var Ty="request_deadline",av=/^Request exceeded the \d+s server processing deadline$/,Ey=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ty||av.test(n),cv="git_mirror_unavailable",lv=/^git mirror is temporarily unavailable$/,uv=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===cv||lv.test(n),pv="connectors_provider_unavailable",dv=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===pv;async function gv(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await Ce(e.json(),t),typeof r.message=="string"?n=r.message:r.error&&typeof r.error=="string"?n=r.error:typeof r.detail=="string"?n=r.detail:typeof r.detail?.message=="string"?n=r.detail.message:typeof r.reason=="string"&&(n=r.reason)}catch{}if(t.aborted)throw Re();return{message:n,data:r}}function mv(e,t,n){return Ey(e,t,n)||uv(e,t,n)||dv(e,t)||e===501&&t?.code===yi||e===409&&(t?.code===hi||t?.code===_i||t?.code===bi)||e===503&&(t?.code===Si||t?.code===Pi)}async function Iy(e,t,n,r){let{message:s,data:o}=await gv(e,t),i=new x(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Ey(e.status,o,s)?Ty:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=On(i));let a=e.status===403&&(o?.code==="account_mfa_required"||o?.code==="sso_required")?o.code:null;if(a){try{C().onAccessRemedy?.(a)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a==="account_mfa_required"?"beeuni:mfa-required":"beeuni:sso-required"))}catch{}}return e.status===431&&(i=new wt(431,{message:"Request is too large to process",suggestion:"Try uploading files one at a time, or reduce the number of files attached to your message."})),n&&!mv(e.status,o,s)&&C().onError?.(i,r),{error:i,success:!1}}var fv="X-Beeuni-Impersonate",My="beeuni.impersonation",qt=null,xi=!1,yv=new Set;function Oy(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function hv(e,t=Date.now()){if(!e||!e.grantId||!e.accountId)return!1;let n=Date.parse(e.expiresAt);return Number.isFinite(n)&&n>t}function _v(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.grantId!="string"||typeof t?.accountId!="string"?null:{grantId:t.grantId,accountId:t.accountId,accountName:typeof t.accountName=="string"?t.accountName:null,expiresAt:typeof t.expiresAt=="string"?t.expiresAt:""}}catch{return null}}function bv(){for(let e of yv)try{e()}catch{}}function Sv(){return xi||(xi=!0,qt=_v(Oy()?.getItem(My)??null)),qt&&!hv(qt)?(Pv(),null):qt}function Pv(){xi=!0;let e=qt!==null;qt=null;try{Oy()?.removeItem(My)}catch{}e&&bv()}var xv=/(^|\/)admin\/(api|analytics)(\/|$)/;function wv(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!xv.test(t)}function Dy(e){if(e!==void 0&&!wv(e))return{};let t=Sv();return t?{[fv]:t.grantId}:{}}var vv=!1;function Av(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function ss(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Gt(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function os(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(Av))Gt(n,s,o);return n}function vi(e,t,n){let r={...t},s=C().clientVersion?.trim();s&&!ss(r,"x-beeuni-client-version")&&Gt(r,"X-Beeuni-Client-Version",s),vv&&Gt(r,"x-beeuni-admin-bypass","1");for(let[i,a]of Object.entries(Dy(e)))Gt(r,i,a);let o=C().credentialHeader?.trim();return o?ss(r,o)||Gt(r,o,n):ss(r,"authorization")||Gt(r,"Authorization",`Bearer ${n}`),r}async function as(e,t){let n=await is();if(!n)throw new oe;return{headers:new Headers(vi(e,os(e,{headers:t}),n)),rejected:()=>Dn(n)}}function kv(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function jy(e,t,n,r,s){if(t instanceof Request){let c=new Headers(vi(t.url,os(t,n),r));return e(new Request(t,{headers:c,...s?{signal:s}:{}}))}let o=String(t),i=vi(o,os(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var Ly=null;async function Ai(e){let t=await es(()=>C().getToken(),e);return t&&(Ly=t),t}var is=Ai;function Dn(e=Ly){e&&C().getToken.invalidate?.(e)}var wi=new Map;function Rv(e){let t=wi.get(e);if(t)return t;let n=(async()=>(Dn(e),is({attempts:2,baseDelayMs:200})))().finally(()=>wi.delete(e));return wi.set(e,n),n}async function vt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=pi}=n,o=n.fetch??C().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:Ry(e,t,s);if(i?.aborted)throw Re();let a=await(i?Ce(is(),i):is());if(!a)throw new oe;let c=r&&!kv(t)&&!ss(os(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await jy(o,e,t,a,i);if(d.status!==401||!c)return d;let g=await Rv(a);return!g||g===a?d:jy(o,p,t,g,i)}async function Fe(e,t,n,r){let s=await vt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new x(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var $y=()=>C().backendUrl||"",Cv=new Set([502,503,504]),Tv=e=>Cv.has(e),By=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Ev=e=>By(e)||(e??"GET").toUpperCase()==="DELETE",Iv=2,cs=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function Ne(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...i}=t,a=new AbortController,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await Mv(e,i,n,r,s,o,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function Mv(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw Re();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},s);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Dv(e,t,c,s,o,i,a);if(p instanceof oe)return{error:p,success:!1};if(!p.ok)return await Iy(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await Ce(p.json(),a.activeController.signal):g?.includes("text/")?d=await Ce(p.text(),a.activeController.signal):d=await Ce(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return jv(c,e,t.method,n,r,s,a)}finally{ls(a)}}function ls(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Ov(e,t,n){try{await Ce(e.arrayBuffer(),t)}catch(r){if(cs(r))throw r}finally{ls(n)}}async function Dv(e,t,n,r,s,o,i){let a=By(t.method),c=Ev(t.method),p=c?Iv+1:1,d;for(let g=0;g<p;g++){g>0&&await rs(250*2**(g-1),t.signal??void 0);let m=g===0?o:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await Ce(vt(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(f){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),f instanceof oe)return new oe;if(i.didTimeout&&cs(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(cs(f)||g===p-1)throw f;continue}if(!a||!Tv(d.status)||g===p-1)return s||ls(i),d;await Ov(d,m.signal,i)}return d}function jv(e,t,n,r,s,o,i){ls(i);let a=cs(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new x("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace($y(),"")||t;c=new x(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(c=new x(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace($y(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&C().onError?.(c,s)):(c=new x(String(e)),r&&C().onError?.(c,s));return{error:c,success:!1}}var qe=()=>C().backendUrl||"",yi="feature_not_supported",hi="model_not_servable",_i="provision_in_flight",bi="sandbox_state_change_in_progress",Si="analytics_unavailable",Pi="accounts_list_unavailable";async function Lv(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await vt(`${qe()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof oe)return ts();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>Ne(`${qe()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>Ne(`${qe()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>Ne(`${qe()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>Ne(`${qe()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>Ne(`${qe()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>Ne(`${qe()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Ne(`${qe()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],Ne(`${qe()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:Lv};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function ki(e){return e.replace(/\/v1\/?$/,"")}async function Wt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=ki(e.backendUrl);try{let r=await fetch(`${n}${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(e.timeoutMs??8e3)});return r.ok?await r.json():null}catch{return null}}async function Ri(){return u(await l.get("/accounts"))}async function Ci(e){return u(await l.post("/accounts",e))}async function Ti(e){return u(await l.get(`/accounts/${e}`))}async function Ei(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function Ii(e){return u(await l.get(`/accounts/${e}/branding`))}async function Mi(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function Oi(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function Di(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function ji(e){return u(await l.delete(`/accounts/${e}/branding`))}async function Li(e){return u(await l.get(`/accounts/${e}/members`))}async function $i(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Bi(e){return u(await l.get(`/accounts/${e}/invites`))}async function Ui(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function Fi(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Ni(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function qi(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function us(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}function Uy(e,t){let n=e.bootstrap_grants_applied?.[0]??t?.projects?.[0];return n?{kind:"project",projectId:n.project_id,accountId:e.account_id}:{kind:"account",accountId:e.account_id}}async function Gi(e,t){let n=await us(e);return{accepted:n,landing:Uy(n,t)}}async function Wi(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function Ki(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function Vi(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Hi(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function $v(e){return Wt(e,"/v1/accounts")}async function zi(){let e=await l.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var Bv=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","genui","us_region","event_triggers","notification_center","volumes","drives","session_log","session_log_restore"];async function At(){return u(await l.get("/projects"))}async function Yi(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function kt(e,t){return u(await l.get(`/projects/${e}`,t))}async function Ji(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Qi(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Xi(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function Uv(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function jn(e,t){let n=u(await l.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function Ln(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function $n(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function Fv(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Zi(e){return u(await l.post("/projects",e))}async function ea(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function ta(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Fy=200;function Nv(e){let t=e.split(`
|
|
2
2
|
`).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
|
|
3
|
-
`);try{return JSON.parse(n)}catch(r){let s=n.length>
|
|
3
|
+
`);try{return JSON.parse(n)}catch(r){let s=n.length>Fy?`${n.slice(0,Fy)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function qv(e,t,n={}){let r=await l.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let c=await r.json().catch(()=>null);throw new x(c?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:c?.code})}let s=r.body?.getReader();if(!s)throw new Error("Provision stream is unavailable on this runtime (no response body)");let o=new TextDecoder,i="",a=null;try{for(;;){let{done:c,value:p}=await s.read();if(c)break;i+=o.decode(p,{stream:!0});let d=i.indexOf(`
|
|
4
4
|
|
|
5
5
|
`);for(;d!==-1;){let g=i.slice(0,d);i=i.slice(d+2),d=i.indexOf(`
|
|
6
6
|
|
|
7
|
-
`);let m=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(`
|
|
7
|
+
`);let m=Nv(g);if(m){if(t(m),m.type==="error")throw new x(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function Gv(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Bn(e,t){return u(await l.patch(`/projects/${e}`,t))}async function na(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function ra(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function sa(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function Wv(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function Kv(e,t){throw G("updateTemplateWarmPool")}async function oa(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function Vv(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Un(e){return u(await l.delete(`/projects/${e}`))}async function Hv(e,t){return Wt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function zv(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=ki(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let s=await r.json().catch(()=>null);return s?.project_id?{ok:!0,project:s}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function ia(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function aa(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function ca(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function la(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ua(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function pa(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function da(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function ga(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await l.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function ma(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function fa(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function ya(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function ha(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await l.delete(`/projects/github/installation?${n.toString()}`))}async function Yv(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function Jv(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function _a(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function ba(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Sa(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Pa(e){return u(await l.get(`/projects/${e}/access`))}async function xa(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function wa(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function Qv(e){return"status"in e&&e.status==="invited"}async function va(e,t,n,r){return u(await l.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Aa(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function ka(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Ra(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Ca(e){return u(await l.get(`/projects/${e}/group-grants`))}async function Ta(e,t,n,r){return u(await l.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function Ea(e,t,n,r){return u(await l.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function Ia(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function Ma(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function Oa(e,t){return u(await l.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function Da(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function ja(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function La(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function $a(e,t,n,r={}){let s=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function Ba(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Ua(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function Fa(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Na(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function qa(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function ps(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function ds(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Ga(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Xv=2e3,Zv=3e3,eA=10*6e4;async function tA(e){let{projectId:t,provider:n,input:r,onChallenge:s,isCancelled:o,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,c=()=>o?.()??!1,p=await ps(t,n,r);if(c())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Xv,p.interval_ms||Zv),g=p.expires_at||a()+eA;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await ds(t,n,p.flow_id)}catch{continue}if(c())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return c()?{status:"cancelled"}:{status:"expired"}}async function Wa(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function Ka(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Va(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Ha(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var za=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Kt=(e,t)=>`${za(e)}/${encodeURIComponent(t)}`,Ny=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Ya(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${za(e)}${n}`))}async function Ja(e,t){return u(await l.post(za(e),t))}async function Qa(e,t,n){return u(await l.put(`${Kt(e,t)}/value`,{value:n}))}async function Xa(e,t){return u(await l.post(`${Kt(e,t)}/retry`))}async function Za(e,t){return u(await l.delete(Kt(e,t)))}async function ec(e,t,n,r){return u(await l.put(`${Kt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function tc(e,t,n,r){return u(await l.delete(`${Kt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function nc(e,t,n,r){return u(await l.put(`${Kt(e,t)}/access`,{mode:n,user_ids:r}))}async function rc(e,t,n){return u(await l.get(Ny(e,t,n)))}async function sc(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function oc(e,t,n,r){return u(await l.put(Ny(e,t,n),{secret_ids:r}))}async function st(){return Ai()}async function nA(e){return es(()=>C().getToken(),e,gs)}function gs(){Dn()}function rA(e){e===null&&Dn()}function sA(e){}async function j(e,t,n){try{return await vt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof oe)return ts();throw r}}function ms(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Vt(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`${ms(e,"catalog")}${r}`)).connectors??[]}async function fs(e){let t=[];for(let n of await Vt(e,{includeSchemas:!1}))for(let r of n.actions)t.push({tool:`${n.slug}.${r.path}`,connector:n.slug,action:r.path,risk:r.risk,description:r.description||r.name,inputSchema:r.inputSchema});return t}async function ic(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await fs(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?o.push(a):s.every(p=>c.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function ys(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await Vt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===r);if(!s)return null;for(let o of s.actions){let i=`${s.slug}.${o.path}`;if(i===t)return{tool:i,connector:s.slug,action:o.path,risk:o.risk,description:o.description||o.name,inputSchema:o.inputSchema,outputSchema:o.outputSchema??null}}return null}function oA(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var iA=9e4;async function Rt(e,t,n={},r={}){let{connector:s,action:o}=oA(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(ms(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??iA,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function hs(e,t){let n=await l.get(ms(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function aA(e,t){if(e&&typeof e=="object"){let n=e;for(let r of["reason","error","message","detail"])if(typeof n[r]=="string"&&n[r])return n[r]}return`HTTP ${t}`}function cA(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}async function _s(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Beeuni-Attachment-Filename":encodeURIComponent(r),"X-Beeuni-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Beeuni-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(o["X-Beeuni-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=cA(C().backendUrl),a=ms(e,"attachments"),c=await j(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new x(aA(d,c.status),{status:c.status,code:String(d&&typeof d=="object"?d.code??c.status:c.status),details:d,response:c,endpoint:a});return d}function lA(e){if(e.owner_type!=="project")return!1;let t=e.shared_with??[];return t.length===0||t.some(n=>n.principal_type==="project")}async function ac(e){return u(await l.get(`/projects/${e}/connections`))}async function cc(e){return u(await l.get(`/projects/${e}/connections/all`))}async function lc(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function uc(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function pc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function Ge(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function uA(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function pA(e,t,n){return u(await l.put(Ge(e,t,"application"),n))}async function dA(e,t){return u(await l.get(Ge(e,t,"application")))}async function gA(e,t,n){return u(await l.post(Ge(e,t,"discover"),n))}async function mA(e,t,n={}){return u(await l.post(Ge(e,t,"discover-resource"),n))}async function fA(e,t,n){return u(await l.post(Ge(e,t,"register"),n))}async function yA(e,t,n){return u(await l.post(Ge(e,t,"authorize"),n))}async function hA(e,t,n){return u(await l.post(Ge(e,t,"device"),n))}async function _A(e,t,n){return u(await l.post(Ge(e,t,`device/${encodeURIComponent(n)}`),{}))}async function bA(e,t){return u(await l.get(Ge(e,t,"status")))}async function dc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function gc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function mc(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function fc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function yc(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function hc(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function _c(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function bc(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Sc(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await l.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function Pc(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function xc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function wc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function vc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Ac(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function kc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function SA(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function PA(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Rc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Cc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Tc(e,t,n={}){return u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}async function xA(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Ec(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function Ic(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function wA(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function Mc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function vA(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=u(await l.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function AA(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function bs(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await l.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function Oc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function Ss(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var kA=bs,RA=Ss;async function Dc(){return u(await l.get("/connectors/connect-status"))}async function jc(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function Lc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function CA(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function $c(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Fn=class extends x{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds:c,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=s,this.action=o,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},Ps=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},xs=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,s){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=s,Object.setPrototypeOf(this,new.target.prototype)}},Te=e=>typeof e=="string"&&e?e:null;function qy(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function TA(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function EA(e,t,n){if(!(e instanceof x)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Te(r.reason)??Te(r.error)??e.message,o=/^upstream_(\d{3})\b/.exec(s),i=typeof r.upstream_status=="number"?r.upstream_status:o?Number(o[1]):null;return new Fn(Te(r.message)??Te(r.hint)??s,{status:e.status,code:i===null?qy(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Te(r.connector)??t,action:Te(r.action)??n,binding:Te(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:TA(e.response),connectUrl:Te(r.connect_url),hint:Te(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Te(r.requested_account)})}function IA(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function ws(e,t,n,r={},s={}){let o=t.trim(),i=n.trim();if(!o||!i)throw new Error("connector slug and action are required");let a;try{a=await Rt(e,`${o}.${i}`,r,s)}catch(c){throw EA(c,o,i)}if(a.status==="pending_approval")throw new Ps(o,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new Fn(c,{status:200,code:a.upstream_error?"upstream_error":qy(c),details:a,data:a,reason:c,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return IA(a)}async function*Bc(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,c=r;for(let p=0;c;p++){if(p>=i)throw new xs(t,n,i,c);let d=await ws(e,t,n,c,a);yield d,c=o(d,c)}}async function Uc(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function Fc(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Nc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function qc(e){return u(await l.get(`/projects/${e}/snapshots`))}async function Nn(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Gc(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Wc(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Kc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function Vc(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Hc(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function zc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Yc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function qn(e){let t=new URL(C().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Beeuni backend: ${n.origin}`);let{headers:r}=await as(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function Jc(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function Qc(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),t?.cursor&&n.set("cursor",t.cursor),t?.limit!==void 0&&n.set("limit",String(t.limit)),u(await l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function Xc(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await l.get(`/projects/${e}/files/search?${r.toString()}`))}async function Zc(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var MA=10*6e4;async function el(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=`${C().backendUrl||""}/projects/${e}/files/archive${s}`;return await(await Fe(o,{method:"GET"},{timeoutMs:MA},"Failed to download")).blob()}async function tl(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return qn(`${C().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function OA(e,t,n,r){let s=new URLSearchParams({path:t});n&&s.set("ref",n);let o=s.toString()?`?${s.toString()}`:"",i=`${C().backendUrl||""}/projects/${e}/files/raw${o}`;return await(await Fe(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var nl=52428800,DA=104857600,Gy=20;var As=e=>`/projects/${encodeURIComponent(e)}/attachments`,ks={showErrors:!1,deadlineCoversBody:!0},Wy=3e4,jA=12e4,LA=6e4,$A=5*6e4,BA=6e4,UA=6e4;function vs(){return new x("Request aborted",{name:"AbortError",code:"ABORTED"})}function Gn(e){if(e?.aborted)throw vs()}function FA(e){return!(e instanceof x)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Wn(e,t,n=!1){let r;for(let s=0;;s++){Gn(t);try{return await e()}catch(o){let i=n&&o instanceof x&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(FA(o)||i))throw o;r??=Date.now()+(n?$A:LA);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await rs(a,t)}catch{throw Gn(t),o}}}}function NA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function rl(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&NA(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!i)throw new Error("Invalid attachment upload handle");return e}async function Ky(e,t,n,r){return u(await l.post(As(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...ks,signal:n,timeout:Wy}),"Failed to start attachment upload")}async function Vy(e,t,n,r){let s=rl({...await Wn(()=>Ky(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function Hy(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new x(r,{status:e,details:n,code:String(n?.statusCode??e)})}function qA(e){if(!(e instanceof x))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function GA(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?o(f):s())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new x("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},BA)},m=()=>{d(vs()),i.abort()};i.open(t.method,t.url);for(let[f,h]of Object.entries(t.headers))i.setRequestHeader(f,h);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d(Hy(i.status,i.responseText))},i.onerror=()=>d(new x("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(vs()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function WA(e,t,n){let r=C().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?vs():new x(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw Hy(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function KA(e,t,n){Gn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?GA(r,e,t,n):WA(e,t,n)}async function VA(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let i=s.upload;try{await Wn(()=>KA(i,t,r),r.signal)}catch(a){let c=qA(a);if(c!==409){if(o||!(c===400||c===401||c===403))throw a;o=!0,s=await Vy(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return zy(e,t,s,r)}async function zy(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${As(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Gn(r.signal);let a=i.received_bytes,c=Math.min(a+s,t.size),p=t.slice(a,c),d=await Wn(async()=>u(await l.putRaw(`${o}/chunks/${a/s}`,p,{...ks,signal:r.signal,timeout:Wy}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==c)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:c},r.onUpload?.(i),r.onProgress?.(c,t.size)}return i}async function Kn(e,t,n={}){if(!e)throw new Error("A project is required to upload attachments");if(!Number.isSafeInteger(t.size)||t.size<=0||t.size>52428800)throw new Error("Attachment must contain 1 byte to 50 MiB");Gn(n.signal);let r=n.resume?rl({...n.resume},t):rl({...await Wn(()=>Ky(e,t,n.signal),n.signal),received_bytes:0},t);n.onUpload?.(r),r.received_bytes<t.size&&(r.upload.kind==="direct"&&Date.parse(r.upload.expires_at)-Date.now()<UA&&(r=await Vy(e,t,r,n)),r=r.upload.kind==="direct"?await VA(e,t,r,n):await zy(e,t,r,n)),n.onProcessing?.();let s=`${As(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Wn(async()=>u(await l.post(`${s}/complete`,{},{...ks,signal:n.signal,timeout:jA}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof x&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Ht(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${As(e)}/${encodeURIComponent(t)}`,{...ks,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function sl(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/branches${r}`))}async function ol(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/commits${r}`))}async function il(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function al(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function cl(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await l.get(`/projects/${e}/files/history?${r.toString()}`))}async function ll(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await l.get(`/projects/${e}/version-diff?${n.toString()}`))}async function ul(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit)),n?.cursor&&r.set("cursor",n.cursor);let s=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function pl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function dl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function gl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function ml(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function fl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function yl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function hl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function _l(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function bl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function Sl(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var zt=new Set,HA=500;function Vn(e){e&&(zt.add(e),zt.size>HA&&zt.delete(zt.values().next().value))}function Pl(e){return!!e&&zt.has(e)}function zA(e){e&&zt.delete(e)}var pe="beeuni.session/2",Pe=1,Yy=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var ie=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Y=e=>typeof e=="string",Ee=e=>Y(e)&&e.length>0,Ke=e=>e===null||Y(e),J=(e,t)=>e===void 0||t(e),We=(...e)=>t=>e.includes(t),Hn=e=>Number.isInteger(e)&&e>=0,Yt=e=>typeof e=="number",Xy=e=>e.schema===pe&&Hn(e.v),Ct=e=>J(e,Y),xl=e=>e===void 0||ie(e)&&Object.values(e).every(t=>ie(t)&&Y(t.version)),Zy=e=>e===null||ie(e)&&Y(e.provider)&&Y(e.model)&&Ct(e.variant),YA=e=>e===null||ie(e)&&Yt(e.input)&&Yt(e.output)&&Yt(e.cache_read)&&Yt(e.cache_write)&&J(e.reasoning,Yt)&&J(e.cost,Yt),Jy=e=>ie(e)&&(e.type==="text"&&Y(e.text)||e.type==="attachment"&&Y(e.mime)),JA=e=>ie(e)&&Array.isArray(e.content)&&e.content.every(Jy)&&J(e.model_content,t=>Array.isArray(t)&&t.every(Jy))&&typeof e.is_error=="boolean",Qy={text:e=>Y(e.text)&&J(e.bytes,Hn)&&Ct(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>Y(e.text),attachment:e=>Y(e.mime)&&Ct(e.ref)&&J(e.bytes,Hn)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>Y(e.call_id)&&Y(e.name)&&Ee(e.kind)&&We("pending","running","complete","error")(e.status)&&J(e.result,JA),compaction:e=>Ke(e.summary)&&Ke(e.first_kept_message_id),subtask:e=>Y(e.thread_id)&&Y(e.agent)&&Y(e.description),step:e=>We("start","finish")(e.phase),harness:e=>Ee(e.harness)&&Ee(e.kind)&&typeof e.model_visible=="boolean"};function QA(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!ie(r)||!Ee(r.id)||n.has(r.id)||!Object.hasOwn(Qy,r.type)||!Qy[r.type](r)||!xl(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function XA(e){return ie(e)&&Xy(e)&&Ee(e.message_id)&&Ee(e.thread_id)&&Number.isInteger(e.seq)&&We("user","assistant","system")(e.role)&&We("turn","compaction","context")(e.kind)&&We("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&J(e.hidden_reason,We("failed_attempt","aborted","retracted","reverted","superseded"))&&J(e.origin,We("prompt","steer","command","automation","subagent","notification"))&&J(e.agent,Ke)&&J(e.reply_to,Ke)&&J(e.parent_message_id,Ke)&&Ct(e.native_agent_id)&&Ct(e.context_ref)&&Zy(e.model)&&YA(e.usage)&&We("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||ie(e.error)&&Ee(e.error.code)&&Y(e.error.message))&&Y(e.created_at)&&Ke(e.completed_at)&&ie(e.producer)&&Ee(e.producer.harness)&&Y(e.producer.harness_version)&&Y(e.producer.adapter_version)&&xl(e.ext)&&QA(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function ZA(e){return ie(e)&&Xy(e)&&Ee(e.thread_id)&&Ke(e.parent_thread_id)&&(e.spawned_by===null||ie(e.spawned_by))&&Y(e.created_at)}function ek(e){return ie(e)&&J(e.schema,t=>t===pe)&&J(e.v,Hn)&&Ct(e.session_id)&&J(e.title,Ke)&&Ct(e.created_at)&&J(e.restore_grade,We("native","converted","partial"))&&J(e.todos,Array.isArray)&&J(e.pending,t=>ie(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&J(e.selection,t=>ie(t)&&J(t.agent,Ke)&&Zy(t.model??null))&&J(e.harness,t=>ie(t)&&Y(t.current)&&Array.isArray(t.history))&&xl(e.ext)}function Rs(e){return ie(e)&&Hn(e.generation)&&typeof e.has_more=="boolean"&&ek(e.session)&&Array.isArray(e.threads)&&e.threads.every(ZA)&&(e.thread_id===null||Ee(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>XA(t)&&t.thread_id===e.thread_id)}var tk=e=>Rs(e)&&e.messages.length>0;function nk(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let s=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(s.length<=t)return s}return null}var eh={paintable:tk,fit:nk,capturedAt:()=>0},rk=new WeakMap;function th(e,t,n){rk.set(e,{read:(r,s)=>t.read(r,s),write:async(r,s,o)=>{await t.write(r,s,o),await n(r,s)}})}function rh(e){return!!e&&e.available===!0&&e.source==="mirror"&&Array.isArray(e.messages)&&e.messages.length>0&&!!(e.runtime_session_id??e.opencode_session_id)}var Cs=1,sk=12,ok=15e5,ik=3e5,ak=336*60*60*1e3,sh="beeuni.saved-copy";function wl(e){return!!e&&typeof e.then=="function"}function ck(e,t){return wl(e)?e.then(t):t(e)}function lk(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let s=a=>{let c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},o=s(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(o+a>t)break;o+=a,i+=1}for(;i>0;i-=1){let a=s(i);if(a.length<=t)return a}return null}function uk(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var pk={paintable:rh,fit:lk,capturedAt:uk};function dk(e){let t=nh(e,pk),n=nh({...e,namespace:`${e.namespace??sh}.log`},eh),r={...t,remove:async(s,o)=>{await Promise.all([t.remove(s,o),n.remove(s,o)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return th(r,n,t.remove),r}function nh(e,t){let{storage:n,userId:r,maxSessions:s=sk,maxBytes:o=ok,maxEnvelopeBytes:i=ik,maxAgeMs:a=ak,namespace:c=sh,now:p=()=>Date.now()}=e,d=`${c}:${r}:`,g=`${d}index`,m=(b,P)=>`${d}${b}/${P}`,f=b=>{try{let P=n.getItem(b);return wl(P)?P.catch(()=>null):P}catch{return null}},h=b=>{try{let P=n.removeItem(b);wl(P)&&P.catch(()=>{})}catch{}},S=async b=>{try{await n.removeItem(b)}catch{}},E=b=>{if(!b)return[];try{let P=JSON.parse(b);return P?.v===Cs&&Array.isArray(P.entries)?P.entries:[]}catch{return[]}},L=Promise.resolve(),D=b=>{let P=L.then(b,b);return L=P.catch(()=>{}),P},w=async b=>{try{await n.setItem(g,JSON.stringify({v:Cs,entries:b}))}catch{}},y=async()=>E(await f(g)),_=async(b,P)=>{let O=[...b].sort(($,N)=>$.u-N.u),A=O.reduce(($,N)=>$+N.b,0);for(;O.length>s||A>o;){let $=O.findIndex(T=>T.s!==P);if($===-1)break;let[N]=O.splice($,1);A-=N.b,await S(`${d}${N.s}`)}return O},R=b=>{D(async()=>{let P=await y(),O=P.find(A=>A.s===b);O&&(O.u=p(),await w(P))})},v=b=>D(async()=>{await S(`${d}${b}`);let P=await y(),O=P.filter(A=>A.s!==b);O.length!==P.length&&await w(O)});return{keyFor:m,read(b,P){let O=`${b}/${P}`;return ck(f(m(b,P)),A=>{if(!A)return null;let $;try{$=JSON.parse(A)}catch{return h(m(b,P)),v(O),null}return!$||$.v!==Cs||$.user!==r||p()-$.at>a||!t.paintable($.e)?(h(m(b,P)),v(O),null):(R(O),$.e)})},write(b,P,O){let A=`${b}/${P}`;if(!t.paintable(O))return v(A);let $={v:Cs,user:r,at:p(),e:O},N=t.fit($,i);if(N===null)return v(A);let T=t.capturedAt(O);return D(async()=>{let q=await y(),W=q.find($e=>$e.s===A);if(W&&T>0&&W.c>T)return;let H=q.filter($e=>$e.s!==A),In={s:A,b:N.length,u:p(),c:T},Le=await _([...H,In],A),Mn=m(b,P);try{await n.setItem(Mn,N)}catch{let $e=Le.filter(ne=>ne.s!==A).sort((ne,St)=>ne.u-St.u)[0];$e&&(await S(`${d}${$e.s}`),Le=Le.filter(ne=>ne.s!==$e.s));try{await n.setItem(Mn,N)}catch{await S(Mn),Le=Le.filter(ne=>ne.s!==A)}}await w(Le)})},remove(b,P){return v(`${b}/${P}`)},clear(){return D(async()=>{let b=await y();for(let P of b)await S(`${d}${P.s}`);await S(g)})}}}var oh=null;function gk(e){oh=e}function vl(){return oh}var mk=new Set;function ih(e){for(let t of mk)try{t(e)}catch{}}var ah=async(e,t,n,r)=>{let s=new URLSearchParams;n.thread!==void 0&&s.set("thread",n.thread),n.before_seq!==void 0&&s.set("before_seq",String(n.before_seq)),n.limit!==void 0&&s.set("limit",String(n.limit));let o=s.toString(),i=await l.get(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/log${o?`?${o}`:""}`,{showErrors:!1,signal:r});if(!i.success)throw i.error??new Error("Session log request failed");return i.data};function fk(e){let t=typeof e.parent_session_id=="string"?e.parent_session_id:e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var yk=50,ch=200,hk=ch;function lh(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return e?.view&&t.set(e.view,"only"),t.size>0?`?${t}`:""}async function Al(e,t){let n=await l.get(`/projects/${e}/sessions${lh(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Tt(e,t){return u(await l.get(`/projects/${e}/sessions${lh(t)}`))}async function kl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Rl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Cl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Tl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function El(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Il(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function _k(e,t){let n=e.public_url??e.public_path??e.proxy_path??e.public_token??"";if(!n)return"";if(/^https?:\/\//.test(n))return n;if(t)try{return new URL(n,t).toString()}catch{return n}return n}function bk(e,t=new Date){let n=null;for(let r of e)r.resource_type!=="transcript"||r.revoked_at||r.expires_at&&Date.parse(r.expires_at)<=t.getTime()||(!n||Date.parse(r.created_at)>Date.parse(n.created_at))&&(n=r);return n}async function Ml(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function Ol(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Dl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function jl(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Et(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||Vn(n?.session_id),n}async function Ll(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Vn(r.session.session_id),r}async function $l(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Vn(n.session_id),n}async function zn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Bl(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return u(await l.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function Ul(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function Yn(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await l.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Fl(e,t,n={},r){let s;try{s=await ah(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!Rs(s))throw new Error("The response is not a session log page");return s}async function Jn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function Sk(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function Pk(e){if(e)return e==="interrupt"?"transcript":"composer"}async function Qn(e,t,n){let r=n.placement??Pk(n.delivery);return u(await l.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Nl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function ql(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Gl(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Wl(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function Kl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Vl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Hl(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function zl(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return vl()?.remove(e,t),n}async function Yl(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function Jl(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Xn(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Zn(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return ih(t),n}async function Ql(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function xk(e){let t=e.split(`
|
|
8
8
|
`).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).replace(/^ /,""));if(t.length===0)return null;try{return JSON.parse(t.join(`
|
|
9
|
-
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function
|
|
9
|
+
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function Xl(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function Zl(e,t,n,r,s={}){let o=await l.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,s);if(!o.ok){let d=await o.json().catch(()=>null);throw new x(d?.error||`Reload failed: HTTP ${o.status}`,{status:o.status,code:d?.code,data:d})}let i=o.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,c="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;c+=a.decode(g,{stream:!0});let m=c.indexOf(`
|
|
10
10
|
|
|
11
|
-
`);for(;m!==-1;){let
|
|
11
|
+
`);for(;m!==-1;){let f=c.slice(0,m);c=c.slice(m+2),m=c.indexOf(`
|
|
12
12
|
|
|
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(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/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}`,
|
|
13
|
+
`);let h=xk(f);if(h){if(r(h),h.type==="error")throw new x(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function eu(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function tu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function nu(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function er(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function ru(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function su(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function wk(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function ou(e){return u(await l.get(`/projects/${e}/triggers`))}async function iu(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function au(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function cu(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function lu(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function uu(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}async function pu(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await l.get(`/projects/${e}/triggers/event-types?${n}`))}async function du(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var ot=new Map;function gu(e,t){return`${e}::${t}`}function uh(e,t){ot.delete(e),ot.set(e,t)}function ph(e,t){let n=gu(e,t),r=ot.get(n);return r&&uh(n,r),r}function Ts(e,t,n){let r=gu(e,t);if(!ot.has(r)&&ot.size>=512){let s=ot.keys().next().value;s!==void 0&&ot.delete(s)}uh(r,n)}function dh(e,t){ot.delete(gu(e,t))}function vk(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function tr(){return vk(C().backendUrl||"http://localhost:8008/v1")}function gh(){let e=C().sandboxId;return e?`${tr()}/p/${e}/8000`:""}function Ak(e,t=8e3){return`${tr()}/p/${e}/${t}`}function Ie(e,t=8e3){return Ak(e,t)}function mu(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var Es=class extends Error{status;code;terminal;constructor(t,n){super(t),this.name="SessionStartError",this.status=n.status,this.code=n.code,this.terminal=n.terminal}};function kk(e){return e instanceof Error&&e.name==="SessionStartError"}function Rk(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Es(s,{status:n,code:r,terminal:!0}):null}function mh(e,t,n){let r=typeof n=="number"?n:n?.waitMs,s=typeof n=="number"?void 0:n?.repositoryMode,o=new URLSearchParams;r&&r>0&&o.set("wait_ms",String(Math.floor(r))),s&&o.set("repository_mode",s),typeof n=="object"&&n?.keepStopped&&o.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&o.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=o.size>0?`?${o.toString()}`:"";return l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function it(e,t,n){let r=await mh(e,t,n);if(!r.success||!r.data){let s=Rk(r.error);if(s&&!(s.status===404&&Pl(t)))throw s;return null}return fh(e,t,r.data)}async function fu(e,t,n){let r=await mh(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return fh(e,t,r.data)}function fh(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Ts(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Ie(r),sandboxId:r}),n}function Ck(e,t){return["session-start",e,t]}async function yu(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function hu(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function _u(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await l.delete(`/projects/${e}/model-defaults?${n}`))}async function Tk(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function yh(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Ek(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Is(e){let t=e.connectors_required?yh(e.connectors_required):void 0,n=e.connectors_personal?yh(e.connectors_personal):void 0;if(t&&n&&!Ek(t,n))throw new Error("connectors_personal must match connectors_required when both fields are present");let r={...e};return delete r.connectors_personal,(t!==void 0||n!==void 0)&&(r.connectors_required=t??n),r}async function bu(e,t,n){let r=Is(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function Ik(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Su(n.block):null}}async function Mk(e,t,n){let r=Su(n,!0),s=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Su(s.block):null}}function Su(e,t=!1){let n=Is(e);if(n.workspace===void 0)return n;let r=n.workspace==="branch";if(n.repository_access!==void 0&&n.repository_access!==r)throw new Error("repository_access conflicts with workspace");if(t&&n.workspace==="read"&&n.repository_access===void 0)throw new Error("Legacy read is unavailable. Set repository_access explicitly.");return n.repository_access??=r,delete n.workspace,n}async function Ok(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Pu(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var hh="Use createPerSeatCheckout().";function xu(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function Dk(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function jk(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,isGrandfathered:t.is_grandfathered===!0};let n=e??xu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:Dk(r),label:s,sublabel:null,isGrandfathered:!1}}async function _h(e){let t=await l.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?xu():t.data}function bh(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString();return n?`?${n}`:""}async function wu(e){return _h(`/billing/account-state${bh(e)}`)}async function vu(e){return _h(`/billing/account-state/minimal${bh(e)}`)}async function Au(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await l.get(`/billing/transactions${n?`?${n}`:""}`))}async function ku(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await l.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Ru(){return u(await l.get("/billing/credit-breakdown"))}async function Cu(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function Tu(){return u(await l.get("/billing/tier-configurations"))}async function Lk(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Wt(e,`/v1/billing/account-state${t}`)}async function Eu(e){throw G("createCheckoutSession",hh)}async function Iu(e,t){throw G("confirmCheckoutSession",hh)}async function Mu(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Ou(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Du(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function ju(e,t,n){throw G("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Lu(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function $u(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),u(await l.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function Bu(e){return u(await l.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Uu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function $k(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Fu(e){return u(await l.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function Bk(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function Uk(e){return u(await l.post("/billing/create-per-seat-checkout",{account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale}),"Failed to create per-seat checkout")}async function Fk(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function Nk(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function Nu(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await l.get(`/usage${n?`?${n}`:""}`))}function Gu(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Ms(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Os(e){return e.size>0?`?${e}`:""}async function Wu(e={}){let t=new URLSearchParams;return Gu(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Ms(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/session-costs${Os(t)}`))}async function nr(e,t={}){let n=new URLSearchParams;return Gu(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${Os(n)}`))}async function qk(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Ms(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/cost-by-project${Os(t)}`))}async function Gk(e={}){let t=new URLSearchParams;return Gu(t,e),e.sessionId&&t.set("session_id",e.sessionId),Ms(t,e),u(await l.get(`/usage/cost-summary${Os(t)}`))}function qu(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let s=t;s.ownerId&&n.set("owner_id",s.ownerId)}Ms(n,t),t.sort&&n.set("sort",t.sort),n.set("format","csv");let r=e==="projects"?"/usage/cost-by-project":"/usage/session-costs";return`${C().backendUrl||""}${r}?${n}`}async function Wk(e,t={}){let n=qu(e==="projects"?"projects":"sessions",t),r=await Fe(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),s=r.headers.get("x-beeuni-row-cap"),o=s!=null?Number(s):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(o)?o:null}}async function Sh(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function Kk(e){return Sh("slack",e)}function Vk(e){return Sh("teams",e)}async function Ph(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function Hk(e){return Ph("slack",e)}function zk(e){return Ph("teams",e)}async function Ku(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function Vu(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var Yk={oauth_available:!1,install_url:null};async function Hu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?Yk:t.data}async function xh(e,t,n){return u(await l.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function zu(e,t){return xh("slack",e,t)}function Yu(e,t){return xh("teams",e,t)}async function Ju(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Qu(e){let t=await l.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function Xu(e,t){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function Zu(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function ep(e){let t=e.connectionId??e.connection_id??null,n=e.connectorSlug??e.connector_slug??e.connectionSlug??e.connection_slug??"beeuni_email";return{...e,connectionId:t,connectorSlug:n}}var Jk={provider:"agentmail",managed_available:!1};async function tp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?ep(r.data):null}async function np(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Jk:t.data}async function rp(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return ep(n)}async function sp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function op(e,t,n){let r=u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"beeuni_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return ep(r)}async function Qk(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function Xk(e,t,n){return u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function ip(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function ap(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function cp(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function lp(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function up(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await l.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function pp(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function dp(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function gp(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function mp(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function fp(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function yp(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function hp(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function _p(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function bp(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Sp(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Pp(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function xp(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function wp(e,t,n,r,s){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function Zk(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function eR(){throw G("getReferralCode")}async function tR(){throw G("refreshReferralCode")}async function nR(e){throw G("validateReferralCode")}async function rR(){throw G("getReferralStats")}async function sR(e={}){throw G("listReferrals")}async function oR(e){throw G("sendReferralEmails")}var vp="call:";function kp(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(vp)&&e.length>vp.length?{type:"connector_call",executionId:e.slice(vp.length)}:{type:"review_item",reviewItemId:e}}function vh(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function iR(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[vh(n.status)]+=1;return t}function aR(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function Ap(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Rp(e){let t=e.indexOf(".");return t<=0?Ap(e):`(${Ap(e.slice(0,t))}) ${Ap(e.slice(t+1))}`}function cR(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Ds=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,Me=e=>Array.isArray(e)?e:void 0,wh=e=>typeof e=="number"?e:0,lR=e=>e.split(`
|
|
14
|
+
`).map(t=>t.trim()).filter(Boolean);function uR(e,t){let n=Ds(e.advanced),r=U(e.description),s=Me(e.whatChanged)??(r?lR(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:U(e.impact)??"",verification:Me(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:Me(e.conflicts),requestedChanges:Me(e.requested_changes)??[],advanced:{headRef:U(n.headRef)??U(e.head_ref)??"",baseRef:U(n.baseRef)??U(e.base_ref)??"",headSha:U(n.headSha)??U(e.head_sha)??U(e.head_commit_sha)??"",baseSha:U(n.baseSha)??U(e.base_sha)??"",additions:wh(n.additions),deletions:wh(n.deletions),files:Me(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function pR(e,t){let n=Me(e.actions);if(n)return{actions:n.map((c,p)=>({id:U(c.id)??`${t.review_item_id}-${p}`,title:U(c.title)??"Action",connector:U(c.connector)??"",action:U(c.action)??"",consequence:U(c.consequence)??"",risk:U(c.risk)??t.risk,icon:U(c.icon)??"generic",argsPreview:Me(c.argsPreview)??[],policySource:U(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=U(e.action_path)??"",{connector:s,action:o}=cR(r),i=Ds(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?Rp(r):t.title||"Run action",connector:s,action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:U(e.approval_context),connectorRisk:U(e.risk)??null,policySource:"Requires approval"}]}}function dR(e,t){return{artifactKind:U(e.artifactKind)??"document",artifactLabel:U(e.artifactLabel)??"Output",previewUrl:U(e.previewUrl)??U(e.preview_url),preview:U(e.preview),files:Me(e.files),note:U(e.note)??t.summary??""}}function gR(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:Me(e.options)??[]}}function mR(e,t){return{note:U(e.note)??t.summary??"",children:Me(e.children)??[]}}function fR(e){let t=Ds(e.detail);switch(e.kind){case"change":return uR(t,e);case"approval":return pR(t,e);case"output":return dR(t,e);case"decision":return gR(t,e);case"batch":return mR(t,e)}}function yR(e,t){let n=typeof e.number=="number"?e.number:void 0,r=U(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function hR(e,t={}){let n=Ds(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?U(n.action_path):void 0,i=e.kind==="change"?yR(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:o?Rp(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:fR(e)}}var Q={PROJECT_READ:"project.read",PROJECT_WRITE:"project.write",PROJECT_DELETE:"project.delete",PROJECT_SESSION_READ:"project.session.read",PROJECT_SESSION_START:"project.session.start",PROJECT_SESSION_STOP:"project.session.stop",PROJECT_SESSION_BINDINGS_WRITE:"project.session.bindings.write",PROJECT_MEMBERS_READ:"project.members.read",PROJECT_MEMBERS_MANAGE:"project.members.manage",PROJECT_TRIGGER_READ:"project.trigger.read",PROJECT_TRIGGER_CREATE:"project.trigger.create",PROJECT_TRIGGER_UPDATE:"project.trigger.update",PROJECT_TRIGGER_DELETE:"project.trigger.delete",PROJECT_TRIGGER_FIRE:"project.trigger.fire",PROJECT_GATEWAY_LOGS_READ:"project.gateway.logs.read",PROJECT_GATEWAY_SPEND_READ:"project.gateway.spend.read",PROJECT_USAGE_READ:"project.usage.read",PROJECT_GATEWAY_BUDGET_SET:"project.gateway.budget.set",PROJECT_GATEWAY_KEYS_MANAGE:"project.gateway.keys.manage",PROJECT_AGENT_READ:"project.agent.read",PROJECT_AGENT_WRITE:"project.agent.write",PROJECT_SKILL_READ:"project.skill.read",PROJECT_SKILL_WRITE:"project.skill.write",PROJECT_COMMAND_READ:"project.command.read",PROJECT_COMMAND_WRITE:"project.command.write",PROJECT_FILE_READ:"project.file.read",PROJECT_FILE_WRITE:"project.file.write",PROJECT_SETTINGS_WRITE:"project.settings.write",PROJECT_SANDBOX_WRITE:"project.sandbox.write",PROJECT_MODEL_READ:"project.model.read",PROJECT_MODEL_WRITE:"project.model.write",PROJECT_GITOPS_READ:"project.gitops.read",PROJECT_GITOPS_PUSH:"project.gitops.push",PROJECT_GITOPS_MERGE:"project.gitops.merge",PROJECT_GITOPS_REF_ANY:"project.gitops.ref.any",PROJECT_GITOPS_REF_DELETE:"project.gitops.ref.delete",PROJECT_SECRET_READ:"project.secret.read",PROJECT_SECRET_WRITE:"project.secret.write",PROJECT_CONNECTOR_READ:"project.connector.read",PROJECT_CONNECTOR_CONNECTIONS_MANAGE:"project.connector.connections.manage",PROJECT_CONNECTOR_WRITE:"project.connector.write",PROJECT_APP_READ:"project.app.read",PROJECT_APP_WRITE:"project.app.write",PROJECT_APP_DEPLOY:"project.app.deploy",PROJECT_APP_ADMIN:"project.app.admin",PROJECT_REVIEW_READ:"project.review.read",PROJECT_REVIEW_SUBMIT:"project.review.submit",PROJECT_REVIEW_ACT:"project.review.act",PROJECT_CREDENTIALS_ISSUE:"project.credentials.issue"},_R=[Q.PROJECT_WRITE,Q.PROJECT_TRIGGER_CREATE,Q.PROJECT_TRIGGER_FIRE,Q.PROJECT_TRIGGER_UPDATE,Q.PROJECT_TRIGGER_DELETE];function bR(e){let t=r=>e[r]?.allowed===!0,n=t(Q.PROJECT_WRITE);return{canCreate:n&&t(Q.PROJECT_TRIGGER_CREATE),canFire:t(Q.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(Q.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(Q.PROJECT_TRIGGER_DELETE)}}var SR=[Q.PROJECT_WRITE,Q.PROJECT_GITOPS_PUSH,Q.PROJECT_GITOPS_MERGE,Q.PROJECT_REVIEW_ACT];function Ah(e){let t=r=>e[r]?.allowed===!0,n=t(Q.PROJECT_WRITE);return{canOpen:n&&t(Q.PROJECT_GITOPS_PUSH),canMerge:n&&t(Q.PROJECT_GITOPS_MERGE),canClose:n}}function PR(e,t,n){let r=kp(e.id);if(r.type==="connector_call"){let s=e.kind==="approval"?e.detail.actions?.[0]:void 0;return(t==="approve"||t==="reject")&&s?.canResolve!==!1&&s?.previewAuthorized!==!1}if(r.type==="change_request"){if(t==="answer")return!1;if(t==="approve")return Ah(n).canMerge}return n[Q.PROJECT_WRITE]?.allowed===!0&&n[Q.PROJECT_REVIEW_ACT]?.allowed===!0}function B(e){return l.get(e,{showErrors:!1})}function k(e){return u(e,"Unexpected empty response")}async function Cp(e){return k(await B(`/accounts/${e}/iam/groups`)).groups}async function Tp(e,t){return k(await B(`/accounts/${e}/iam/groups/${t}`))}async function Ep(e,t){return k(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Ip(e,t,n){return k(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Mp(e,t){return k(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function Op(e,t){return k(await B(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Dp(e,t,n){return k(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function xR(e,t){return k(await B(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function jp(e,t,n){return k(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function wR(e,t){return k(await B(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function vR(e,t){let n=k(await B(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function at(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function AR(e,t={}){let n=at({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return k(await B(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function kR(e,t={}){let n=at({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return k(await B(`/accounts/${e}/iam/policies${n}`)).policies}async function RR(e,t){return k(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function CR(e,t,n){return k(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function TR(e,t){return k(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function ER(e,t){return k(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function IR(e,t){return k(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Lp(e){return k(await B(`/accounts/${e}/iam/roles`)).roles}async function $p(e){return k(await B(`/accounts/${e}/iam/agent-identities`)).agents}async function Bp(e){return k(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function Up(e,t){return k(await B(`/accounts/${e}/iam/roles/${t}/permissions`))}async function MR(e){return k(await B(`/accounts/${e}/iam/actions`)).actions}async function Fp(e,t){return k(await B(`/accounts/${e}/iam/roles/${t}/usage`))}async function Np(e,t){return k(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function qp(e,t,n){return k(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Gp(e,t,n){return k(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Wp(e,t){return k(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function OR(e,t,n){return k(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function DR(e){return k(await B(`/accounts/${e}/iam/scim/tokens`)).tokens}async function jR(e,t){return k(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function LR(e,t){return k(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function $R(e){return k(await B(`/accounts/${e}/iam/mfa-required`))}async function BR(e){return k(await B(`/accounts/${e}/iam/mfa-required/preview`))}async function UR(e,t){return k(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function FR(e){return k(await B(`/accounts/${e}/iam/session-oversight`))}async function NR(e,t){return k(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function qR(e){return k(await B(`/accounts/${e}/iam/sso/provider`)).provider}async function GR(e,t){return k(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function WR(e){return k(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function KR(e){return k(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function VR(e){return k(await B(`/accounts/${e}/iam/sso/mappings`)).mappings}async function HR(e,t){return k(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function zR(e,t){return k(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function YR(e){return k(await B(`/accounts/${e}/iam/session-policy`))}async function JR(e,t){return k(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function QR(e){return k(await B(`/accounts/${e}/iam/sessions`)).sessions}async function XR(e,t){return k(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function ZR(e){return k(await B(`/accounts/${e}/iam/pat-policy`))}async function eC(e,t){return k(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function tC(e){return k(await B(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function nC(e,t){return k(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function rC(e,t){return k(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function sC(e,t){return k(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function oC(e){return k(await B(`/accounts/${e}/audit/webhooks`)).webhooks}async function iC(e,t){return k(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function aC(e,t,n){return k(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function cC(e,t){return k(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function lC(e,t={}){let n=at({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return k(await B(`/accounts/${e}/audit${n}`))}async function Kp(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),k(await B(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Vp(e,t,n){return n.length===0?[]:k(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function uC(e){return k(await B(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function pC(e,t){return k(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function Hp(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function zp(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function Yp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function Jp(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function Qp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Xp(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function dC(e){return at({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function Zp(e,t){return u(await B(`/accounts/${e}/iam/assignments${dC(t)}`)).assignments}async function ed(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await l.post(`/accounts/${e}/iam/assignments`,n))}async function td(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function nd(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await B(`/accounts/${e}/iam/permissions${n}`)).permissions}async function kh(){let e=await l.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function Rh(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function Ch(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function Th(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}var Eh="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function gC(e){throw G("getGoogleAuthUrl",Eh)}async function mC(e,t){throw G("convertPresentationToGoogleSlides",Eh)}async function rd(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind),t?.sessionId&&n.set("session_id",t.sessionId),t?.limit!=null&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);let r=n.toString();return u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function sd(e){return u(await l.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function od(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function id(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function ad(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function cd(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}async function ld(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function ud(e){return u(await l.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function pd(e,t){let n=await l.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var js=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Ih(e,t=""){return`${tr()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Mh(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let s=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new js(s,t.status)}return r}async function fC(e){return Mh(Ih(e))}async function yC(e){return Mh(Ih(e,"/messages"))}async function dd(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function gd(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Ls(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function $s(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var hC=4;async function Oh(e,t){let n=new Array(e.length),r=0,s=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(hC,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?o.done.push(i):o.failed.push({reminder:i,error:c.error})}),o}function md(e,t,n){return Oh(t,r=>Ls(e,r.sessionId,r.reminderId,n))}function fd(e,t){return Oh(t,n=>$s(e,n.sessionId,n.reminderId))}async function yd(e){return u(await l.get(`/projects/${e}/reminders`))}async function hd(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await l.get(`/accounts/tokens${r}`))}async function _d(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await l.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function bd(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function Sd(){return u(await l.get("/oauth/grants")).grants}async function Pd(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function _C(){return u(await l.get("/accounts/me/devices")).devices}async function bC(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function xd(e){return u(await l.get(`/projects/${e}/cli-token`))}async function wd(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function vd(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function Jt(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,s]of Object.entries(e))n.includes(` ${r} `)&&s!=null&&s!==""&&t.set(r,String(s));return t}function Ad(e={}){return{format:e.format,action:e.action,actor:e.actor,actor_type:e.actorType,project_id:e.projectId,session_id:e.sessionId,source:e.source,credential_kind:e.credentialKind,phase:e.phase,outcome:e.outcome,resource_type:e.resourceType,request_id:e.requestId,correlation_id:e.correlationId,since:e.since,until:e.until,q:e.q,cursor:e.cursor,limit:e.limit}}async function kd(e,t){let n=Jt(Ad(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function Rd(e,t){let n=Jt(Ad({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function Cd(e,t){let n=Jt(Ad(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Td(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Ed(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Id(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Md(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Od(e,t){return u(await l.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function Dd(e,t){return u(await l.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function SC(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function jd(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await l.get(`/marketplace/items${n}`))}async function Ld(){return u(await l.get("/marketplace/marketplaces"))}async function $d(){return u(await l.get("/marketplace/marketplaces/featured"))}async function Bd(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Ud(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Fd(){return u(await l.get("/marketplace/sources"))}async function Nd(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function qd(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function PC(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function xC(e){throw G("getTemplate")}async function wC(e,t){throw G("installTemplate")}async function Gd(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Wd(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Bs(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Kd(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Vd(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Hd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function zd(e,t){let n=await Bs(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await l.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),s=new TextEncoder().encode(JSON.stringify(r)),o="";for(let i of s)o+=String.fromCharCode(i);return{BEEUNI_AUTH_ISSUER:n.auth.issuer,BEEUNI_AUTH_AUDIENCE:n.auth.audience,BEEUNI_AUTH_JWKS:`data:application/json;base64,${btoa(o)}`}}async function Yd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Jd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function Qd(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Xd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Us(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Fs(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function vC(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function AC(e){let t=Uint8Array.from(e),n=await globalThis.crypto.subtle.digest("SHA-256",t.buffer);return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("")}async function Zd(e,t,n={}){let r=await vC(t),s=n.mediaType??"application/gzip",o=await Us(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),Fs(e,o.artifact.artifact_id,{sha256:await AC(r),size_bytes:r.byteLength})}async function eg(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function tg(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function ng(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function rg(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function sg(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function og(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function ig(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function ag(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var xe=(e,t)=>`/projects/${e}/apps/${t}`;async function cg(e,t){return u(await l.get(`${xe(e,t)}/machines`),"Failed to list machines").machines}async function lg(e,t,n,r){return u(await l.post(`${xe(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var ug=(e,t,n)=>lg(e,t,n,"start"),pg=(e,t,n)=>lg(e,t,n,"stop"),dg=(e,t,n)=>lg(e,t,n,"restart");async function gg(e,t,n){return u(await l.delete(`${xe(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function mg(e,t,n,r={}){return u(await l.put(`${xe(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function fg(e,t,n){return u(await l.post(`${xe(e,t)}/exec`,n),"Failed to run the command")}async function yg(e,t){return u(await l.get(`${xe(e,t)}/volumes`),"Failed to list volumes").volumes}async function hg(e,t,n){return u(await l.post(`${xe(e,t)}/volumes`,n),"Failed to create the volume")}async function _g(e,t,n,r){return u(await l.patch(`${xe(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function bg(e,t,n,r){u(await l.delete(`${xe(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Sg(e,t,n){return u(await l.get(`${xe(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Pg(e,t,n){return u(await l.post(`${xe(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function xg(e,t,n,r){return u(await l.post(`${xe(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function wg(e,t,n,r){return u(await l.post(`${xe(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function de(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var fe=e=>`/drives/${encodeURIComponent(e)}`;async function kC(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new x("Files not found",{status:404});return t[0]}async function RC(e,t){return u(await l.get(`${fe(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function CC(e,t){return u(await l.put(`${fe(e)}/access`,t),"Failed to share folder")}async function TC(e,t){let n=u(await l.delete(`${fe(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function EC(e){return u(await l.get(`${fe(e)}/principals`),"Failed to load people")}async function IC(e){return u(await l.get(`${fe(e)}/conflicts`),"Failed to load conflicts").conflicts}async function MC(e,t){u(await l.post(`${fe(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function OC(e,t="/"){return(await Dh(e,t)).entries}async function Dh(e,t="/"){return u(await l.get(`${fe(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function vg(e,t,n){let r=de(C().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${fe(e)}/files/content?${new URLSearchParams(s)}`}async function DC(e,t,n){let r=await j(vg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new x(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function jC(e,t,n){let r=await j(vg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new x(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function LC(e,t,n,r){return u(await l.putRaw(`${fe(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function $C(e,t){return u(await l.post(`${fe(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function BC(e,t,n){return u(await l.post(`${fe(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function UC(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${fe(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function FC(e){return u(await l.get(`${fe(e)}/versions`),"Failed to load versions").versions}async function NC(e,t){u(await l.post(`${fe(e)}/restore`,{versionId:t}),"Failed to restore version")}var qC=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function GC(e,t){return(await jh(e,t)).drives}async function jh(e,t){return u(await l.get(qC(e,t)),"Failed to load session files")}async function Ag(e){return u(await l.post("/notifications/device-token",e))}async function kg(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var WC=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered"];async function Rg(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return u(await l.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function Cg(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await l.post("/notifications/read",t))}var KC={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1},capture_device_down:{push:!0,email:!0},capture_device_recovered:{push:!0,email:!1}};async function Tg(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function Eg(e){return u(await l.put("/notifications/preferences",e))}async function Ig(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function Mg(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await l.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function Og(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function rr(e){return u(await l.get(`/projects/${e}/model-access`))}async function sr(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function VC(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:o,previewIsLinkOnly:i}=e;return t||n?!1:s?o&&!i:r==="error"}function Dg(e){return typeof e=="string"&&e.trim().length>0}function Lh(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Dg(t)||Dg(n)||Dg(r)}function HC(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function or(e){if(!e)return!0;let t=HC(e.items);return t?!t.some(Lh):!Lh(e)}var ke="beeuni.transcript.v1",$h=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function jg(e){return typeof e=="string"&&$h.includes(e)}var zC=["once","always","reject"],YC=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var Fh="beeuni-v1-import",JC={harness:Fh,harness_version:ke,adapter_version:"1"},Lg={schema:pe,v:1},QC={opencode:"[Tool execution was interrupted]",pi:"No result provided"},XC="[Old tool result content cleared]",ZC="The following tool was executed by the user",eT=new Map(Object.entries({bash:"shell",powershell:"shell",read:"read",write:"write",edit:"edit",multiedit:"edit",patch:"patch",apply_patch:"patch",list:"list",ls:"list",glob:"glob",find:"glob",grep:"grep",webfetch:"web_fetch",websearch:"web_search",codesearch:"web_search",todowrite:"todo",todoread:"todo",task:"task",question:"question",plan_enter:"plan",plan_exit:"plan"})),tT=e=>eT.get(e)??(e.includes("_")?"mcp":"other"),nT=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),rT=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),F=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),X=e=>typeof e=="string"?e:void 0,Ve=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ws=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,Nh=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Qt=e=>Ve(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Xt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function $g(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>$g(r,t[s]));if(!F(e)||!F(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0);return n.length===Object.keys(t).filter(r=>t[r]!==void 0).length&&n.every(r=>$g(e[r],Ws(t,r)))}function qs(e,t){if($g(e,t))return;if(e===void 0)return{del:!0};if(!F(e)||!F(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let s=qs(Ws(e,r),Ws(t,r));s&&Nh(n,r,s)}return{sub:n}}function Gs(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=F(e)?{...e}:{};for(let[r,s]of Object.entries(t.sub)){let o=Gs(Ws(n,r),s);o===void 0?delete n[r]:Nh(n,r,o)}return n}var ir=e=>Object.values(e??{}).find(t=>t.version===ke),Ks=(e,t)=>({[e]:{version:ke,...t}}),qh=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},Bh=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),sT=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),oT=e=>{if(F(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==ke&&F(n.data?.details));return t?t.data.details:{}};function iT(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=Xt(e.started_at)??t.created,i=Xt(e.ended_at)??o,a=r?.exit_code!==void 0?{exit:r.exit_code}:{};if(e.status==="pending")return{status:"pending",input:e.input??{},raw:""};if(e.status==="running")return{status:"running",input:e.input??{},...e.title&&{title:e.title},time:{start:o}};if(e.status==="error")return{status:"error",...s,error:Bh(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:o,end:i}};let c=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...qh(d,t)}]:[]),p=Xt(r?.cleared_at);return{status:"completed",...s,output:Bh(r?.content),title:e.title??"",metadata:{...oT(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...c.length&&{attachments:c}}}function Gh(e,t){let n=sT(e,t);switch(e.type){case"text":return{...n,type:"text",text:e.text,...e.synthetic!==void 0&&{synthetic:e.synthetic}};case"reasoning":return{...n,type:"reasoning",text:e.text,time:{start:t.created}};case"attachment":return{...n,type:"file",mime:e.mime,...e.name!==void 0&&{filename:e.name},...qh(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:iT(e,t,{...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID})};case"step":return e.phase==="start"?{...n,type:"step-start"}:{...n,type:"step-finish",reason:"stop",cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};case"compaction":return{...n,type:"compaction",auto:e.trigger==="auto"||e.trigger==="overflow",...e.trigger==="overflow"&&{overflow:!0},...e.first_kept_message_id!==null&&{tail_start_id:e.first_kept_message_id}};case"harness":return t.fromV1&&(e.harness==="opencode"||e.harness==="pi")?e.data:e.model_visible&&e.fallback_text!==void 0?{...n,type:"text",text:e.fallback_text,synthetic:!0}:void 0;case"subtask":return}}function aT(e){return jg(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function Wh(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:rT.get(e.finish);return{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"assistant",time:{created:t.created,...e.completed_at!==null&&{completed:Xt(e.completed_at)}},...e.reply_to&&{parentID:e.reply_to},modelID:e.model?.model??"",providerID:e.model?.provider??"",...e.model?.variant!==void 0&&{variant:e.model.variant},mode:e.agent??"",agent:e.agent??"",path:{cwd:"",root:""},cost:r?.cost??0,tokens:{input:r?.input??0,output:r?.output??0,reasoning:r?.reasoning??0,cache:{read:r?.cache_read??0,write:r?.cache_write??0}},...s&&{finish:s},...e.error&&{error:aT(e.error)},...n}}function Kh(e,t){return e.role==="assistant"?Wh(e,t):{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"user",time:{created:t.created},agent:e.agent??"",model:{providerID:e.model?.provider??"",modelID:e.model?.model??"",...e.model?.variant!==void 0&&{variant:e.model.variant}}}}function Vh(e,t,n){let r=`${e.message_id}-summary`;return{info:Wh({...e,reply_to:e.message_id,agent:"compaction",finish:e.status==="complete"?"stop":null},n,{id:r,summary:!0}),parts:[{id:`${r}-p0`,...n.sessionID!==null&&{sessionID:n.sessionID},messageID:r,type:"text",text:t.summary}]}}function cT(e,t,n){let r=n||e.producer.harness===Fh;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=ir(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:Xt(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=Gh(d,i);return g===void 0?[]:[Gs(g,ir(d.ext)?.data)]}),c=[{runtime_session_id:o,info:Gs(Kh(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=Gs(Vh(e,p,i),s?.summary);c.push({runtime_session_id:o,info:d.info,parts:d.parts})}return c}var Bg=e=>Ve(F(e.info)&&F(e.info.time)?e.info.time.created:void 0)??-1/0,Ns=e=>String(F(e.info)?e.info.id:""),Hh=(e,t)=>Bg(e)-Bg(t)||(Ns(e)<Ns(t)?-1:Ns(e)>Ns(t)?1:0),Uh=e=>{let t=ir(e.ext);return t?t.native_id??null:e.thread_id};function Vs(e){let t=structuredClone(e),n=t.threads.find(i=>i.parent_thread_id===null)??t.threads[0],r=t.threads.flatMap(i=>i.messages.flatMap(a=>cT(a,Uh(i),ir(i.ext)!==void 0))),s=ir(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?Uh(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(Hh)}}function lT(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:F(e.model)?{p:e.model.providerID,m:e.model.modelID,v:e.model.variant}:{},n=X(t.p),r=X(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...X(t.v)!==void 0&&{variant:t.v}}}function uT(e){if(!F(e.tokens))return null;let t=e.tokens,n=F(t.cache)?t.cache:{};return{input:Ve(t.input)??0,output:Ve(t.output)??0,cache_read:Ve(n.read)??0,cache_write:Ve(n.write)??0,...Ve(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Ve(e.cost)!==void 0&&{cost:e.cost}}}var pT=e=>({code:X(e.code)||X(e.name)||"UnknownError",message:X(F(e.data)?e.data.message:void 0)??""});function zh(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:X(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...X(e.url)!==void 0&&{url:e.url}}}function dT(e,t,n,r){let s=e.state,o=F(s.time)?s.time:{};F(s.input)||r.tool_input++;let i=F(s.metadata)&&Ve(s.metadata.exit)!==void 0?{exit_code:s.metadata.exit}:{},a,c,p=s.input??null;if(s.status==="completed"){let m=(Array.isArray(s.attachments)?s.attachments:[]).filter(F).map(h=>{let{bytes:S,...E}=zh(h,n,r);return{type:"attachment",...E}}),f=Qt(o.compacted);a="complete",c={content:[...X(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:XC}],cleared_at:f}}}else if(s.status==="error"){let m=X(s.error);a="error",c={content:m!==void 0?[{type:"text",text:m}]:[],is_error:!0,...m!==void 0&&{error:{message:m}},...i}}else if(n.live)a=s.status==="pending"?"pending":"running",a==="pending"&&X(s.raw)&&!(F(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=QC[n.h];a="error",c={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=Qt(o.start),g=Qt(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:tT(e.tool),input:p,status:a,...c&&{result:c},...X(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function gT(e,t,n,r,s,o){let i=(a,c=!1)=>({type:"harness",id:t,harness:s.h,kind:a,data:e,model_visible:c,...c&&{fallback_text:ZC}});if(!F(e))return i("unknown");switch(e.type){case"text":return typeof e.text!="string"||e.ignored===!0?i("text"):{type:"text",id:t,text:e.text,...typeof e.synthetic=="boolean"&&{synthetic:e.synthetic}};case"reasoning":return typeof e.text!="string"?i("reasoning"):{type:"reasoning",id:t,text:e.text};case"file":return e.mime==="text/plain"||e.mime==="application/x-directory"?i("file"):{type:"attachment",id:t,...zh(e,s,o),...X(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&F(e.state)?dT(e,t,s,o):i("tool");case"step-start":case"step-finish":return{type:"step",id:t,phase:e.type==="step-start"?"start":"finish"};case"compaction":{if(e!==n)return i("compaction");let a=e.overflow===!0?"overflow":e.auto===!0?"auto":"manual";return{type:"compaction",id:t,summary:r,first_kept_message_id:X(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(X(e.type)||"unknown")}}function mT(e){let t=e.map((s,o)=>F(s)&&typeof s.id=="string"&&s.id?s.id:`#${o}`),n=new Set(t),r=new Set;return t.map(s=>{if(!r.has(s))return r.add(s),s;let o=2;for(;n.has(`${s}#${o}`);)o++;return n.add(`${s}#${o}`),`${s}#${o}`})}function fT(e,t,n,r,s,o){let i=F(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],c=i.role==="user"?a.find(A=>F(A)&&A.type==="compaction"):void 0,p=t&&F(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",g=c?p:d==="assistant"?i:void 0,m=g&&F(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",h=g&&F(g.time)?Qt(g.time.completed):null,S=o.live?"streaming":"interrupted",E=g?m?f?"aborted":"error":h?"complete":S:c?S:"complete",L=Qt(F(i.time)?i.time.created:void 0)??"",D=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(A=>F(A)&&A.type==="text"&&typeof A.text=="string"?[A.text]:[]).join(""):null,w={tool_input:0,cut_point:0,attachment:0},y=mT(a),_=a.map((A,$)=>gT(A,y[$],c,D,o,w)),R=_.some(A=>A.type==="text"||A.type==="attachment"||A.type==="tool_call"||A.type==="harness"&&A.model_visible),v=!s&&d!=="system"&&(c?E==="complete":!m||f&&R),b=o.live&&v&&E!=="streaming"&&_.some(A=>A.type==="tool_call"&&(A.status==="pending"||A.status==="running"))?"streaming":E,P=s?"superseded":v||!m?void 0:f?"aborted":"failed_attempt";return c&&F(c)&&X(c.tail_start_id)===void 0&&w.cut_point++,{m:{...Lg,message_id:X(i.id)??"",thread_id:n,seq:r,role:d,kind:c?"compaction":"turn",status:b,in_context:v,...P&&{hidden_reason:P},agent:X(i.agent)??null,...d==="assistant"&&{reply_to:X(i.parentID)??null},model:lT(i),usage:g?uT(g):null,finish:!g||c?null:f?"aborted":m?"error":nT.get(i.finish)??null,error:m?pT(m):null,created_at:L,completed_at:g||c?h:L||null,producer:JC,blocks:_},lost:w}}function yT(e,t,n,r,s){let o={};t.runtime_session_id!==r&&(o.runtime_session_id=t.runtime_session_id);let i={sessionID:t.runtime_session_id,messageID:e.message_id,created:Xt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=qs(t.parts[d],Gh(p,i));g&&(p.ext=Ks(s,{data:g}))}):o.parts=t.parts;let a=qs(t.info,Kh(e,i));a&&(o.info=a);let c=e.blocks.find(p=>p.type==="compaction");if(n&&c){let p=qs({info:n.info,parts:n.parts},Vh(e,c,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Ks(s,{data:o}))}function hT(e,t,n){if(t){for(let r of[!0,!1])for(let s of e)if(!(s.runtime_session_id===t||!Array.isArray(s.parts))){for(let o of s.parts)if(!(!F(o)||o.type!=="tool"||!F(o.state))&&(r?F(o.state.metadata)&&o.state.metadata.sessionId===t:n(o.state).includes(t)))return{row:s,part:o}}}}function Hs(e,t={}){let n={h:t.harness??"opencode",resolve:t.resolveAttachment??(()=>null),counts:{tool_input:0,cut_point:0,attachment:0},live:t.live===!0},r=structuredClone(e.rows).sort(Hh),s=new Map;for(let w of r){let y=s.get(w.runtime_session_id);y?y.push(w):s.set(w.runtime_session_id,[w])}let o=e.root_id,i=s.has(o),a=new Map,c=w=>a.get(w)??(a.set(w,JSON.stringify(w)),a.get(w)),p=new Map;for(let w of s.keys()){let y=i&&w===o?void 0:hT(r,w,c);y&&p.set(w,y)}let d=[...r].reverse().find(w=>w.runtime_session_id===null||!p.has(w.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=w=>w!==null&&p.has(w)?w:m,h=Qt(r.map(Bg).find(Number.isFinite))??"",S=[];for(let[w,y]of s){if(w!==g&&(w===null||!p.has(w)))continue;let _=w===g,R=_?r.filter(T=>T.runtime_session_id!==g&&f(T.runtime_session_id)===m):[],v=[...R,...y],b=new Set(R),P=new Map,O=new Set;for(let T of v){let q=F(T.info)?T.info:{};if(q.role!=="user"||!Array.isArray(T.parts)||!T.parts.some(H=>F(H)&&H.type==="compaction"))continue;let W=v.find(H=>!O.has(H)&&H.runtime_session_id===T.runtime_session_id&&F(H.info)&&H.info.role==="assistant"&&H.info.summary===!0&&H.info.parentID===q.id);W&&(P.set(T,W),O.add(W))}let A=[];for(let T of v){if(O.has(T))continue;let q=P.get(T),{m:W,lost:H}=fT(T,q,_?m:w,A.length+1,b.has(T),n);if(yT(W,T,q,w,n.h),W.in_context)for(let In of["tool_input","cut_point","attachment"])n.counts[In]+=H[In];A.push(W)}let $=w===null?void 0:p.get(w),N=A.find(T=>T.role==="user"&&T.kind==="turn");S.push({...Lg,thread_id:_?m:w,parent_thread_id:$?f($.row.runtime_session_id):null,spawned_by:$&&typeof $.part.callID=="string"?{message_id:X($.row.info?.id)??"",call_id:$.part.callID}:null,agent:N?.agent??null,title:null,created_at:A[0]?.created_at||h,messages:A,ext:Ks(n.h,w===null?{}:{native_id:w})})}S.sort((w,y)=>w.parent_thread_id===null?-1:y.parent_thread_id===null?1:D(w)-D(y));let E=S[0]?.messages.filter(w=>w.role==="user"&&w.kind==="turn").at(-1),L=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...Lg,session_id:e.session_id,title:null,created_at:h,restore_grade:L?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:E?.agent??null,model:E?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:S,...g!==o&&{ext:Ks(n.h,{data:{root_id:o}})}};function D(w){return r.findIndex(y=>y.runtime_session_id===w.thread_id)}}var Ug={schema:pe,v:1},_T=Object.freeze({}),Yh=new WeakMap;function ar(e){let t=Yh.get(e);if(t&&t.state===e.state)return t.block;let n=e.sessionID??null,r={id:e.messageID,sessionID:e.sessionID,role:"assistant"},o=Hs({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return Yh.set(e,{state:e.state,block:o}),o}var Fg=new WeakMap;function Ng(e){if(Fg.has(e))return Fg.get(e);let t={...Ug,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:ke}},messages:[{...Ug,message_id:"",thread_id:"",seq:1,role:"assistant",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:"",completed_at:null,producer:{harness:"",harness_version:"",adapter_version:""},blocks:[e]}]},{rows:n}=Vs({...Ug,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[t]}),r=n[0].parts[0];return Fg.set(e,r),r}function ae(e){return Ng(e)}var ye=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",He=e=>ye(e)?ae(e):e;function Qh(e){let t=ae(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:_T}var Xh=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function Zh(e){return e.status==="complete"?"completed":e.status}var Jh=new WeakMap;function e_(e){if(e.status!=="complete")return"";let t=Jh.get(e);return t===void 0&&Jh.set(e,t=Xh(e)),t}function t_(e){return e.status==="error"?e.result?.error?.message||Xh(e):void 0}function he(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function bT(e){return he(e)==="bash"}function qg(e){let t=he(e);return t==="question"||t==="ask"}function ST(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var n_=new Set(["show","show_user"]);function Gg(e){return n_.has(he(e))}function PT(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Wg(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||zs(e))}function zs(e){let t=ye(e)?ae(e):e,n=he(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:or(t.state?.input)}var r_=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Kg(e){return r_.has(he(e))}var xT=50*1024*1024,Vg="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",wT=new RegExp(`^beeuni-attachment://(${Vg})/(${Vg})/(${Vg})$`);function zg(e){if(typeof e!="string")return null;let t=wT.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function vT(e){return zg(e)!==null}var Hg=new WeakMap;async function Yg(e,t,n,r={}){if(n.size>xT)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:Hg.get(n)?.get(s);if(o?.promise)return o.promise;let i=o??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let c=Hg.get(n)??new Map;c.set(s,i),Hg.set(n,c)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=l.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(c=>{throw i.promise=void 0,c}),i.promise}async function Jg(e,t){let n=zg(e);if(!n)throw new Error("Invalid attachment reference");let r=C().backendUrl.replace(/\/$/,""),s=await j(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new x("Could not load attachment",{status:s.status});return s.blob()}var AT=new Set(["show","show_user"]);function kT(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return t;let i=e.indexOf("</file>",o+1);if(i===-1)return t;t.push(e.slice(s,o).trimStart()),n=i+7}}var ze=e=>!!e&&typeof e=="object"&&!Array.isArray(e),cr=e=>typeof e=="string"&&e.length>0?e:null,s_=e=>typeof e=="string"?cr(e.split("/").pop()):null;function Ys(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function RT(e){if(Array.isArray(e))return e;if(typeof e!="string"||!e.trim())return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function CT(e){let t=e.blocks.filter(ze).map(n=>n.type==="attachment"?{type:"file",url:n.ref??n.url,filename:n.name,mime:n.mime}:n.type==="tool_call"?{type:"tool",tool:n.name,state:{input:n.input}}:n.type==="harness"&&ze(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function TT(e,t){for(let n of kT(e))t(Ys(n,"attachment"),Ys(n,"filename")??s_(Ys(n,"path")),Ys(n,"mime"))}function ET(e,t){for(let n of[e,...RT(e.items)])ze(n)&&t(n.attachment,s_(n.path),null)}function IT(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=ze(r)&&Array.isArray(r.blocks)?CT(r):r;if(!ze(s)||!ze(s.info)||!Array.isArray(s.parts))continue;let o=cr(s.info.id);if(!o)continue;let i=cr(s.info.role)??"unknown",a=(c,p,d)=>{let g=zg(c);!g||n.has(c)||(n.add(c),t.push({url:c,attachment_id:g.attachmentId,filename:p,mime:d,message_id:o,role:i}))};for(let c of s.parts)ze(c)&&(c.type==="file"?a(c.url,cr(c.filename),cr(c.mime)):c.type==="text"&&typeof c.text=="string"?TT(c.text,a):c.type==="tool"&&typeof c.tool=="string"&&AT.has(he(c.tool))&&ze(c.state)&&ze(c.state.input)&&ET(c.state.input,a))}return t}function ct(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function MT(e,t){if(e==null)return t;let n=e.trim().toLowerCase();return["1","true","yes","y","on"].includes(n)?!0:["0","false","no","n","off"].includes(n)?!1:t}function OT(e){if(e==null)return;let t=e.trim().toLowerCase();if(["1","true","yes","y","on"].includes(t))return!0;if(["0","false","no","n","off"].includes(t))return!1}function Qg(e,t,n){return e!==void 0?e:MT(ct(t),n)}var Xg={get disableMobileAdvertising(){return Qg(C().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Qg(C().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Qg(C().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var DT=new Set(["project-manager"]);function Js(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Xg.enableProjects||!DT.has(e.name)}function jT(e){let t=e.agents.filter(Js),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function o_(){return{projects:{list:At,listForAccount:Yi,get:kt,detail:jn,create:Zi,createRepo:ea,provision:ta,update:Bn,archive:Un,llmCatalog:Ln,modelPicker:$n,modelAccess:rr,setModelAccess:sr,sandboxHealth:Nn,sandboxTemplates:Nc,sessions:Tt,createSession:Et},github:{linkRepository:aa,replaceProjectRepository:ca,getInstallation:la,listInstallations:ua,listLinkableInstallations:pa,listRepositories:da,listRepositoryBranches:ga,linkInstallation:fa,saveInstallation:ma,deleteInstallation:ha,storeUserToken:ya},connectStatus:Dc,marketplace:{items:s=>jd(s),item:s=>Bd(s),itemFile:(s,o)=>Ud(s,o),marketplaces:()=>Ld(),featured:()=>$d(),sources:{list:()=>Fd(),add:s=>Nd(s),remove:s=>qd(s)}}}}var LT=["screen","actions","audio"],$T=["password_managers","messaging","banking"],BT={localHours:8760,remoteDays:3650},UT=[500,1e3,2e3,5e3,1e4],FT=[720,1080,1440,2160],NT={intervalMs:2e3,maxHeight:1440},qT=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function GT(e){let t=e.trim().toLowerCase();if(!t)return null;let n;try{n=new URL(t.includes("://")?t:`https://${t}`).hostname}catch{return null}return n=n.replace(/^www\./,"").replace(/\.$/,""),qT.test(n)?n:null}function WT(e){let t=e.trim();return!t||t.length>255||t.startsWith("-")||/[\u0000-\u001f\u007f]/.test(t)||/\s/.test(t)&&!t.toLowerCase().endsWith(".exe")?null:t}function KT(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var Z=e=>`/accounts/${e}/capture`;function Ye(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}var i_=e=>Ye({q:e.q,kinds:e.kinds?.join(","),app:e.app,limit:e.limit,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,scope:e.scope}),Zg=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function em(e,t={}){return u(await l.get(`${Z(e)}/devices${Ye({user_id:t.userId,scope:t.scope})}`))}async function tm(e,t){return u(await l.delete(`${Z(e)}/devices/${t}`))}async function nm(e,t,n){return u(await l.put(`${Z(e)}/devices/${t}/link`,{user_id:n}))}async function rm(e){return u(await l.get(`${Z(e)}/enrollment-tokens`))}async function sm(e,t){return u(await l.post(`${Z(e)}/enrollment-tokens`,t))}async function om(e,t){return u(await l.delete(`${Z(e)}/enrollment-tokens/${t}`))}async function im(e,t={}){return u(await l.get(`${Z(e)}/enrollments${Ye({status:t.status})}`))}async function am(e,t,n){return u(await l.post(`${Z(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function cm(e,t){return u(await l.post(`${Z(e)}/enrollments/${t}/deny`,{}))}async function lm(e){return u(await l.get(`${Z(e)}/policy`))}async function um(e,t){return u(await l.put(`${Z(e)}/policy`,{policy:t}))}async function pm(e,t={}){return u(await l.get(`${Z(e)}/timeline${Ye(Zg(t))}`))}async function dm(e,t={}){return u(await l.get(`${Z(e)}/timeline/items${Ye(Zg(t))}`))}async function gm(e,t={}){return u(await l.get(`${Z(e)}/days${Ye({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function mm(e,t){return u(await l.get(`${Z(e)}/search${i_(t)}`))}async function fm(e,t,n={}){return u(await l.get(`${Z(e)}/frames/${t}${Ye({user_id:n.userId})}`))}async function ym(e,t,n={}){return u(await l.get(`${Z(e)}/chunks/${t}/media${Ye({user_id:n.userId})}`))}async function hm(e,t,n){return u(await l.get(`${Z(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function _m(e){return u(await l.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function bm(e,t){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function Sm(e){return u(await l.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function Pm(e){return u(await l.get(Z(e)))}async function xm(e,t){return u(await l.patch(Z(e),{enabled:t}))}async function wm(e){return u(await l.get(`/capture/me/search${i_(e)}`))}async function vm(e={}){return u(await l.get(`/capture/me/timeline${Ye(Zg(e))}`))}async function Am(e){return u(await l.get(`/capture/me/frames/${e}`))}function HT(e){return{workspace:{get:()=>Pm(e),setEnabled:t=>xm(e,t)},devices:{list:t=>em(e,t),revoke:t=>tm(e,t),link:(t,n)=>nm(e,t,n),assetUrl:(t,n)=>hm(e,t,n)},enrollment:{tokens:{list:()=>rm(e),create:t=>sm(e,t),revoke:t=>om(e,t)},list:t=>im(e,t),approve:(t,n)=>am(e,t,n),deny:t=>cm(e,t)},policy:{get:()=>lm(e),set:t=>um(e,t)},timeline:{get:t=>pm(e,t),items:t=>dm(e,t),days:t=>gm(e,t)},search:t=>mm(e,t),frame:(t,n)=>fm(e,t,n),media:(t,n)=>ym(e,t,n)}}var a_={account:e=>HT(e),deviceGrant:_m,approveDevice:bm,denyDevice:Sm,me:{search:wm,timeline:vm,frame:Am}};function c_(){return{billing:{accountState:wu,accountStateMinimal:vu,transactions:Au,transactionsSummary:ku,creditBreakdown:Ru,usageHistory:Cu,usageRollup:Nu,sessionCosts:{list:Wu,get:nr},tierConfigurations:Tu,checkout:{createSession:n=>Eu(n),confirmSession:(n,r)=>Iu(n,r)},subscription:{createPortalSession:(n,r)=>Mu(n,r),cancel:(n,r)=>Ou(n,r),reactivate:n=>Du(n),scheduleDowngrade:(n,r,s)=>ju(n,r,s),cancelScheduledChange:n=>Lu(n),prorationPreview:(n,r)=>$u(n,r)},credits:{purchase:n=>Bu(n),autoTopupSettings:n=>Uu(n),configureAutoTopup:n=>Fu(n)}},sandboxShares:{list:ld,create:ud,revoke:pd}}}var Je={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",BEEUNI_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function lt(){let e=ct("BACKEND_URL")||C().backendUrl;return e||"http://localhost:8008/v1"}function It(e){let t=de(e);return t.endsWith("/v1")?t:`${t}/v1`}function lr(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=lr(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return lr(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function zT(e){return e==="running"||e==="active"?"active":e==="queued"||e==="branching"||e==="provisioning"?"provisioning":e==="failed"||e==="error"?"error":e==="stopped"||e==="completed"||e==="archived"?"stopped":e||"unknown"}function Qs(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"daytona",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${lt()}/p/${n.external_id}/${Je.BEEUNI_MASTER}`:""),status:zT(n?.status||t.status),metadata:{...t.metadata??{},project_id:e.project_id,session_id:t.session_id,project_name:e.name,runtime_status:n?.status,error:t.error},created_at:n?.created_at||t.created_at,updated_at:n?.updated_at||t.updated_at}}async function km(){let e=await At(),t=[];for(let n of e){let r=await Tt(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Qs(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Rm(e){let t=await l.get(`/sessions/${encodeURIComponent(e)}`,{showErrors:!1});if(t.success&&t.data)return t.data;if(t.error?.status===400||t.error?.status===404)return null;throw t.error??new Error("Session request failed")}async function Xs(e){let t=await Rm(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await ur(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function ur(e){let t=await km();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}var Zt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function ce(e,t,n){let r=n?.fetch??C().fetch??((p,d)=>fetch(p,d)),s=de(n?.backendUrl??C().backendUrl??"");if(!s)throw new Zt("not_configured","backendUrl is not configured (configureBeeuni / createBeeuni first)",0);let o={accept:"application/json"};t.body!==void 0&&(o["content-type"]="application/json"),t.bearer&&(o.authorization=`Bearer ${t.bearer}`);let i=await r(`${It(s)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:o,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new Zt(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return c}function Zs(e,t){return ce("/auth/signup",{body:e},t)}function eo(e,t){return ce("/auth/sign-in/password",{body:e},t)}function to(e,t){return ce("/auth/sign-in/magic-link",{body:e},t)}function no(e,t){return ce("/auth/verify-otp",{body:e},t)}function ro(e,t){return ce("/auth/sign-in/oauth",{body:e},t)}function so(e,t){return ce("/auth/oauth/exchange",{body:e},t)}function en(e,t){return ce("/auth/refresh",{body:e},t)}function oo(e,t){return ce("/auth/password/reset",{body:e},t)}function io(e,t,n){return ce("/auth/password/update",{body:e,bearer:t},n)}function ao(e,t){return ce("/auth/user",{bearer:e},t)}function co(e,t,n){return ce("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function lo(e,t){return ce("/auth/sign-in/sso",{body:e},t)}var uo={enroll:(e,t,n)=>ce("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>ce(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>ce(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>ce(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function po(e,t={},n){return ce("/auth/sign-out",{body:t,bearer:e},n)}function go(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,c=0,p=new Set,d=S=>(S.expires_at??0)*1e3,g=S=>d(S)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let S of[...p])try{S(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let S=c,E=(async()=>{let L=await e.storage.get();if(S===c&&L)try{let D=JSON.parse(L);D.session?.access_token&&D.session?.refresh_token&&(r=D.session,s=D.user??null)}catch{r=null}return o=!0,r})();i=E,E.then(()=>{i===E&&(i=null)},()=>{i===E&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let S=r.refresh_token,E=c,L=en({refresh_token:S},e.request).then(async D=>(E!==c||(r=D.session,D.user&&(s=D.user),await m()),r)).catch(async D=>{if(E!==c)return r;let w=D&&typeof D=="object"&&"status"in D?D.status:0;if(w>=400&&w<500)return r=null,s=null,await m(),null;throw D}).finally(()=>{a===L&&(a=null)});a=L}return a}return{subscribe(S){return p.add(S),()=>{p.delete(S)}},current:()=>r,user:()=>s,load:f,async set(S,E){await f(),c+=1,a=null,r=S,E!==void 0&&(s=E),S||(s=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){c+=1,a=null,r=null,s=null,o=!0,await m()}}}function l_(){return{list:Ri,get:Ti,create:Ci,secretResources:{list:Ya,create:Ja,rotate:Qa,retry:Xa,remove:Za,grant:ec,revoke:tc,setAccess:nc},updateName:Ei,branding:{get:Ii,update:Mi,uploadAsset:Oi,removeAsset:Di,reset:ji},leave:Hi,members:Li,invite:$i,removeMember:Ki,updateMemberRole:Vi,invites:Bi,cancelInvite:Ui,resendInvite:Fi,tokens:{list:hd,create:_d,revoke:bd},connectedApps:{list:Sd,revoke:Pd},audit:{log:kd,export:Cd,webhooks:{list:Td,create:Ed,update:Id,remove:Md}}}}function u_(){return{assignments:{list:Zp,create:ed,revoke:td},permissions:{list:nd,forRole:Up},roles:{list:Lp,create:Np,update:qp,setPermissions:Gp,remove:Wp,usage:Fp},groups:{list:Cp,get:Tp,create:Ep,update:Ip,remove:Mp,members:{list:Op,add:Dp,remove:jp}},agentIdentities:$p,oauthClients:{list:Hp,get:zp,create:Yp,update:Jp,rotateSecret:Qp,remove:Xp},can:Kp,canBatch:Vp}}function p_(){let e={signUp:Zs,signInWithPassword:eo,sendMagicLink:to,verifyOtp:no,signInWithProvider:ro,exchangeCode:so,refresh:en,resetPassword:oo,updatePassword:io,updateUserMetadata:co,signInWithSso:lo,mfa:uo,user:ao,signOut:po,session:go},t=l_(),n=u_();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Ni,describe:qi,accept:us,acceptAndLand:Gi,decline:Wi}}}var pr=new Map,Cm=new Map;function Tm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function d_(e){return pr.get(Tm(e))??null}function g_(){return[...pr.values()].filter(e=>typeof e=="string")}function m_(e){return pr.has(Tm(e))}async function ut(e){let t=Tm(e),n=pr.get(t);if(n!==void 0)return n;let r=Cm.get(t);if(r)return r;let s=(async()=>{try{let o=await l.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let i=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return pr.set(t,i),i}catch{return null}finally{Cm.delete(t)}})();return Cm.set(t,s),s}function f_(e){let{apiBaseUrl:t}=e;return m_(t)||ut(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:d_(t)}}function y_(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new x(`Beeuni SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/beeuni" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let s=C().backendUrl??e.backendUrl,o=80,i=t(s);return i&&(o=i.port?Number(i.port):i.protocol==="https:"?443:80),f_({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function h_(e,t){let n=null;async function r(){n||(n=zn(e,t,{showErrors:!1}).then(s=>{let o=er(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,c=s.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var tn={url:null,sandboxId:null,dbSandboxId:null,version:0},JT=new Set;function mo(e,t=null,n=null){if(!(tn.url===e&&tn.sandboxId===t&&tn.dbSandboxId===n)){tn={url:e,sandboxId:t,dbSandboxId:n,version:tn.version+1};for(let r of JT)r()}}function __(){return tn.url}var dr=new Map;function b_(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Mt=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function S_(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await it(e,t,Math.min(3e4,o()));for(;Date.now()<s&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,o()))),i=await it(e,t,Math.min(3e4,o()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new x(b_(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new x("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ie(c);return mo(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function P_(e,t,n){let r=null;function s(){if(r)return r;let p=ph(e,t);return p&&(r=p),r}let o=S_(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=ut(C().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?mu(p.session):null,h=f?.sandbox?.external_id,S=f?.runtime_session_id;if(h&&S){let w=Ie(h);return mo(w,h),r={runtimeSessionId:S,opencodeSessionId:S,runtimeUrl:w,sandboxId:h},Ts(e,t,r),await m,r}let E=`${e}
|
|
15
|
+
${t}`,L=dr.get(E);if(L)return r=await L,await m,r;let D=o(g);dr.set(E,D);try{return r=await D,await m,r}finally{dr.get(E)===D&&dr.delete(E)}}function a(p){let d=s();if(!d)throw new Mt(p);return d}function c(){r=null,dh(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:c}}var V=["directory","workspace"],x_=["messageID","model","agent","noReply","tools","format","system","variant","parts"],I=(e,t,n=V,r=[],s)=>({method:e,path:t,query:n,body:r,bodyParam:s}),QT={"session.list":I("GET","/session",[...V,"scope","path","roots","start","search","limit"]),"session.get":I("GET","/session/{sessionID}"),"session.create":I("POST","/session",V,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":I("DELETE","/session/{sessionID}"),"session.update":I("PATCH","/session/{sessionID}",V,["title","metadata","permission","time"]),"session.status":I("GET","/session/status"),"session.messages":I("GET","/session/{sessionID}/message",[...V,"limit","before"]),"session.prompt":I("POST","/session/{sessionID}/message",V,x_),"session.promptAsync":I("POST","/session/{sessionID}/prompt_async",V,x_),"session.abort":I("POST","/session/{sessionID}/abort"),"session.revert":I("POST","/session/{sessionID}/revert",V,["messageID","partID"]),"session.unrevert":I("POST","/session/{sessionID}/unrevert"),"session.summarize":I("POST","/session/{sessionID}/summarize",V,["providerID","modelID","auto"]),"session.command":I("POST","/session/{sessionID}/command",V,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":I("POST","/session/{sessionID}/share"),"session.unshare":I("DELETE","/session/{sessionID}/share"),"session.fork":I("POST","/session/{sessionID}/fork",V,["messageID"]),"session.diff":I("GET","/session/{sessionID}/diff",[...V,"messageID"]),"session.todo":I("GET","/session/{sessionID}/todo"),"permission.list":I("GET","/permission"),"permission.reply":I("POST","/permission/{requestID}/reply",V,["reply","message"]),"question.list":I("GET","/question"),"question.reply":I("POST","/question/{requestID}/reply",V,["answers"]),"question.reject":I("POST","/question/{requestID}/reject"),"part.update":I("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",V,[],"part"),"part.delete":I("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":I("GET","/file",[...V,"path"]),"file.read":I("GET","/file/content",[...V,"path"]),"find.files":I("GET","/find/file",[...V,"query","dirs","type","limit"]),"vcs.diff":I("GET","/vcs/diff",[...V,"mode","context"]),"global.health":I("GET","/global/health",[]),"global.dispose":I("POST","/global/dispose",[]),"global.config.get":I("GET","/global/config",[]),"global.config.update":I("PATCH","/global/config",[],[],"config"),"provider.list":I("GET","/provider"),"provider.auth":I("GET","/provider/auth"),"provider.oauth.authorize":I("POST","/provider/{providerID}/oauth/authorize",V,["method","inputs"]),"provider.oauth.callback":I("POST","/provider/{providerID}/oauth/callback",V,["method","code"]),"auth.set":I("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":I("GET","/agent"),"app.skills":I("GET","/skill"),"app.log":I("POST","/log",V,["service","level","message","extra"]),"command.list":I("GET","/command"),"tool.ids":I("GET","/experimental/tool/ids"),"tool.list":I("GET","/experimental/tool",[...V,"provider","model"]),"mcp.status":I("GET","/mcp"),"mcp.add":I("POST","/mcp",V,["name","config"]),"mcp.connect":I("POST","/mcp/{name}/connect"),"mcp.disconnect":I("POST","/mcp/{name}/disconnect"),"mcp.auth.start":I("POST","/mcp/{name}/auth"),"mcp.auth.callback":I("POST","/mcp/{name}/auth/callback",V,["code"]),"mcp.auth.remove":I("DELETE","/mcp/{name}/auth"),"project.list":I("GET","/project"),"project.current":I("GET","/project/current"),"path.get":I("GET","/path")};function XT(e,t){let n=[];for(let r of e.query){let s=t[r];s!=null&&n.push(`${r}=${encodeURIComponent(String(s))}`)}return n.length?`?${n.join("&")}`:""}function ZT(e,t,n={},r={}){let s=QT[t],o=s.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(s.bodyParam)i=n[s.bodyParam],a=i!==void 0;else for(let p of s.body)p in n&&(i={...i,[p]:n[p]},a=!0);let c=new Headers(r.headers);return a&&c.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${o}${XT(s,n)}`,{method:s.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function eE(e){if(!e)return"stream";let t=e.split(";")[0]?.trim()??"";return t.startsWith("application/json")||t.endsWith("+json")?"json":t==="multipart/form-data"?"formData":["application/","audio/","image/","video/"].some(n=>t.startsWith(n))?"blob":t.startsWith("text/")?"text":"json"}async function tE(e,t){let n=e.fetch??globalThis.fetch,r;try{r=await n(t)}catch(i){return{error:i||{},request:t,response:void 0}}if(r.headers.get("content-type")==="text/html")throw new Error("The session runtime does not serve this request (it answered text/html)");if(r.ok){let i=eE(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let s=await r.text(),o=s;try{o=JSON.parse(s)}catch{}return{error:o||{},request:t,response:r}}function Em(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let s=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!s.ok)throw Object.assign(new Error(`SSE failed: ${s.status} ${s.statusText}`),{status:s.status});if(!s.body)throw new Error("No body in SSE response");let o=s.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{o.cancel().catch(()=>{})}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:c,value:p}=await o.read();if(c)break;a=(a+p).replace(/\r\n/g,`
|
|
16
16
|
`).replace(/\r/g,`
|
|
17
17
|
`);let d=a.split(`
|
|
18
18
|
|
|
19
|
-
`);a=d.pop()??"";for(let g of d){let m={},
|
|
20
|
-
`))if(h.startsWith("data:"))
|
|
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??""}
|
|
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 S=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(S)||(m.retry=S)}f.length&&(m.data=f.join(`
|
|
21
|
+
`)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*nE(e,t,n){let r=e.eventTransport??Em(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal:s}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(o=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(c){if(n.onSseError?.(c),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(o*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function gr(e){let t=s=>(o,i)=>tE(e,ZT(e.baseUrl,s,o,i)),n=s=>o=>t(s)(void 0,o);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(s={})=>({stream:nE(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,s)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var w_=200;async function rE(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function Ot(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new x(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function v_(e){let t=e.runtimeUrl.replace(/\/$/,""),n=gr({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${s}${d.size?`?${d}`:""}`,m=S=>e.fetch(new Request(`${t}${S}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/beeuni/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/beeuni/opencode")),!f.ok)throw new x(`Reading the session transcript failed: ${await rE(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,w_),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await o(Math.min(r.limit-a.length,w_),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,s,o]=await Promise.all([n.session.status().then(i=>Ot(i,"Reading the session status failed")),n.permission.list().then(i=>Ot(i,"Reading permission requests failed")),n.question.list().then(i=>Ot(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{Ot(await n.permission.reply({requestID:r,reply:s,...o!==void 0?{message:o}:{}}),"Answering the permission request failed")},answerQuestion:async(r,s)=>{if(s===null){Ot(await n.question.reject({requestID:r}),"Dismissing the question failed");return}Ot(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let o=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof o?.model=="string"?o.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(s={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!s)throw new x("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return Ot(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function A_(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return v_({runtimeUrl:r,rootId:n,fetch:j})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,s)=>(await t()).answerPermission(n,r,s),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function k_(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await nu(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var nn=BigInt(4096),Qe=BigInt(0xffffffffffff),R_=Qe+BigInt(1),sE=R_/BigInt(2),pt=BigInt(3600*1e3)*nn,fo=120*1e3,C_=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,oE=/^msg_([0-9a-f]{12})/,T_="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Dt(e){let t=oE.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function rn(e){return BigInt(Math.trunc(e))*nn&Qe}function jt(e,t){let n=e-t&Qe;return n>=sE&&(n-=R_),n}function Im(e){let t=null;for(let n of e)n!=null&&(t===null||jt(n,t)>BigInt(0))&&(t=n);return t}function E_(e,t){let n=Dt(e);return n===null?!1:jt(n,rn(t))>pt}function I_(e,t){let n=t===void 0?null:rn(t);return M_(e,r=>n===null||jt(r,n)<=pt)}function M_(e,t){let n=[];for(let r of e){let s=Dt(r);s!==null&&t(s)&&n.push(s)}return Im(n)}function iE(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=T_[n%62])}return e}function Mm(e){let t=e.random,n=rn(e.nowMs-(e.backdateMs??fo)),r=e.newestKnownTime??null;if(r!==null){let o=jt(r,n);o>=BigInt(0)&&o<=pt&&(n=r+BigInt(1)&Qe)}let s="";if(t)for(let o=0;o<14;o++)s+=T_[Math.min(61,Math.floor(t()*62))];else s=iE();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function yo(e={}){let t=e.nowMs??Date.now(),n=rn(t-fo),r=M_(e.after??[],s=>{let o=jt(s,n);return o>=BigInt(0)&&o<=pt});return Mm({nowMs:t,newestKnownTime:r}).id}function O_(e){return{scope:()=>eu(e.projectId,e.sessionId),providerSecretPool:{list:()=>sc(e.projectId,e.sessionId),get:t=>rc(e.projectId,e.sessionId,t),set:(t,n)=>oc(e.projectId,e.sessionId,t,n)},rescope:t=>tu(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,s=n?.agent??e.agent,o=r&&s?{}:await e.persistedPromptDefaults(),i=r??o.model,a=s??o.agent,c=yo(),p=await Qn(e.projectId,e.sessionId,{clientMessageId:c,messageId:c,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new x("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var D_=async function*(e){let t=C().eventStreamTransport;if(!t){yield*Em(((s,o)=>j(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await as(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function Xe(){let e=__();return e||(C().billingEnabled??!1?"":gh())}async function Om(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Dm(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function jm(e){let t=Dm(e),n=await j(`${t}/env`);if(!n.ok)throw new Error(await Om(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Lm(e,t,n){let r=Dm(e),s=await j(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await Om(s,"Failed to save secret"))}async function $m(e,t){let n=Dm(e),r=await j(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Om(r,"Failed to delete secret"))}var j_={list:jm,set:Lm,delete:$m};async function L_(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await j(`${r}/beeuni/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}async function ho(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function mr(e){if(!e)throw new Error("[beeuni-pty] Server URL not ready \u2014 sandbox is still loading");return de(e)}async function Um(e){let t=mr(e),n=await j(`${t}/beeuni/pty`);if(!n.ok)throw new Error(await ho(n,"Failed to list terminals"));return n.json()}async function Fm(e,t){let n=mr(e),r=await j(`${n}/beeuni/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await ho(r,"Failed to create terminal"));return r.json()}async function Nm(e,t,n){let r=mr(e),s=await j(`${r}/beeuni/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await ho(s,"Failed to update terminal"));return s.json()}async function qm(e,t){let n=mr(e),r=await j(`${n}/beeuni/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await ho(r,"Failed to remove terminal"))}async function Gm(e,t,n){let r=mr(t),o=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),de(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/beeuni/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await st();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${o}${o.includes("?")?"&":"?"}${c}`:o}function $_(e){let t=e.reason.trim().toLowerCase();return t.includes("pty not found")?"replace":t.includes("pty exited")?"ended":e.hadError||t.includes("idle timeout")||t.includes("upstream error")||e.code!==1e3?"reconnect":"ended"}var dt="\x1B",B_="\x07",aE="\0",Bm=`(?:${B_}|${dt}\\\\)`,cE=[new RegExp(`${dt}\\]697;[^${B_}${dt}]*${Bm}`,"g"),new RegExp(`${aE}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${dt}\\][0-9]+;rgb:[0-9a-fA-F/]+${Bm}`,"g"),new RegExp(`${dt}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Bm}`,"g"),new RegExp(`${dt}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${dt}\\[\\d+;\\d+R`,"g"),new RegExp(`${dt}\\[\\?[0-9;]*c`,"g")];function U_(e){let t=e;for(let n of cE)t=t.replace(n,"");return t}var F_={list:Um,create:Fm,update:Nm,remove:qm,webSocketUrl:Gm};async function M(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await j(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await o.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!o.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${o.status}`);return a}async function lE(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return M(e,`/beeuni/tasks${r}`)}async function uE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}`)}async function pE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}/events`)}async function dE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}/status`)}async function gE(e,t){return M(e,"/beeuni/tasks",{method:"POST",body:JSON.stringify(t)})}async function mE(e,t,n){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function fE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function yE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function hE(e,t){return M(e,`/beeuni/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function _E(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return M(e,`/beeuni/tickets${n}`)}async function bE(e,t){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}`)}async function SE(e,t){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}/events`)}async function PE(e,t){return M(e,"/beeuni/tickets",{method:"POST",body:JSON.stringify(t)})}async function xE(e,t,n){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function wE(e,t,n){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function vE(e,t,n){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function AE(e,t,n){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function kE(e,t,n){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function RE(e,t){return M(e,`/beeuni/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function CE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/columns`)}async function TE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function EE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/fields`)}async function IE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function ME(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/templates`)}async function OE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function DE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function jE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/agents`)}async function LE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function $E(e,t,n,r){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function BE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function UE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function FE(e,t,n=200){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function NE(e){return M(e,"/beeuni/projects")}async function qE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}`)}async function GE(e,t){return M(e,`/beeuni/projects/by-session/${encodeURIComponent(t)}`)}async function WE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/sessions`)}async function KE(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function VE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function HE(e,t,n="all"){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function zE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function YE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function JE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function QE(e,t,n,r){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function XE(e,t,n,r){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function ZE(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function eI(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function tI(e,t){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials`)}async function nI(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function rI(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function sI(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function oI(e,t,n){return M(e,`/beeuni/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var iI=1e4,aI={retryOnAuthError:!1};function sn(e,t,n){return M(e,t,{signal:AbortSignal.timeout(iI),...n},aI)}async function cI(e,t=!1){return(await sn(e,`/beeuni/services${t?"?all=true":""}`)).services??[]}async function lI(e){return(await sn(e,"/beeuni/services/templates")).templates??[]}async function uI(e,t){return(await sn(e,`/beeuni/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function pI(e,t,n){let r=n==="delete",s=r?`/beeuni/services/${encodeURIComponent(t)}`:`/beeuni/services/${encodeURIComponent(t)}/${n}`;return sn(e,s,{method:r?"DELETE":"POST"})}async function dI(e,t){return sn(e,`/beeuni/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function gI(e,t){return sn(e,"/beeuni/services/register",{method:"POST",body:JSON.stringify(t)})}var Ze=new Map,mI=256,on=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function gt(){let e=Xe();if(!e)throw new on;return Oe(e)}function Oe(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Ze.get(e);if(t)return Ze.delete(e),Ze.set(e,t),t;if(!Zr())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureBeeuni()/createBeeuni() before talking to a sandbox runtime.");let n=gr({baseUrl:e,fetch:j,eventTransport:D_});return Ze.set(e,n),Ze.size>mI&&Ze.delete(Ze.keys().next().value),n}function fI(e){Ze.delete(e)}function yI(){Ze.clear()}var _o=new Map;function hI(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=_o.get(e);if(t)return t;let n=gr({baseUrl:e,fetch});return _o.set(e,n),n}function _I(e){_o.delete(e)}function bI(){_o.clear()}async function SI(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n?.error||n?.message||t||e.statusText||`HTTP ${e.status}`}catch{return t||e.statusText||`HTTP ${e.status}`}}async function PI(e){let t=Xe();if(!t)throw new x("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/beeuni/refresh":"/global/dispose",r=await j(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new x(`System reload failed (${r.status}): ${await SI(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new x(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new x(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var N_="frontend";function bo(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${N_}] ${t}`,...n?[n]:[]);try{gt().app.log({service:N_,level:e,message:t,extra:n})}catch{}}var mt={debug:(e,t)=>bo("debug",e,t),info:(e,t)=>bo("info",e,t),warn:(e,t)=>bo("warn",e,t),error:(e,t)=>bo("error",e,t)};function q_(e){return{type:"heartbeat-gap",gapMs:e}}function G_(e){switch(e.type){case"message.updated":return{type:"message.updated",sessionID:e.properties.sessionID,message:e.properties.info};case"message.removed":return{type:"message.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID};case"message.part.updated":return{type:"message.part.updated",sessionID:e.properties.sessionID,part:e.properties.part};case"message.part.removed":return{type:"message.part.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID,partID:e.properties.partID};case"session.status":return{type:"session.status",sessionID:e.properties.sessionID,status:e.properties.status};case"session.idle":return{type:"session.idle",sessionID:e.properties.sessionID};case"session.error":return{type:"session.error",sessionID:e.properties.sessionID,error:e.properties.error};case"question.asked":return{type:"question.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,questions:e.properties.questions,tool:e.properties.tool};case"question.replied":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"replied",answers:e.properties.answers};case"question.rejected":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"rejected"};case"permission.asked":return{type:"permission.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,permission:e.properties.permission,patterns:e.properties.patterns,tool:e.properties.tool};case"permission.replied":return{type:"permission.replied",sessionID:e.properties.sessionID,requestID:e.properties.requestID,reply:e.properties.reply};case"todo.updated":return{type:"todo.updated",sessionID:e.properties.sessionID,todos:e.properties.todos};case"server.connected":return{type:"connection",status:"connected"};default:return null}}var xI={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},wI=16,vI=8,AI=6e4,kI=5e3,RI=250,CI=1e3,TI=3e4,EI=5,II=1e4,MI=4,OI=.5,DI=3e3,jI=3e4,LI=2e4,$I=2e3,BI=8;function UI(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function FI(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function W_(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}var fr=new WeakMap;function NI(e,t,n){let r=t.timers??xI,s=t.connectTimeoutMs??LI,o=t.heartbeatTimeoutMs??AI,i=t.maxConsecutiveHardFailures??BI,a=new AbortController;function c(y,..._){for(let R of n){let v=y(R);if(v)try{v(..._)}catch(b){console.warn("[opencode-events] subscriber handler threw, skipping",b)}}}let p=null,d=!1,g=y=>{p!==y&&(p=y,y&&c(_=>_.onConnectionChange,y))},m=r.now(),f=null,h=[],S,E=0,L=new Map,D=()=>{if(S&&r.clearTimeout(S),S=void 0,h.length===0)return;let y=h;h=[],L.clear(),E=r.now(),m=r.now();for(let _ of y)_&&c(R=>R.onEvent,_.event)},w=()=>{if(S)return;let y=r.now()-E;S=r.setTimeout(D,Math.max(0,wI-y))};return(async()=>{let y=0,_=0,R=0;for(;!a.signal.aborted;){let v=!1,b=!1,P,O,A=null,$=r.now(),N=new AbortController;g("connecting");let T=W_(a.signal);T.promise.then(()=>N.abort());try{let ne=await new Promise((Ut,xt)=>{let me=!1;O=r.setTimeout(()=>{me||(me=!0,mt.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:s}),N.abort(),xt(new Error(`SSE connect timed out after ${s}ms`)))},s),e.global.event({signal:N.signal,sseDefaultRetryDelay:DI,sseMaxRetryDelay:jI,sseMaxRetryAttempts:1}).then(Be=>{me||(me=!0,r.clearTimeout(O),Ut(Be))},Be=>{me||(me=!0,r.clearTimeout(O),xt(Be))})}),{stream:St}=ne;if(f){let Ut=r.now()-f.lastActivityAt,xt=f.eventful;f=null,(xt||Ut>kI)&&c(me=>me.onGapRehydrate,Ut)}m=r.now();let Pt=()=>{r.clearTimeout(P),P=r.setTimeout(()=>{mt.warn("SSE heartbeat timeout, forcing reconnect"),N.abort()},o)};Pt();let Jr=r.now(),zw=St[Symbol.asyncIterator]();for(;!N.signal.aborted;){let Ut=zw.next().then(Ue=>({kind:"next",result:Ue}),Ue=>({kind:"error",error:Ue})),xt=W_(N.signal),me=await Promise.race([Ut,xt.promise.then(()=>({kind:"aborted"}))]);if(xt.cleanup(),me.kind==="aborted")break;if(me.kind==="error")throw me.error;if(me.result.done)break;g("open"),Pt();let Be=me.result.value,Ft=Be&&typeof Be=="object"&&"payload"in Be?Be.payload:Be;if(!Ft?.type)continue;Ft.type!=="server.connected"&&(v=!0);let ci=FI(h[h.length-1]?.event,Ft);if(ci)h[h.length-1]={type:ci.type,event:ci};else{let Ue=UI(Ft);if(Ue){let ky=L.get(Ue);ky!==void 0&&(h[ky]=void 0),L.set(Ue,h.length)}h.push({type:Ft.type,event:Ft})}w(),!(r.now()-Jr<vI)&&(await new Promise(Ue=>r.setTimeout(Ue,0)),Jr=r.now())}b=v}catch(ne){if(a.signal.aborted)break;A=ne;let St=String(ne),Pt=Nt(ne)||Nt(ne?.cause);if(mt.error("SSE event stream error",{error:St,retryCount:y,isAuthError:Pt}),Pt)try{gs(),await st(),mt.info("SSE: refreshed auth token after auth error")}catch(Jr){mt.error("SSE: failed to refresh auth token",{error:String(Jr)})}}finally{r.clearTimeout(P),r.clearTimeout(O),N.abort(),T.cleanup(),D()}if(a.signal.aborted)break;let q=r.now()-$,W=A?.cause?.status;if(_=!v&&(typeof W=="number"&&W>=400||q<$I)?_+1:0,_>=i){mt.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:_,lastError:String(A)}),p=null,d=!0,c(ne=>ne.onParked,{consecutiveFailures:_,lastError:A});break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||v},R=b&&q<II?R+1:0;let Le=b&&R<=MI;Le?y=0:(y++,y>1&&mt.warn("SSE event stream reconnecting",{retryCount:y}));let Mn=Le?RI:Math.min(CI*2**Math.min(y-1,EI),TI),$e=Math.round(Mn*(1+OI*(r.random?.()??0)));await new Promise(ne=>{let St=r.setTimeout(ne,$e),Pt=()=>{r.clearTimeout(St),ne()};a.signal.addEventListener("abort",Pt,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),S&&r.clearTimeout(S)}}}function So(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?Oe(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s},c=fr.get(i);if(c?.isParked()&&(fr.delete(i),c=void 0),!c)c=NI(i,e,new Set([a])),fr.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&s?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),fr.get(i)===p&&fr.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function K_(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Oe(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Oe(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Oe(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return So({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Y_(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new x(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function ln(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function se(e){let t=(e??Xe()).trim();if(!t)throw new on;return t}async function xo(e,t){let n=await j(`${se(t)}${e}`);if(!n.ok)throw new x(await ln(n),{status:n.status,response:n});return n.json()}var wo=["/workspace","/tmp","/home","/opt"],qI=wo.filter(e=>e!=="/workspace");function Vm(e){return wo.some(t=>e===t||e.startsWith(`${t}/`))}function un(e){return Vm(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function ft(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(qI.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Hm=ft;async function pn(e,t){let n=se(t),r=ft(e)||".";return(await xo(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function dn(e,t){let n=se(t),r=ft(e),s=await j(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!s.ok)throw new x(await ln(s),{status:s.status,response:s});return s.json()}async function GI(e,t,n){let r=se(n),s=ft(e),o=await j(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new x(await ln(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new x("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var WI=8,Po=0,J_=[];async function KI(){if(Po<WI){Po++;return}await new Promise(e=>J_.push(e)),Po++}function VI(){Po--,J_.shift()?.()}function Q_(e,t){let n=se(t);return qn(`${n}/file/raw?path=${encodeURIComponent(ft(e))}`)}async function gn(e,t){await KI();try{let n=se(t);try{return await GI(e,void 0,n)}catch{}let r=await dn(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{VI()}}async function _r(e){return xo("/file/status",se(e))}async function br(e,t,n){let r=se(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),xo(`/find/file?${s.toString()}`,r)}async function Sr(e,t){let n=se(t);return(await xo(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var yr=[400,1200],HI=e=>e===408||e===429||e===502||e===503||e===504,V_=e=>new Promise(t=>setTimeout(t,e));function zI(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Wm=3e4,X_=15*6e4,YI=256;function an(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Wm;let t=Wm+e/YI;return Math.min(X_,Math.max(Wm,Math.round(t)))}async function JI(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function hr(e,t){let n;for(let s=0;s<=yr.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,zI(a)||s===yr.length)break;await V_(yr[s]);continue}if(o.ok)return o.json();let i=await JI(o);if(n=new x(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!HI(o.status)||s===yr.length)throw n;await V_(yr[s])}if(n instanceof x)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new x(`Upload failed: ${r}`)}var Km=8*1024*1024;function QI(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new x(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function H_(e,t){try{e?.onProgress?.(t)}catch{}}function z_(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function XI(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function mn(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=se(o),c=an(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Km){let f=await hr(()=>z_(e,t,p),h=>j(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return QI(f[0],e.size),H_(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await hr(()=>z_(new Blob([],{type:e.type}),t,p),f=>j(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:an(0)})))[0]?.path;if(!g)throw new x("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=XI(g);if(!m.name)throw new x(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=Km){let h=Math.min(e.size,f+Km),S=e.slice(f,h,e.type),E=await hr(()=>{let L=new FormData;return m.parent&&L.append("path",m.parent),L.append("filename",m.name),L.append("first",f===0?"true":"false"),L.append("offset",String(f)),L.append("file",S,m.name),L},L=>j(`${a}/file/append`,{method:"POST",body:L},{timeoutMs:an(S.size)}));if(E.path!==g||E.size!==h)throw new x(`Upload verification failed for ${g}: expected ${h} bytes, received ${E.size}`,{code:"UPLOAD_SIZE_MISMATCH"});H_(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await Lt(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function Z_(e,t,n){let r=se(n);return hr(()=>{let s=new FormData;return t&&s.append("path",t),s.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),s},s=>j(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:ZI}))}var ZI=X_;function eM(e,t,n){let r=se(n),s=an(t.size);return hr(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>j(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var cn=class extends x{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function Pr(e,t){let n=se(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",c=un(`${a}/${i}`),p=[];try{p=await pn(eb(c),n)}catch(g){if(!(g instanceof x&&g.status===404))throw g}if(p.some(g=>g.name===tb(c)))throw new cn(c);let d=await nb(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function xr(e,t,n){let r=se(n);return eM(t,await gn(e,r),r)}function tM(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function eb(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function tb(e){return e.slice(e.lastIndexOf("/")+1)}function nM(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function wr(e,t,n){let r=se(n),s=un(tM(e.trim()));return nb(s,t,r,{overwrite:!0})}async function nb(e,t,n,r){let s=tb(e);if(!s)throw new x(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=eb(e);await fn(o,n).catch(()=>{});let i=nM(),a=await mn(t,o,`.${s}.beeuni-write-${i}`,n),c=a[0]?.path;if(!c)throw new x(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=un(c);try{await rb(p,e,n,r.overwrite)}catch(g){throw await Lt(p,n).catch(()=>{}),!r.overwrite&&g instanceof x&&g.status===409?new cn(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Lt(e,t){let n=await j(`${se(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new x(`Delete failed (${n.status}): ${await ln(n)}`,{status:n.status,response:n});return n.json()}async function fn(e,t){let n=await j(`${se(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new x(`Mkdir failed (${n.status}): ${await ln(n)}`,{status:n.status,response:n});return n.json()}async function vr(e,t,n){return rb(e,t,se(n),!0)}async function rb(e,t,n,r){let s=await j(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!s.ok)throw new x(`Rename failed (${s.status}): ${await ln(s)}`,{status:s.status,response:s});return s.json()}async function zm(){return Y_(await gt().project.current())}async function vo(){return Y_(await gt().global.health())}async function Ym(){try{return(await vo()).healthy===!0}catch{return!1}}var sb={list:pn,read:dn,readBlob:gn,status:_r,findFiles:br,findText:Sr,upload:mn,write:wr,create:Pr,copy:xr,remove:Lt,mkdir:fn,rename:vr,currentProject:zm,health:vo,isReachable:Ym,toDaemonPath:ft,toSandboxAbsolutePath:un,toWorkspaceRelative:Hm};function ob(e){return{list:async t=>pn(t,(await e()).runtimeUrl),read:async t=>dn(t,(await e()).runtimeUrl),readBlob:async t=>gn(t,(await e()).runtimeUrl),status:async()=>_r((await e()).runtimeUrl),findFiles:async(t,n)=>br(t,n,(await e()).runtimeUrl),findText:async t=>Sr(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>mn(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>wr(t,n,(await e()).runtimeUrl),create:async t=>Pr(t,(await e()).runtimeUrl),copy:async(t,n)=>xr(t,n,(await e()).runtimeUrl),remove:async t=>Lt(t,(await e()).runtimeUrl),mkdir:async t=>fn(t,(await e()).runtimeUrl),rename:async(t,n)=>vr(t,n,(await e()).runtimeUrl)}}function ib(e){return{get:t=>zn(e.projectId,e.sessionId,t),presence:(t,n)=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>nr(e.sessionId,{projectId:e.projectId}),update:t=>Hl(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),zl(e.projectId,e.sessionId)),restore:()=>Jl(e.projectId,e.sessionId),recover:()=>Yl(e.projectId,e.sessionId),start:(...t)=>it(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>fu(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Xn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Zn(e.projectId,e.sessionId)),configState:()=>Ql(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),Xl(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),Zl(e.projectId,e.sessionId,...t)),setSharing:t=>kl(e.projectId,e.sessionId,t),previews:()=>Ml(e.projectId,e.sessionId),participants:()=>Rl(e.projectId,e.sessionId),watch:()=>Cl(e.projectId,e.sessionId),setWatch:t=>Tl(e.projectId,e.sessionId,t),setPinned:t=>El(e.projectId,e.sessionId,t),setArchived:t=>Il(e.projectId,e.sessionId,t),commit:t=>bl(e.projectId,e.sessionId,t),publicShares:{list:()=>Ol(e.projectId,e.sessionId),create:(...t)=>Dl(e.projectId,e.sessionId,...t),revoke:(...t)=>jl(e.projectId,e.sessionId,...t)}}}function ab(e){return{reminders:{list:()=>dd(e.projectId,e.sessionId),create:t=>gd(e.projectId,e.sessionId,t),update:(t,n)=>Ls(e.projectId,e.sessionId,t,n),remove:t=>$s(e.projectId,e.sessionId,t)},audit:(t,n)=>Bl(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Yg(e.projectId,e.sessionId,t,n),read:(t,n)=>Jg(`beeuni-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Ul(e.projectId,e.sessionId,t),messageAuthors:()=>ru(e.projectId,e.sessionId),modelUsage:()=>su(e.projectId,e.sessionId),transcriptSync:t=>Yn(e.projectId,e.sessionId,t),log:t=>Fl(e.projectId,e.sessionId,t),turn:()=>Jn(e.projectId,e.sessionId),prompts:{create:t=>Qn(e.projectId,e.sessionId,t),list:()=>Nl(e.projectId,e.sessionId),remove:t=>ql(e.projectId,e.sessionId,t),retry:t=>Kl(e.projectId,e.sessionId,t),edit:(t,n)=>Gl(e.projectId,e.sessionId,t,n),interrupt:t=>Wl(e.projectId,e.sessionId,t),hold:t=>Vl(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function cb(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var sM=["control_plane","provider_ingress","daemon","upstream_port"];function Jm(e){return typeof e=="string"&&sM.includes(e)?e:null}function Qm(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.harness?e.harness.ready===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function Xm(e,t){let n=(e===void 0?Xe():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await j(`${n}/beeuni/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let i=o,a=Jm(r.headers.get("X-Beeuni-Proxy-Hop"))??Jm(o?.hop),c=Number(r.headers.get("X-Beeuni-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var lb=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,ub=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,pb=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,db=new Set([22,4096,parseInt(Je.BEEUNI_MASTER,10)]);function oM(e){return ub.test(e)}function Ao(e){if(!e)return"/";let t=e,n=t.indexOf("](");n!==-1&&(t=t.slice(0,n));let r=t.toLowerCase().indexOf("%5d(");return r!==-1&&(t=t.slice(0,r)),t?t.startsWith("/")?t:`/${t}`:"/"}function iM(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var aM=new Set(["'",'"',"`","<","(","["]),cM=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function lM(e){let t=0,n=e.length;for(;t<n&&(e[t]===" "||e[t]===" ");)t++;for(;n>t&&(e[n-1]===" "||e[n-1]===" ");)n--;for(;t<n&&aM.has(e[t]);)t++;for(;n>t&&cM.has(e[n-1]);)n--;return e.slice(t,n)}function uM(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var pM=/^\/proxy\/(\d{1,5})(\/.*)?$/,dM=/^\/(connectors|settings|dashboard|projects|agents|skills|tools|commands|support|changelog|files|p|browser|desktop|terminal|sessions|services|workspace|channels|scheduled-tasks|marketplace|templates|tunnel|admin|auth)(\/|$|\?)/;function gb(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:dM.test(t.pathname)}catch{return!1}}function kr(e){if(!e)return null;let t=lM(iM(e.trim())),n=ef(t);if(n){let r=Ao(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(Je.BEEUNI_MASTER,10);if(s===i){let c=r.pathname.match(pM);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return s=p,o=Ao(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=Ao(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=uM(e);return r&&r!==e?kr(r):null}}function gM(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,i=o+r[0].length;t.some(([c,p])=>o>=c&&i<=p)||t.push([o,i])}return t}function mM(e,t){return t.some(([n,r])=>e>=n&&e<r)}function mb(e){let t=[],n=new Set,r=gM(e);lb.lastIndex=0;let s;for(;(s=lb.exec(e))!==null;){let o=kr(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:c}=o;a<1||a>65535||db.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:mM(s.index,r)}))}return t}function fM(e){return mb(e).length>0}function yM(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function fb(e){return e.trim().toLowerCase().split("_").join("-")}function yb(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function hM(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let s=r.split("{port}").join(String(e)).split("{sandbox}").join(fb(n.sandboxId));return`${yb(s)}${t}`}function hb(e){return e.sandboxId.trim().length>0}function yt(e,t,n){let r=Ao(t);if(!hb(n))return Pb(e,r);let s=hM(e,r,n);return s||(yM(n.apiBaseUrl)?`http://p${e}-${fb(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${yb(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function _M(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return yt(3211,`/open?path=/workspace/${r}`,t)}function _b(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function bM(e){return`http://localhost:3211${_b(e)}`}function bb(){return"/health"}function SM(e){return yt(3211,bb(),e)}function PM(e,t){return yt(e,"/",t)}function Sb(e){let t=kr(e);return!(!t||db.has(t.port)||gb(e))}function Zm(e,t){if(!e)return e;let n=kr(e);return n?Sb(n.originalUrl)?yt(n.port,n.path,t):n.originalUrl:e}function Pb(e,t="/"){return`http://localhost:${e}${t}`}var xb=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function ef(e){let t=e.match(ub);if(t)return{port:parseInt(t[1],10),sandboxId:t[2],backendPort:t[3]?parseInt(t[3],10):80,path:t[4]||"/"};let n=e.match(pb);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(xb);if(r)try{let s=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(s.port,10)||(s.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function xM(e){try{let t=ef(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function wM(e){return oM(e)||pb.test(e)||xb.test(e)}function vM(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Ar="/web-proxy/";function AM(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Ar}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(Je.BEEUNI_MASTER,10);return`${yt(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function kM(e){try{let t=new URL(e),n=t.pathname.indexOf(Ar);if(n===-1)return null;let s=t.pathname.slice(n+Ar.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],i=s[2],a=s[3]||"/";return`${o}://${i}${a}${t.search}${t.hash}`}catch{return null}}function RM(e){try{return new URL(e).pathname.includes(Ar)}catch{return e.includes(Ar)}}function CM(e){if(!e)return!1;let t=e.trim();return!!(/^https?:\/\/(?!localhost|127\.0\.0\.1)/i.test(t)||/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t))}function TM(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t)?`https://${t}`:null:null}function wb(e){return{health:t=>Xm(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>yt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>Zm(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ie(e.requireReady("sandboxPortUrl").sandboxId,t)}}function tf(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=h_(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=P_(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return s},set model(f){s=f},get agent(){return o},set agent(f){o=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...ib(m),...ab(m),...wb(m),...k_(m),...O_(m),...K_(m),files:ob(c),...A_(m),get runtime(){return Oe(d("runtime").runtimeUrl)}}}function vb(e){return{apps:{list:()=>Gd(e),create:t=>Wd(e,t),get:t=>Bs(e,t),update:(...t)=>Kd(e,...t),access:{get:(...t)=>Yd(e,...t),update:(...t)=>Qd(e,...t),session:(...t)=>Xd(e,...t),agents:t=>Jd(e,t)},remove:t=>Vd(e,t),token:t=>Hd(e,t),authEnv:t=>zd(e,t),artifacts:{register:t=>Us(e,t),uploadArchive:(...t)=>Zd(e,...t),finalize:(...t)=>Fs(e,...t)},deployments:{create:(...t)=>eg(e,...t),list:t=>tg(e,t),get:(...t)=>ng(e,...t),logs:(...t)=>rg(e,...t),remove:(...t)=>ig(e,...t)},start:t=>sg(e,t),stop:t=>og(e,t),rollback:(...t)=>ag(e,...t),machines:{list:t=>cg(e,t),start:(t,n)=>ug(e,t,n),stop:(t,n)=>pg(e,t,n),restart:(t,n)=>dg(e,t,n),destroy:(t,n)=>gg(e,t,n)},scale:(...t)=>mg(e,...t),exec:(...t)=>fg(e,...t),volumes:{list:t=>yg(e,t),create:(...t)=>hg(e,...t),update:(...t)=>_g(e,...t),destroy:(...t)=>bg(e,...t),snapshots:(...t)=>Sg(e,...t),snapshot:(...t)=>Pg(e,...t),restore:(...t)=>xg(e,...t),fork:(...t)=>wg(e,...t)}}}}function Ab(e){return{list:()=>Pa(e),invite:(...t)=>va(e,...t),update:(...t)=>xa(e,...t),revoke:t=>wa(e,t),pendingInvites:()=>Aa(e),resendInvite:(...t)=>Ra(e,...t),revokeInvite:(...t)=>ka(e,...t),requests:()=>_a(e),approveRequest:(...t)=>ba(e,...t),rejectRequest:(...t)=>Sa(e,...t),groupGrants:()=>Ca(e),attachGroupGrant:(...t)=>Ta(e,...t),updateGroupGrant:(...t)=>Ea(e,...t),detachGroupGrant:t=>Ia(e,t),resourceGrants:{list:()=>Ma(e),create:t=>Oa(e,t),remove:t=>Da(e,t)}}}function kb(e){return{tokens:{list:()=>xd(e),create:t=>wd(e,t),revoke:t=>vd(e,t)},setupLinks:{requestSecret:t=>Od(e,t),requestConnector:t=>Dd(e,t)},validateManifest:t=>Qi(e,t),gitToken:()=>Xi(e),agentIdentities:()=>Bp(e),secrets:{list:()=>Ba(e),upsert:t=>Ua(e,t),setStrategy:(...t)=>Fa(e,...t),broker:(...t)=>Na(e,...t),remove:t=>Ka(e,t),setPersonal:(...t)=>Va(e,...t),removePersonal:t=>Ha(e,t),setGitCredential:t=>Wa(e,t),listProviderOAuth:()=>qa(e),startProviderOAuth:(...t)=>ps(e,...t),pollProviderOAuth:(...t)=>ds(e,...t),removeProviderOAuth:t=>Ga(e,t)},access:Ab(e)}}function Rb(e){return{list:()=>ac(e),listAll:()=>cc(e),reconcile:(...t)=>lc(e,...t),reconcileMember:(...t)=>uc(e,...t),updateCredential:(...t)=>pc(e,...t),revoke:(...t)=>dc(e,...t),activate:(...t)=>gc(e,...t),setDefault:(...t)=>mc(e,...t),rename:(...t)=>fc(e,...t),share:(...t)=>hc(e,...t),addComputer:(...t)=>yc(e,...t),connect:(...t)=>_c(e,...t),finalize:(...t)=>bc(e,...t)}}function ko(e){return{catalog:t=>Vt(e,t),tools:()=>fs(e),search:(...t)=>ic(e,...t),describe:(...t)=>ys(e,...t),call:(...t)=>Rt(e,...t),callAction:(t,n,r,s)=>Rt(e,`${t}.${n}`,r,s),accounts:(...t)=>hs(e,...t),uploadAttachment:(...t)=>_s(e,...t)}}function nf(e,t){return{slug:t,run:(r,s,o)=>ws(e,t,r,s,o),call:(r,s,o)=>Rt(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?ys(e,`${t}.${r}`):(await Vt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>hs(e,t),paginate:(r,s,o)=>Bc(e,t,r,s,o),uploadAttachment:(r,s)=>_s(e,r,{...s,connector:t})}}var EM=100,Cb=0,IM=new Set(["attachment_size_mismatch","attachment_failed"]),Tb=()=>new x("Attachment expired. Attach the file again.",{code:"attachment_expired"});function rf(e){if(!e||typeof e.attachment_id!="string"||!e.attachment_id||typeof e.filename!="string"||!e.filename||typeof e.mime!="string"||!e.mime||!Number.isSafeInteger(e.size)||e.size<=0||e.size>52428800||!Number.isFinite(Date.parse(e.expires_at))||Date.parse(e.expires_at)<=Date.now())throw new Error("Attachment metadata is invalid or expired. Attach the file again.");return{attachment_id:e.attachment_id,filename:e.filename,mime:e.mime,size:e.size,expires_at:e.expires_at}}function sf(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,i=0,a=!1,c,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,_){y.removalDeleted||(y.removalDeleted=!0,Ht(e,_).catch(()=>{}))}function m(){c&&clearTimeout(c);let y=d().map(({item:R})=>R);(y.length!==p.attachments.length||y.some((R,v)=>R!==p.attachments[v]))&&(p={attachments:y});let _=Math.min(...y.filter(R=>R.status==="ready").map(R=>Date.parse(R.attachment.expires_at)));Number.isFinite(_)&&!a&&(c=setTimeout(()=>{for(let R of d())R.item.status==="ready"&&Date.parse(R.item.attachment.expires_at)<=Date.now()&&(R.item={...R.item,status:"error",error:Tb()});m()},Math.min(2147483647,Math.max(0,_-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let R of s)R();for(let R of[...o])R()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(y){f();let _=d();if(_.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(v=>!Number.isSafeInteger(v)||v<=0||v>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(_.reduce((v,b)=>v+b.item.size,0)+y.reduce((v,b)=>v+b,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function S(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let _=y.item.file;i++;let R=++y.generation,v=new AbortController;y.abort=v,y.item={...y.item,status:"uploading",error:void 0};let b=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===R,P,O=0,A,$=()=>{A=void 0,!(!b()||y.item.status!=="uploading"||P===void 0)&&(y.item={...y.item,receivedBytes:P},P=void 0,O=Date.now(),m())},N=T=>Math.floor(T*100/y.item.size);Kn(e,_,{resume:y.upload,signal:v.signal,onUpload:T=>{y.upload=T,y.removed&&(v.abort(),g(y,T.attachment_id))},onProgress:T=>{if(!b()||N(T)===N(y.item.receivedBytes)||(P=T,A))return;let q=O+EM-Date.now();if(q<=0)return $();A=setTimeout($,q),typeof A=="object"&&"unref"in A&&A.unref()},onProcessing:()=>{A&&clearTimeout(A),A=void 0,P=void 0,b()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then(T=>{b()&&(y.item={...y.item,status:"ready",attachment:rf(T),receivedBytes:T.size})}).catch(T=>{T instanceof x&&IM.has(T.code??"")&&(y.upload=void 0),b()&&(y.item={...y.item,status:T instanceof x&&T.code==="ABORTED"?"aborted":"error",error:T instanceof Error?T:new Error(String(T))})}).finally(()=>{i--,A&&clearTimeout(A),y.abort===v&&(y.abort=void 0),m(),S()})}m()}function E(y){h(y.map(R=>R.size));let _=y.map(R=>{let v=`attachment-${++Cb}`;return r.set(v,{generation:0,item:{id:v,file:R,filename:R.name,mime:R.type||"application/octet-stream",size:R.size,status:"pending",receivedBytes:0}}),v});return m(),S(),_}function L(y){let _=y.map(({attachment:v,file:b})=>{try{return{attachment:rf(v),file:b}}catch{return}});h(_.flatMap(v=>v?[v.attachment.size]:[]));let R=_.map(v=>{if(!v)return;let b=`attachment-${++Cb}`,{attachment:P,file:O}=v;return r.set(b,{generation:0,item:{id:b,...O?{file:O}:{},filename:P.filename,mime:P.mime,size:P.size,status:"ready",receivedBytes:P.size,attachment:P}}),b});return m(),R}function D(y){let _=r.get(y);!_||_.item.status==="ready"||(_.generation++,_.abort?.abort(),_.item={..._.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function w(y,{signal:_}={}){let R=[...y];return new Promise((v,b)=>{let P=()=>{o.delete($),_?.removeEventListener("abort",A)},O=N=>{P(),b(N)},A=()=>O(Re()),$=()=>{let N=!1;for(let q of R){let W=r.get(q);if(!W)return O(new Error("Attachment was removed before it was sent"));if(a&&!W.handedOff)return O(new Error("Attachment controller is disposed"));if(W.item.status==="error"||W.item.status==="aborted")return O(W.item.error??new Error("Attachment upload failed"));W.item.status!=="ready"&&(N=!0)}if(N)return;let T;try{T=R.map(q=>{let W=rf(r.get(q).item.attachment);return{type:"file",attachment_id:W.attachment_id,filename:W.filename,mime:W.mime}})}catch(q){return O(q instanceof Error?q:new Error(String(q)))}P(),v(T)};if(_?.aborted)return A();o.add($),_?.addEventListener("abort",A,{once:!0}),$()})}return{add:y=>E([y])[0],addMany:E,restore:L,retry(y){let _=r.get(y);if(_?.handedOff||f(),!(!_||_.item.status==="ready"||_.item.status==="uploading"||_.item.status==="processing"||_.item.status==="pending")){if(!_.item.file||_.upload&&Date.parse(_.upload.expires_at)<=Date.now())throw Tb();_.item={..._.item,status:"pending",error:void 0},S()}},async remove(y){let _=r.get(y);if(!_)return;_.removed=!0,_.generation++,r.delete(y);let R=_.upload?.attachment_id??_.item.attachment?.attachment_id;R&&_.abort?.abort(),m(),S(),R&&g(_,R)},abort:D,submit(y){if(!a){for(let _ of y){let R=r.get(_);R&&(R.handedOff=!0)}m()}},reclaim(y){if(!a){for(let _ of y){let R=r.get(_);R&&(R.handedOff=!1)}m()}},whenReady:w,forget(y=d().map(_=>_.item.id)){for(let _ of y){let R=r.get(_);R&&(R.generation++,R.abort?.abort(),r.delete(_))}m(),S()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let _=y.upload?.attachment_id??y.item.attachment?.attachment_id;_&&e&&Ht(e,_).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(y){return s.add(y),()=>{s.delete(y)}}}}function Eb(e){return{attachments:{upload:(...t)=>Kn(e,...t),delete:(...t)=>Ht(e,...t),createController:t=>sf(e,t)},get:t=>kt(e,t),detail:()=>jn(e),skills:{create:(...t)=>ia(e,...t)},audit:t=>Rd(e,t),update:t=>Bn(e,t),archive:()=>Un(e),llmCatalog:()=>Ln(e),modelPicker:()=>$n(e),modelAccess:()=>rr(e),setModelAccess:t=>sr(e,t),sandboxHealth:()=>Nn(e),onboardingComplete:(...t)=>oa(e,...t)}}function Ib(e){return{sessions:{list:t=>Tt(e,t),listPage:t=>Al(e,t),create:t=>Et(e,t),ensureWarm:()=>Ll(e),claimWarm:t=>$l(e,t)},review:{list:t=>rd(e,t),summary:()=>sd(e),get:t=>od(e,t),submit:t=>id(e,t),act:(...t)=>ad(e,...t),bulkAct:t=>cd(e,t)},approvals:{list:t=>ja(e,t),resolve:(...t)=>$a(e,...t),sessionsNeedingInput:t=>La(e,t)}}}function Mb(e){return{files:{list:t=>Jc(e,t),listDirectory:t=>Qc(e,t),read:(t,n)=>Zc(e,t,n),search:(...t)=>Xc(e,...t),archive:(...t)=>el(e,...t),archiveRequest:(...t)=>tl(e,...t),history:(...t)=>cl(e,...t)},git:{commits:()=>ol(e),commit:t=>il(e,t),commitDiff:t=>al(e,t),branches:()=>sl(e),versionDiff:(...t)=>ll(e,...t),inviteCollaborator:(...t)=>Ji(e,...t)},changeRequests:{list:(...t)=>ul(e,...t),get:t=>pl(e,t),update:(...t)=>Sl(e,...t),diff:t=>dl(e,t),mergePreview:t=>gl(e,t),open:(...t)=>ml(e,...t),merge:(...t)=>fl(e,...t),close:(...t)=>yl(e,...t),reopen:(...t)=>hl(e,...t),requestChanges:(...t)=>_l(e,...t)},...Ib(e)}}function Ob(e){return{policies:{list:()=>Uc(e),set:(...t)=>Fc(e,...t)},reminders:{list:()=>yd(e),updateMany:(...t)=>md(e,...t),removeMany:(...t)=>fd(e,...t)},triggers:{list:()=>ou(e),eventApps:()=>du(e),eventTypes:(...t)=>pu(e,...t),create:(...t)=>iu(e,...t),update:(...t)=>au(e,...t),remove:(...t)=>cu(e,...t),fire:(...t)=>uu(e,...t),setActivation:(...t)=>lu(e,...t)},...Mb(e)}}function Db(e,t){return{connectors:{...ko(e),list:()=>Sc(e),config:(...n)=>Rc(e,...n),create:(...n)=>Ec(e,...n),remove:(...n)=>Mc(e,...n),sync:()=>Pc(e),auth:{discover:(...n)=>Ic(e,...n)},setName:(...n)=>Cc(e,...n),setCredentialMode:(...n)=>xc(e,...n),setAuthorizationStrategy:(...n)=>wc(e,...n),setCredential:(...n)=>jc(e,...n),deleteCredential:(...n)=>Lc(e,...n),setSensitive:(...n)=>vc(e,...n),connections:t,policies:{get:(...n)=>Ac(e,...n),set:(...n)=>kc(e,...n)},connect:(...n)=>Tc(e,...n),finalize:(...n)=>$c(e,...n),discover:{list:(...n)=>bs(e,...n),sections:(...n)=>Oc(e,...n),detail:(...n)=>Ss(e,...n)}},...Ob(e)}}function jb(e){return{gateway:{logs:t=>up(e,t),log:t=>pp(e,t),overview:t=>dp(e,t),series:t=>gp(e,t),breakdown:t=>mp(e,t),sessions:t=>fp(e,t),errors:t=>yp(e,t),budgets:()=>hp(e),setBudget:t=>_p(e,t),deleteBudget:t=>bp(e,t),keys:()=>Sp(e),createKey:t=>Pp(e,t),revokeKey:t=>xp(e,t),routing:{get:()=>ip(e),set:t=>ap(e,t),reset:()=>cp(e),preview:t=>lp(e,t)},playground:(t,n,r)=>wp(e,t,n,r)}}}function Lb(e){return{modelDefaults:{get:()=>yu(e),set:t=>hu(e,t),clear:t=>_u(e,t)},setDefaultAgent:t=>Pu(e,t),sandbox:{list:()=>Yc(e),snapshots:()=>qc(e),rebuildSnapshot:t=>Gc(e,t),fixWithAgent:()=>Wc(e),createTemplate:t=>Kc(e,t),updateTemplate:(...t)=>Vc(e,...t),removeTemplate:t=>Hc(e,t),buildTemplate:t=>zc(e,t),setProvider:t=>sa(e,t)},setAgentScope:(...t)=>bu(e,...t)}}function $b(e){return{channels:{slack:{installation:()=>Ku(e),connect:t=>Vu(e,t),mode:()=>Hu(e),completeInstall:t=>zu(e,t),manifest:()=>Ju(e),disconnect:()=>Qu(e),getFile:t=>Xu(e,t),uploadFile:t=>Zu(e,t)},teams:{completeInstall:t=>Yu(e,t)},email:{installation:t=>tp(e,t),mode:()=>np(e),connect:t=>rp(e,t),disconnect:t=>sp(e,t),updatePolicy:(...t)=>op(e,...t)}},updateFeatureFlag:(...t)=>na(e,...t),updateExperimentalFeature:(...t)=>ra(e,...t),...Lb(e)}}async function of(e){let t=e?.fetch??C().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??C().backendUrl,r=await t(`${It(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new x(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var MM=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function OM(e,t){let n=o=>{let i=MM.exec(o.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),s=n(t);if(!r||!s)return null;for(let o=0;o<3;o++)if(r[o]!==s[o])return r[o]<s[o]?-1:1;return 0}function DM(){return gt()}var Bb=null,Ub=!1;function jM(e){let t=Bb;Bb=e,!(Ub||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(Ub=!0,console.warn("[beeuni] createBeeuni() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedBeeuni() from @beeuni/sdk/server.")))}function Fb(e,t){t?.global!==!1&&jM(e),Xr(e,t);let n=y_(e),{auth:r,accounts:s,iam:o,accountInvites:i}=p_(),{billing:a,sandboxShares:c}=c_(),{projects:p,github:d,connectStatus:g,marketplace:m}=o_();function f(h){let S=Rb(h);return{...Eb(h),...vb(h),...kb(h),...Db(h,S),...jb(h),...$b(h),connector:E=>nf(h,E),session:E=>tf(h,E,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,capture:a_,projects:p,connectors:ko(),connector:h=>nf(void 0,h),project:f,session:(h,S)=>tf(h,S,e,n),github:d,billing:a,sandboxShares:c,connectStatus:g,marketplace:m,notifications:{registerDeviceToken:Ag,unregisterDeviceToken:kg,list:Rg,markRead:Cg,preferences:Tg,updatePreferences:Eg,webPushPublicKey:Ig,registerWebPushSubscription:Mg,unregisterWebPushSubscription:Og},mobileClientPolicy:of,validateToken:zi,runtime:DM}}function Nb(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<16;r++)t[r]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(r=>r.toString(16).padStart(2,"0"));return`${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n.slice(10).join("")}`}function qb(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function yn(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function Gb(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function Wb(e){if(yn(e).length>0)return{state:e};let t=e.pending[0];if(!t)return{state:e};let n={...t,attempts:t.attempts+1};return{state:{...e,pending:[n,...e.pending.slice(1)],inFlightId:n.id,inFlightIds:[n.id]},claimed:n}}function Kb(e){let t=yn(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function Vb(e,t){let n=yn(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function Hb(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function zb(e,t){return yn(e).includes(t)?e:e.pending.some(n=>n.id===t)?{...e,pending:e.pending.filter(n=>n.id!==t)}:e.failed.some(n=>n.id===t)?{...e,failed:e.failed.filter(n=>n.id!==t)}:e}function Yb(e,t,n){return yn(e).includes(t)||!e.pending.some(r=>r.id===t)?e:{...e,pending:e.pending.map(r=>r.id===t?{...r,text:n}:r)}}function Jb(e,t,n){let r=yn(e);if(r.includes(t))return e;let s=e.pending.findIndex(p=>p.id===t);if(s===-1)return e;let o=r.length,i=Math.min(Math.max(n,o),e.pending.length-1);if(i===s)return e;let a=[...e.pending],[c]=a.splice(s,1);return a.splice(i,0,c),{...e,pending:a}}var af={thinking:!1,toolDetails:!0,assistantMetadata:!0};function LM(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function $M(e){let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=t%60;return`${n}m ${r.toFixed(0)}s`}function BM(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
22
22
|
|
|
23
23
|
`;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
|
|
24
24
|
>
|
|
@@ -51,15 +51,15 @@ ${s}
|
|
|
51
51
|
${e.state.error}
|
|
52
52
|
\`\`\`
|
|
53
53
|
`),n+=`
|
|
54
|
-
`,n}return""}function
|
|
54
|
+
`,n}return""}function UM(e,t){if(!t)return`## Assistant
|
|
55
55
|
|
|
56
|
-
`;let n=e.agent?
|
|
56
|
+
`;let n=e.agent?LM(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=$M(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
|
|
57
57
|
|
|
58
58
|
`:`## ${n}
|
|
59
59
|
|
|
60
|
-
`}function
|
|
60
|
+
`}function FM(e,t,n){let r="";e.role==="user"?r+=`## User
|
|
61
61
|
|
|
62
|
-
`:r+=
|
|
62
|
+
`:r+=UM(e,n.assistantMetadata);for(let s of t)r+=BM(s,n);return r}function Qb(e,t,n=af){let r=`# ${e.title||"Untitled Session"}
|
|
63
63
|
|
|
64
64
|
`;r+=`**Session ID:** \`${e.id}\`
|
|
65
65
|
`,r+=`**Created:** ${new Date(e.time.created).toLocaleString()}
|
|
@@ -67,30 +67,32 @@ ${e.state.error}
|
|
|
67
67
|
|
|
68
68
|
`,r+=`---
|
|
69
69
|
|
|
70
|
-
`;for(let s of t)r+=
|
|
70
|
+
`;for(let s of t)r+=FM(s.info,s.parts,n),r+=`---
|
|
71
71
|
|
|
72
|
-
`;return r}function
|
|
72
|
+
`;return r}function Xb(e,t){return`session-${e}.md`}var cf="An error occurred";var NM=["message","error","detail","error_description","msg","errors","data"];function lf(e){let t=e.trim();for(let n=0;n<4;n++){let r=t.replace(/^(?:\d{3}\s+)?(?:[A-Za-z_$][\w$]*)?Error:\s*/,"").trim();if(r===t)break;t=r}return t}function hn(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function qM(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=hn(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function GM(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=WM(e,t);if(n)return n;let r=VM(e,t);return r?r.slice(0,200):void 0}function nS(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function Zb(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function WM(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!nS(t.charCodeAt(s))){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return;let i=e.indexOf("<",o+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(o+1,i).trim();if(a)return a}n=o+1}}var KM=["script","style"];function VM(e,t){let n=[],r=0;for(;r<e.length;){let s=e.indexOf("<",r);if(s===-1){n.push(e.slice(r));break}n.push(e.slice(r,s));let o=KM.find(i=>t.startsWith(`<${i}`,s)&&nS(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:Zb(e,i);continue}r=Zb(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function HM(e){if(!e.startsWith("JSON parsing failed: Text:"))return;let t=e.match(/"model"\s*:\s*"([^"\\]{1,120})"/)?.[1]?.trim();return t?`The response from ${t} could not be read.`:"The model response could not be read."}function zM(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function eS(e,t,n){if(typeof e=="string")return Ro(e,t,n);if(e&&typeof e=="object")return Co(e,t,n)}function Ro(e,t,n=new WeakSet){let r=lf(e);if(!r)return;if(t>=4)return r;let s=HM(r);if(s)return s;let o=hn(r);if(o!==void 0)return typeof o=="string"?Ro(o,t+1,n):o&&typeof o=="object"?Co(o,t+1,n):String(o);let i=rS(r);if(i){let a=hn(i);if(a&&typeof a=="object"){let c=Co(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=qM(r);if(a)return Ro(a,t+1,n)??a}return GM(r)??r}function Co(e,t,n=new WeakSet){if(t>=4||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let i of e){let a=eS(i,t,n);if(a)return a}return}let r=e;for(let i of NM){let a=eS(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return zM(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function _e(e){return e?typeof e=="string"?Ro(e,0)??cf:typeof e=="object"?Co(e,0)??cf:String(e):cf}function Rr(e){let t=YM(e)?.trim();if(!t)return;let n=_e(e);if(!(t===n||lf(t)===n))return t}function YM(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:s}=n,o=[r,s].filter((i,a,c)=>typeof i=="string"&&i.trim()!==""&&c.indexOf(i)===a);if(o.length>0)return o.join(`
|
|
73
73
|
|
|
74
|
-
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function 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
|
|
74
|
+
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function rS(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function JM(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(typeof t.message=="string"&&t.message)return t.message;if(typeof t.error=="string"&&t.error)return t.error;let n=t.data;if(typeof n?.message=="string")return n.message;let r=t.error;if(typeof r?.message=="string")return r.message}function QM(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n;!Number.isInteger(r.attempt)||r.attempt<1||typeof r.provider!="string"||!r.provider||typeof r.route_model!="string"||!r.route_model||typeof r.resolved_model!="string"||!r.resolved_model||typeof r.stage!="string"||!r.stage||typeof r.code!="string"&&!(typeof r.code=="number"&&Number.isFinite(r.code))||typeof r.message!="string"||!r.message||r.status!==void 0&&(!Number.isInteger(r.status)||r.status<100||r.status>599)||t.push({attempt:r.attempt,provider:r.provider,routeModel:r.route_model,resolvedModel:r.resolved_model,stage:r.stage,...typeof r.status=="number"?{status:r.status}:{},code:r.code,message:r.message})}return t.length>0?t:void 0}function tS(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,s=typeof e.upstream_status=="number"?e.upstream_status:void 0,o=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=QM(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,c=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&s===void 0&&!o&&!i?void 0:{message:typeof e.message=="string"&&e.message||JM(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function we(e){if(e==null)return;if(typeof e=="string"){let a=lf(e),c=hn(a)??hn(rS(a));return c!==void 0?we(c):void 0}if(typeof e!="object")return;let t=e,n=tS(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let s=t.error;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=tS(s);if(a)return a}let o=t.data;if(o&&typeof o.responseBody=="string"){let a=hn(o.responseBody);if(a!==void 0){let c=we(a);if(c)return c}}if(o&&typeof o.message=="string"){let a=we(o.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let c=we(a);if(c)return c}}return n}var sS={};function z(e,t){for(let n of t)sS[n]=e}z("read",["read"]);z("list",["list","ls"]);z("glob",["glob"]);z("grep",["grep"]);z("write",["write"]);z("edit",["edit","multiedit","morph_edit","MultiEdit","NotebookEdit"]);z("apply_patch",["apply_patch","patch"]);z("bash",["bash"]);z("script",["codemode"]);z("web_search",["web_search","websearch","image_search"]);z("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);z("media",["image_gen","video_gen"]);z("show",["show","show_user","presentation_gen"]);z("task",["task"]);z("delegate",["agent_spawn","agent_task","agent_task_create","agent_task_start","task_create","task_start","session_spawn","session_start_background","agent_message","agent_task_message","task_message","agent_task_update","task_update","session_message","agent_status","agent_task_list","agent_task_get","task_list","task_get","agent_stop","agent_task_cancel","task_cancel","agent_task_approve","task_approve","task_done","task_delete"]);z("todowrite",["todowrite","todo_write","todoread"]);z("question",["question","ask"]);z("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);z("connectors",["connector_get","connector_list","connector_setup","beeuni_connector_call","beeuni_connectors","beeuni_connectors_connectors","beeuni_connectors_discover","beeuni_connectors_describe","beeuni_connectors_call","beeuni_connector_describe","beeuni_connector_discover"]);z("automations",["triggers"]);z("skill",["skill"]);z("context",["prune","distill","compress","context_info"]);z("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var XM=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function le(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=sS[t];if(n)return n;for(let[r,s]of XM)if(t.startsWith(r))return s;return"other"}function et(e){for(let t of[e?.filePath,e?.file_path,e?.path,e?.notebook_path])if(typeof t=="string"&&t)return t}var ZM=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function eO(){return new RegExp(`(^|\\s)([-+]?)(${ZM.join("|")}):("[^"]*"|\\S+)`,"gi")}function tO(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function nO(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function rO(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function sO(e){return rO(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function oS(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Cr(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(eO(),(s,o,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=sO(c);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(tO(),"$1").replace(nO(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${oS(n)}`:r:n.length>0?oS(n):t}var oO=/\s/,iO=/\w/;function be(e){return e!==void 0&&oO.test(e)}function Tr(e){return e===`
|
|
75
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function uf(e){return e!==void 0&&iO.test(e)}function $t(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(aO(n.charCodeAt(0))):n;return t}function aO(e){if(e<128)return e>=97&&e<=122?e-32:e;let t=String.fromCharCode(e).toUpperCase();if(t.length!==1)return e;let n=t.charCodeAt(0);return n<128?e:n}function tt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function iS(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return tt(e.slice(t))}function Er(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let s=e.indexOf(n,r+t.length);return s===-1?null:e.slice(r+t.length,s)}function pf(e,t){let n=Er(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
|
|
76
76
|
`)&&(n=n.slice(1)),n.endsWith(`
|
|
77
|
-
`)&&(n=n.slice(0,-1)),n)}function 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
|
|
79
|
-
`)
|
|
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
|
-
|
|
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(
|
|
85
|
-
`)
|
|
77
|
+
`)&&(n=n.slice(0,-1)),n)}function df(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let s=e.indexOf(">",r+1+t.length);return s===-1?null:{open:r,end:s}}function aS(e,t){let n=df(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function cS(e,t){let n=df(e,t);if(!n)return null;let r=e.indexOf(`</${t}>`,n.end+1);return r===-1?null:e.slice(n.end+1,r)}function lS(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=df(e,t,s);if(!o)break;let i=e.indexOf(n,o.end+1);if(i===-1)break;r+=e.slice(s,o.open),s=i+n.length}return r+e.slice(s)}function uS(e,t,n){let r=[];for(let s of e.split(/[\n\r\u2028\u2029]/)){let o=0;for(;;){let i=s.indexOf(t,o);if(i===-1)break;let a=s.indexOf(n,i+t.length);if(a===-1)break;r.push(s.slice(i+t.length,a)),o=a+n.length}}return r}function Ir(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&be(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function pS(e,t,n){let r=$t(t),s=$t(n);for(let o of $t(e).split(/[\n\r\u2028\u2029]/)){let i=o.indexOf(r);if(i!==-1&&o.lastIndexOf(s)>=i+r.length)return!0}return!1}function dS(e,t){let n=$t(e),r=t.map($t),s=e.length,o=c=>{let p=c;for(;p<s&&be(e[p]);)p++;return p},i=c=>{for(let p=c;p<s;p++)if(Tr(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let c=o(a);if(c>=s)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=o(c+p.length);if(e[d]===":"){let g=o(d+1);if(g<s){let m=g;for(;m<s&&!Tr(e[m]);)m++;for(;m>g+1&&be(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!Tr(e[m]))return e[m];return null}}a=i(c)}return null}function gS(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=be(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!be(e[a-1]))continue;let c=a+1;if(be(e[c])){for(;c<t&&be(e[c]);)c++;uf(e[c])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(Tr(e[a])?1:0);let o=(a,c)=>s[c]===s[a],i=a=>{let c=a+1;for(;be(e[c]);)c++;let p=c;for(;p<t&&uf(e[p]);)p++;return e.slice(c,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let c=a+7;for(;c<t&&/[a-z0-9]/.test(e[c]);)c++;if(c===a+7||e[c]!=="*"||e[c+1]!=="*")continue;let p=c+2,d=p;for(;d<t&&be(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(o(d,m))return{id:e.slice(a+2,c),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Tr(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function mS(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&be(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&be(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!uf(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&be(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function fS(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(o<c&&(o=e.indexOf("]",c)),o===-1)break;let p=o;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(s,a)+(t?" ":e.slice(c,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function yS(e){return fS(e,!0)}function hS(e){return fS(e,!1)}function cO(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function _S(e,t){let n=$t(e),r=$t(t),s=e.length,o=i=>{let a=i;for(;a<s&&be(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=o(i+r.length);if(e[a]!==":")continue;let c=o(a+1);for(let p=c;p<s;){if(!be(e[p])){p++;continue}let d=o(p);if(cO(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var bS=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function lO(e){return bS.has(le(e))}function uO(e){let t=0,n=0,r=0;for(let s of e){let o=le(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function gf(e){if(!e)return"";let t=tt(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function To(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Eo(e){let t=He(e),r=(t.state??{}).input??{};switch(ee(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=r.filePath??r.file_path??r.path;return i?gf(String(i)):""}case"glob":return r.pattern?String(r.pattern):"";case"grep":{let i=r.pattern??r.query,a=r.path??r.include;return i&&a?`"${To(String(i),40)}" in ${gf(String(a))}`:i?`"${To(String(i),60)}"`:""}case"list":return r.path?gf(String(r.path)):"";case"bash":return To(String(r.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let i of o){let a=r[i];if(typeof a=="string"&&a.length>0)return To(i==="query"&&Cr(a)||a,60)}return""}var SS={read:"Read",search:"Search",list:"List",shell:"Shell",edit:"Edit",write:"Write",fetch:"Fetch",webSearch:"Web Search",scrape:"Scrape",applyPatch:"Apply Patch",task:"Task",worker:"Worker",workspace:"Workspace"};function pO(e,t={}){let n=ye(e)?ae(e):e,r={...SS,...t},s=ee(n.tool),o=Eo(n);switch(s){case"read":return{title:r.read,subtitle:o};case"glob":case"grep":return{title:r.search,subtitle:o};case"list":return{title:r.list,subtitle:o};case"bash":return{title:r.shell,subtitle:o};case"edit":case"morph_edit":return{title:r.edit,subtitle:o};case"write":return{title:r.write,subtitle:o};case"webfetch":case"web_fetch":return{title:r.fetch,subtitle:o};case"websearch":case"web_search":return{title:r.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:r.scrape,subtitle:o};case"apply_patch":return{title:r.applyPatch,subtitle:o};case"task":return{title:r.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:r.worker,subtitle:o};case"project_select":case"project_list":return{title:r.workspace,subtitle:o};default:return{title:s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase()),subtitle:o}}}function De(e){return e.type==="text"}function Ae(e){return e.type==="reasoning"}function te(e){return e.type==="tool"}function ff(e){return e.type==="file"}function dO(e){return e.type==="agent"}function gO(e){return e.type==="compaction"}function mO(e){return e.type==="snapshot"}function fO(e){return e.type==="patch"}function yO(e){return e.type==="step-start"||e.type==="step-finish"}function hO(e){if(De(e)||Ae(e))return e.text}function _O(e){if(!ff(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function bO(e){let t=[],n=[];for(let r of e)ff(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function SO(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function PO(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var xO=new Set(["todoread","context_info"]);function _n(e){return!xO.has(ye(e)?e.name:e.tool)}var wO=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function Or(e){let t=ye(e)?ae(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=le(n);if(r==="task"||r==="delegate"){let s=t.state?.metadata?.sessionId;if(typeof s=="string"&&s)return s;if(r==="task"&&t.state?.status==="error")return t.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return vO(n,t.state)}function vO(e,t){let n=ee(e);if(wO.has(n)){let r=t?.title?.match(/\bses_[a-zA-Z0-9]+/);return r?r[0]:t?.output?.match(/\bses_[a-zA-Z0-9]+/)?.[0]}if(n==="session_spawn"||n==="session_start_background")return t?.output?.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/)?.[1]}function AO(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return _e(n.error)}}function kO(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)te(r)&&_n(r)&&t.push(r);return t}function RO(e,t={}){switch(ee(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:wS(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"BeeuniWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"apply_patch":return{icon:"file-pen",title:"Patch",subtitle:t.files?.length?`${t.files.length} file${t.files.length>1?"s":""}`:void 0};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"prune":return{icon:"scissors",title:"DCP Prune",subtitle:t.reason};case"distill":return{icon:"scissors",title:"DCP Distill"};case"compress":return{icon:"scissors",title:"DCP Compress",subtitle:t.topic};case"context_info":return{icon:"scissors",title:"Context Info"};case"session_read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session_list_spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":return{icon:"folder",title:"Projects"};case"project_get":case"project_update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":return{icon:"clock",title:"List Triggers"};case"trigger_get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":return{icon:"layers",title:"Agent Status"};case"agent_task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":return{icon:"trash-2",title:"Delete Task",subtitle:t.id};case"pty_spawn":return{icon:"terminal",title:"Spawn",subtitle:t.title||t.command};case"pty_read":return{icon:"terminal",title:"Terminal Output",subtitle:t.id};case"pty_write":case"pty_input":return{icon:"terminal",title:"Terminal Input",subtitle:t.id};case"pty_kill":return{icon:"terminal",title:"Kill Process",subtitle:t.id};default:return CO(e,t)}}function CO(e,t){switch(le(e)){case"read":return{icon:"glasses",title:"Read",subtitle:PS(et(t))};case"list":return{icon:"list",title:"List",subtitle:xS(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":return{icon:"file-pen",title:"Edit",subtitle:mf(et(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:mf(et(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function PS(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function mf(e){if(!e)return;let t=e.split("/"),n=t[t.length-1]||e;if(t.length<=1)return n;let r=t[t.length-2];return r?`${n} /${r}`:n}function xS(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function TO(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function Mr(e,t=120){if(typeof e!="string")return"";let n=e.split(`
|
|
78
|
+
`).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function wS(e){let t=Mr(e.description);if(t)return t;let n=Mr(e.title,80);if(n)return n;let r=Mr(e.message);if(r)return r;let s=Mr(e.prompt);if(s)return s;let o=Mr(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function EO(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function IO(e,t){return e.find(n=>n.tool?.callID===t)}function MO(e,t){return e.find(n=>n.tool?.callID===t)}var OO=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function DO(e){return e?e.replace(OO,""):""}function Io(e){let t=vS(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let s=r&&typeof r=="object"?vS(r):void 0;return s?[s]:[]})}function vS(e){let t=e?.oldString??e?.old_string??e?.oldText,n=e?.newString??e?.new_string??e?.newText;return typeof t=="string"&&typeof n=="string"?[t,n]:void 0}var jO={bash:"Shell",pty_spawn:"Spawn Terminal",pty_read:"Terminal Output",pty_write:"Terminal Input",pty_input:"Terminal Input",pty_kill:"Kill Process",read:"Read File",list:"List Directory",ls:"List Directory",write:"Write File",edit:"Edit File",multiedit:"Edit File",morph_edit:"Edit File",apply_patch:"Apply Patch",patch:"Apply Patch",grep:"Search Code",glob:"Find Files",image_search:"Image Search",session_search:"Search Sessions",webfetch:"Fetch Page",scrape_webpage:"Scrape Page",websearch:"Web Search",web_search:"Web Search",image_gen:"Generate Image",video_gen:"Generate Video",task:"Delegate to Agent",todowrite:"Plan Tasks",todoread:"Read Plan",question:"Ask Question",presentation_gen:"Presentation",show:"Show Output",show_user:"Show Output",prune:"Prune Context",distill:"Distill Context",compress:"Compress Context",context_info:"Context Info"},LO={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",script:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function $O(e){return e.replace(/^oc[-_]/,"")}function yf(e){return $O(e).replace(/-/g,"_")}function hf(e){return yf(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Mo(e){return{label:jO[yf(e)]??hf(e),category:LO[le(e)]}}var BO=256*1024;function UO(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function FO(e){if(e===void 0)return{};if(e.length>BO)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function NO(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,s=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!s))return s?_e(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var ge=e=>typeof e=="string"?e:void 0,Oo=e=>typeof e=="number"?e:void 0,Do=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function _f(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var qO=new Set(["add","update","delete","move"]);function GO(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=Do(d),m=g&&(ge(g.relativePath)||ge(g.filePath));if(!g||!m)return[];let f=ge(g.type);return[_f({path:m,type:f&&qO.has(f)?f:void 0,before:ge(g.before),after:ge(g.after),patch:ge(g.patch)??ge(g.diff),additions:Oo(g.additions),deletions:Oo(g.deletions),movePath:ge(g.movePath)})]});return p.length?p:void 0}let r=et(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[_f({path:r,after:ge(t.content)})];if(e!=="edit")return;let s=Do(n.filediff),o=s?void 0:ge(n.patch),i=o?WO(o):void 0,a=s||o?[]:Io(t);return[_f({path:r,before:ge(s?.before)??(a.length?a.map(([c])=>c).join(`
|
|
79
|
+
`):void 0),after:ge(s?.after)??(a.length?a.map(([,c])=>c).join(`
|
|
80
|
+
`):ge(t.new_source)),patch:o,additions:Oo(s?.additions)??i?.additions,deletions:Oo(s?.deletions)??i?.deletions})]}function WO(e){let t=0,n=0;for(let r of e.split(`
|
|
81
|
+
`))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function KO(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function AS(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=FO(r),i=UO(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=NO(s);m&&(i="error",a=m)}let c=le(e),p=t.input??{},d="metadata"in t&&Do(t.metadata)||{},g=Do(d.diagnostics);return{name:e,kind:c,title:n||Mo(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:GO(c,p,d),diff:ge(d.patch)??ge(d.diff),diagnostics:g,answers:c==="question"?KO(d):void 0,childSessionId:Or({tool:e,state:t})}}function bf(e){let t=ye(e)?ae(e):e;return AS(t.tool,t.state)}function VO(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function HO(e){return{kind:"reasoning",id:e.id,text:e.text}}function zO(e){return{kind:"tool",id:e.id,tool:AS(e.tool,e.state)}}function YO(e){let t=e.mime;return{kind:"file",id:e.id,filename:e.filename,mime:t,url:e.url,isImage:t.startsWith("image/"),isPdf:t==="application/pdf"}}function JO(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function QO(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function XO(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function ZO(e){return{kind:"agent",id:e.id,name:e.name}}function eD(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:_e(e.error),createdAt:e.time.created}}function tD(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function nD(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function rD(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Sf(e){switch(e.type){case"text":return VO(e);case"reasoning":return HO(e);case"tool":return zO(e);case"file":return YO(e);case"subtask":return JO(e);case"patch":return QO(e);case"snapshot":return XO(e);case"agent":return ZO(e);case"retry":return eD(e);case"compaction":return tD(e);case"step-start":return nD(e);case"step-finish":return rD(e);default:return{kind:"unknown",raw:e}}}function sD(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=we(e);return{name:t,message:n?.message||_e(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function oD(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function jo(e){let t=e.parts.map(Sf),n=e.info.role==="assistant"?e.info.error:void 0,r=sD(n),s=!r&&!t.some(oD);return{parts:t,error:r,isEmpty:s}}var Pf=Qe+BigInt(1),kS=Pf/BigInt(2);function Lo(e){return BigInt(Math.trunc(e))*nn}function xf(e,t){let r=t-(t&Qe)+e;return r-t>kS?r-=Pf:t-r>kS&&(r+=Pf),r}function RS(e,t){let n=Dt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return xf(n,t);let s=Lo(r),o=xf(n,s);return(o>s?o-s:s-o)<=pt?o:s}function CS(e){return Dt(e)===null?1:0}function TS(e,t){return e<t?-1:e>t?1:0}function iD(e,t){return ES(e,t,Lo(Date.now()))}function aD(e){let t=null;for(let n of e){let r=n.info.time?.created;typeof r=="number"&&(t===null||r>t)&&(t=r)}return Lo(t??Date.now())}function ES(e,t,n){let r=CS(e.info.id),s=CS(t.info.id);if(r!==s)return r-s;if(r===0){let a=RS(e,n),c=RS(t,n);return a!==c?a<c?-1:1:TS(e.info.id,t.info.id)}let o=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return o===null&&i===null?0:o===null?1:i===null?-1:o!==i?o<i?-1:1:TS(e.info.id,t.info.id)}function cD(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=aD(e),s=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:ES(d,g,r)}),o=[],i=new Map;for(let d of s)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};o.push(g),i.set(d.info.id,g)}let a=null,c=[],p=[];for(let d of s){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=c[c.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):c.push({userMessage:uD(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=o[0]??c[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;o.push({userMessage:g,assistantMessages:m})}}return c.length>0?[...c,...o]:o}var Dr=new Map,lD=256;function uD(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=Dr.get(s);if(o)return o;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(Dr.size>=lD){let a=Dr.keys().next().value;a!==void 0&&Dr.delete(a)}return Dr.set(s,i),i}function pD(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function dD(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(De(n)&&n.text?.trim())return n}}function gD(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function mD(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!te(o))continue;let i=o,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:o,message:s})}return r}function fD(e){let t=new Map;for(let n of e){if(!n.parentID)continue;let r=t.get(n.parentID);r?r.push(n.id):t.set(n.parentID,[n.id])}return t}function yD(e){let t=e-6e4;return(n,r)=>{let s=n.time.updated??n.time.created,o=r.time.updated??r.time.created,i=s>t,a=o>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:o-s}}function IS(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let s of n)r.push(s),r.push(...IS(e,s));return r}function MS(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function wf(e){if(!e?.length)return!1;for(let t=e.length-1;t>=0;t--){let n=e[t].info;if(n.role==="assistant")return!n.time?.completed&&MS(n.error)}return!1}function $o(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vf(e){let t=e.trim();return t.length>500?!1:!!(/^Error:\s/i.test(t)||/^([\w._-]+Error|[\w._-]+Exception):\s/i.test(t)||/Traceback \(most recent call last\)/i.test(t)||/^\s*\[\s*\{[\s\S]*"message"\s*:/.test(t))}function hD(e){return!!e&&(vf(e)||DS(e)!==null)}function Bo(e){let t=ye(e)?ae(e):e,n=OS.get(t);if(n&&n.state===t.state)return n.outcome;let r=_D(t);return OS.set(t,{state:t.state,outcome:r}),r}var OS=new WeakMap;function _D(e){let t=e.state;if(t.status==="error")return"failed";if(t.status!=="completed")return"ok";let n=typeof t.output=="string"?t.output.trim():"";if(!n)return"ok";if(vf(n))return"failed";let r=bD(n);return r===void 0?"ok":SD(r)?"failed":PD(r)}function bD(e){try{return JSON.parse(e)}catch{return}}function SD(e){return $o(e)&&e.success===!1&&typeof e.error=="string"}function PD(e){let t=$o(e)?e.results:void 0;if(!Array.isArray(t)||t.length===0)return"ok";let n=t.filter(r=>r!==null&&typeof r=="object"&&r.success===!1).length;return n===0?"ok":n===t.length?"failed":"partial"}function DS(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!$o(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},s=Ir(r.errorSummary);if(s===null)return r;try{let o=JSON.parse(s);typeof o.message=="string"&&o.message.trim()&&(r.nestedMessage=o.message.trim()),typeof o.status=="number"&&(r.status=o.status),typeof o.error=="boolean"&&(r.nestedError=o.error)}catch{}return r}function xD(e){return mS(e).replace(/\s+/g," ").trim()||e.trim()}function wD(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!$o(n))return null;let r=n.success,s=n.error,o=n.hint;if(r!==!1||typeof s!="string")return null;let i=[];i.push(s.trim());let a=Ir(s);if(a!==null)try{let p=JSON.parse(a).message;typeof p=="string"&&p.trim()&&i.push(`Details: ${p.trim()}`)}catch{}return typeof o=="string"&&o.trim()&&i.push(`Hint: ${o.trim()}`),i.join(`
|
|
82
|
+
|
|
83
|
+
`)}function vD(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function AD(e,t=2e3){let n=(e??"").trim();try{let r=JSON.parse(n);if(typeof r=="string")try{r=JSON.parse(r)}catch{}r&&typeof r=="object"&&(n=JSON.stringify(r,null,2))}catch{}return n.length>t?{text:n.slice(0,t).trimEnd(),truncatedChars:n.length-t}:{text:n,truncatedChars:0}}function kD(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=yS(n),n=hS(n),n=n.replace(/[#*_`>]+/g," "),n=n.replace(/\s+/g," ").trim(),n=n.replace(/\b(\w{2,})(?:\s+\1\b)+/gi,"$1"),n.length>t?n.slice(0,t).trimEnd()+"\u2026":n}function RD(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let s=r.error.trim(),o;for(let i=0;i<3;i++){let a=Ir(s);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(o=c.status),typeof c.message=="string"&&c.message.trim())s=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())s=c.error.trim();else break}return{message:s,status:o}}function jr(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Uo(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},o=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=o.exec(e))!==null;)if(s(jr(i[1]),jr(i[2]),i[3]?jr(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(s(jr(i[2]),jr(i[1])),n.length>=t)return n}return n}function jS(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{return JSON.parse(n)}catch{}return null}}function Fo(e){return e.filter(t=>t.title&&t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function Af(e){if(!e)return[];let t=jS(e,!0);if(t?.success===!1)return[];if(Array.isArray(t?.results)&&t.results.length>0){let n=t.results[0];if(n&&typeof n.query=="string"){let r=[];for(let s of t.results)typeof s.query=="string"&&r.push({query:s.query,answer:s.answer||void 0,sources:Array.isArray(s.results)?Fo(s.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=Fo(t.results);if(r.length>0)return[{query:t.query||"",answer:t.answer||void 0,sources:r}]}}if(t?.query&&typeof t.query=="string")return[{query:t.query,answer:t.answer||void 0,sources:Array.isArray(t.results)?Fo(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=Fo(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let s of n){let o=s.match(/^Title:\s*(.+)/m),i=s.match(/^URL:\s*(.+)/m),a=s.match(/^Author:\s*(.+)/m),c=s.match(/^Published Date:\s*(.+)/m),p=s.match(/^Text:\s*([\s\S]*?)$/m);o&&i&&r.push({title:o[1].trim(),url:i[1].trim(),snippet:p?.[1]?.trim()||void 0,author:a?.[1]?.trim()||void 0,publishedDate:c?.[1]?.trim()||void 0})}if(r.length>0)return[{query:"",sources:r}]}if(typeof e=="string"){let n=Uo(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function No(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function CD(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return No(e)}}function TD(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function ED(e){if(!e)return!1;let t=e.slice(0,600).toLowerCase();return t.includes("<!doctype html")||t.includes("<html")?!0:/<\/(body|head|div|p|span|table)>/i.test(e.slice(0,3e3))}function LS(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let s=r.trim();/^https?:\/\//i.test(s)&&n.push(s)}return n}return[]}function $S(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=_S(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function ID(e,t){let n=BS(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?$S(r,LS(t)):[]}function BS(e){if(!e)return null;let t=jS(e);if(!t)return null;if(t.results&&Array.isArray(t.results))return{total:t.total||t.results.length,successful:t.successful??t.results.filter(n=>n.success!==!1).length,failed:t.failed??t.results.filter(n=>n.success===!1).length,results:t.results.map(n=>({url:n.url||"",success:n.success!==!1,title:n.title||void 0,content:n.content||n.text||n.snippet||void 0,error:n.error||void 0}))};if(typeof e=="string"){let n=Uo(e);if(n.length>0)return{total:n.length,successful:n.length,failed:0,results:n.map(r=>({url:r.url,success:!0,title:r.title||void 0,content:r.snippet||void 0}))}}return null}function MD(e){if(typeof e!="string"||!e.trim())return null;try{let t=new URL(e.trim());return t.protocol==="http:"||t.protocol==="https:"?t.toString():null}catch{return null}}var OD={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",script:"script",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function Sn(e){return OD[le(e)]}function $r(e){let t=ee(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var DD={run:"Terminal",memory:"Memory"};function jD(e){let t=Sn(e);return(t==="hidden"?void 0:DD[t])??$r(e)}function Lr(e,t,n){return e===1?t:n}function kf(e){return e.length===0?"":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function NS(e){return e.length?Eo(e[0]):""}function je(e){return(e.state??{}).input??{}}var LD={agent_spawn:"spawn",agent_task:"spawn",agent_task_create:"spawn",agent_task_start:"spawn",task:"spawn",task_create:"spawn",task_start:"spawn",session_spawn:"spawn",session_start_background:"spawn",agent_message:"message",agent_task_message:"message",task_message:"message",session_message:"message",agent_status:"status",agent_task_list:"status",agent_task_get:"status",task_list:"status",task_get:"status",agent_stop:"stop",agent_task_cancel:"stop",task_cancel:"stop",agent_task_approve:"done",task_approve:"done",task_done:"done",task_delete:"delete"};function $D(e){let t=ee(e.tool);if(t==="agent_task_update"||t==="task_update")switch(je(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return LD[t]??"message"}function US(e){switch(e){case"create":return"create";case"update":return"update";case"delete":return"delete";case"test":return"test";case"pause":case"resume":return"control";case"list":case"get":return"read";default:return"unknown"}}function BD(e){let t=ee(e.tool);if(t==="triggers"){let r=je(e).action||"list";return US(r)}let n=t.match(/^trigger_(.+)$/);return US(n?n[1]:"list")}var UD={connector_setup:"connect",connector_get:"read",connector_list:"read",beeuni_connector_discover:"read",beeuni_connector_describe:"read",beeuni_connectors:"read",beeuni_connectors_connectors:"read",beeuni_connectors_discover:"read",beeuni_connectors_describe:"read",beeuni_connector_call:"call",beeuni_connectors_call:"call"};function FD(e){return UD[ee(e.tool)]??"read"}var ND={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function qD(e){return ND[ee(e.tool)]??"open"}function bn(e){return e.every(t=>t===e[0])}var GD={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function WD(e){if(ee(e.tool)!=="memory")return"read";let n=je(e).command;return n&&GD[n]||"unknown"}var KD={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},VD={create_slide:"Added a slide to a presentation",list_slides:"Checked a presentation's slides",list_presentations:"Checked your presentations",delete_slide:"Deleted a slide from a presentation",delete_presentation:"Deleted a presentation",validate_slide:"Checked a slide",export_pdf:"Exported a presentation to PDF",export_pptx:"Exported a presentation to PPTX",preview:"Previewed a presentation",serve:"Previewed a presentation"};function HD(e){let t=tt(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function zD(e){let t=je(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return YD(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return HD(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=MD(o);return i?No(i):"a link"}return""}function YD(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function JD(e){let t=je(e).action;return t&&KD[t]||"Worked on an image"}function QD(e){let t=je(e).action;return t&&VD[t]||"Worked on a presentation"}function XD(e){return e.slice(0,e.indexOf(":"))}var ZD={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},ej={create_slide:"presentation:create_slide",list_slides:"presentation:list_slides",list_presentations:"presentation:list_presentations",delete_slide:"presentation:delete_slide",delete_presentation:"presentation:delete_presentation",validate_slide:"presentation:validate_slide",export_pdf:"presentation:export_pdf",export_pptx:"presentation:export_pptx",preview:"presentation:preview",serve:"presentation:preview"};function tj(e){let t=ee(e.tool);if(t==="image_gen"){let n=je(e).action;return n&&ZD[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=je(e).action;return n&&ej[n]||"presentation:unknown"}return"shown:result"}var nj=new Set(["create_slide","export_pdf","export_pptx"]);function rj(e){let t=He(e),n=ee(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=je(t).action;return r?nj.has(r)?"presentation":null:"presentation"}return null}var sj={"image:generate":e=>`Made ${e} images`,"image:edit":e=>`Edited ${e} images`,"image:upscale":e=>`Upscaled ${e} images`,"image:remove_bg":e=>`Removed backgrounds from ${e} images`,"image:unknown":e=>`Worked on ${e} images`,"video:create":e=>`Made ${e} videos`,"presentation:create_slide":e=>`Added ${e} slides`,"presentation:delete_slide":e=>`Deleted ${e} slides`,"presentation:delete_presentation":e=>`Deleted ${e} presentations`,"presentation:list_slides":()=>"Checked a presentation's slides","presentation:list_presentations":()=>"Checked your presentations","presentation:validate_slide":()=>"Checked slides","presentation:export_pdf":e=>`Exported ${e} presentations to PDF`,"presentation:export_pptx":e=>`Exported ${e} presentations to PPTX`,"presentation:preview":e=>`Previewed ${e} presentations`,"presentation:unknown":e=>`Worked on ${e} presentations`,"shown:result":e=>`Showed you ${e} results`},FS={image:"image",video:"video",presentation:"presentation",shown:"result"};function oj(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[XD(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Lr(s,FS[r],`${FS[r]}s`)}`)}),`Worked on ${kf(n)}`}function Br(e,t){let n=t.map(He),r=n.length,s=NS(n);switch(e){case"explore":{let o=n.filter(i=>ee(i.tool)==="read").length;return o===r?`Read ${r} ${Lr(r,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(n.map(a=>et(je(a))).filter(Boolean)).size||r,i=n.every(a=>ee(a.tool)==="write")?"Wrote":"Updated";return o===1?s?`${i} ${s}`:`${i} a file`:`${i} ${o} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"script":return r===1?"Ran a script":`Ran ${r} scripts`;case"web":{let o=p=>{let d=ee(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(o).length;if(i===r)return`Searched the web \xB7 ${r} ${Lr(r,"query","queries")}`;if(i===0)return`Read ${r} ${Lr(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of Af(d).flatMap(m=>m.sources))g.url&&a.add(g.url)}else{let d=p.state?.input?.url;typeof d=="string"&&d&&a.add(d)}let c=a.size||r;return`Searched and read ${c} ${Lr(c,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return JD(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return QD(i);let c=zD(i);return c?`Showed you ${c}`:"Showed you the result"}let o=n.map(tj);return bn(o)?sj[o[0]](r):oj(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map($D);if(bn(o))switch(o[0]){case"spawn":return r===1?"Asked a helper agent":`Worked with ${r} helper agents`;case"message":return r===1?"Sent instructions to a helper agent":`Sent instructions to ${r} helper agents`;case"status":return"Checked on a helper agent";case"stop":return r===1?"Stopped a helper agent":`Stopped ${r} helper agents`;case"done":return r===1?"A helper agent finished a task":`Helper agents finished ${r} tasks`;case"delete":return r===1?"Removed a task":`Removed ${r} tasks`}return r===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${r} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=n.map(WD);if(bn(o))switch(o[0]){case"write":return r===1?"Wrote to its memory":`Wrote to its memory \xB7 ${r} updates`;case"delete":return r===1?"Deleted from its memory":`Deleted ${r} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=n.map(FD);if(bn(o))switch(o[0]){case"connect":return r===1?s?`Connected to ${s}`:"Connected a connector":`Connected ${r} connectors`;case"call":return r===1?"Used a connector":`Made ${r} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=n.map(BD);if(bn(o))switch(o[0]){case"create":return r===1?"Set up an automation":`Set up ${r} automations`;case"update":return r===1?"Updated an automation":`Updated ${r} automations`;case"delete":return r===1?"Deleted an automation":`Deleted ${r} automations`;case"control":return r===1?"Adjusted an automation":`Adjusted ${r} automations`;case"test":return r===1?"Tested an automation":`Tested ${r} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=n.map(qD);if(bn(o))switch(o[0]){case"delete":return r===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${r} projects \u2014 deletion isn't allowed`;case"create":return r===1?s?`Created ${s}`:"Created a project":`Created ${r} projects`;case"update":return r===1?s?`Updated ${s}`:"Updated your project":`Updated ${r} projects`;case"open":return r===1?s?`Opened ${s}`:"Opened your project":`Opened ${r} projects`}return s?`Worked in ${s}`:"Worked in your project"}case"skills":return r===1?s?`Used the ${s} skill`:"Used a skill":`Used ${r} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(r===1)return`Used ${$r(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>$r(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${kf(o)}`}}}function Rf(e,t){let n=t.map(He),r=NS(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let s=ee(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${s} ${r}`:`Couldn't ${s} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let s=n.filter(a=>a.state?.status==="error"),o=s.length?s:n,i=Array.from(new Set(o.map(a=>$r(a.tool))));return`Couldn't finish using ${kf(i)}`}}}var qS=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),ij={read:{verb:"Read",running:"Reading",objectKeys:["filePath","path","file"]},write:{verb:"Wrote",running:"Writing",objectKeys:["filePath","path","file"]},edit:{verb:"Edited",running:"Editing",objectKeys:["filePath","path","file"]},apply_patch:{verb:"Edited",running:"Editing",objectKeys:["filePath","path"]},bash:{verb:"Ran",running:"Running",objectKeys:["command"]},glob:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},grep:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},list:{verb:"Listed",running:"Listing",objectKeys:["path"]},web_search:{verb:"Searched",running:"Searching",objectKeys:["query"]},websearch:{verb:"Searched",running:"Searching",objectKeys:["query"]},webfetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},web_fetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},scrape:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},scrape_webpage:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},task:{verb:"Delegated",running:"Delegating",objectKeys:["description"]},memory:{verb:"Remembered",running:"Remembering"},get_mem:{verb:"Recalled",running:"Recalling"},memory_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},mem_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},ltm_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},dcp_compress:{verb:"Compacted",running:"Compacting"},dcp_distill:{verb:"Distilled",running:"Distilling"},dcp_prune:{verb:"Pruned",running:"Pruning"},compress:{verb:"Compacted",running:"Compacting"},distill:{verb:"Distilled",running:"Distilling"},prune:{verb:"Pruned",running:"Pruning"},context_info:{verb:"Checked context",running:"Checking context"}};function aj(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Cr(t)||t}function cj(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let s=n[r];if(typeof s=="string"&&s.trim())return aj(r,s.trim())}}function Pn(e){let t=ye(e)?ae(e):e;if(Ae(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!te(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=he(t.tool),r=ij[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:cj(s,r.objectKeys),tier:qS.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function qo(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(Pn(o).tier==="plumbing"){r=!0;continue}if(Ae(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,te(o)&&Bo(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function Cf(e){return`${e} ${e===1?"step":"steps"}`}function GS(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${Cf(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${Cf(n)}`:s===0?`${Cf(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function Tf(e){let t=new Map,n=0;for(let s of e){if(!te(s)||Pn(s).tier==="plumbing")continue;let o=Sn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),Bo(s)!=="ok"&&(n+=1))}if(t.size===0)return GS(qo(e),!1);let r=[...t].map(([s,o],i)=>{let a=Br(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function lj(e){let t=!1,n=!1,r=!1,s=null,o=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),s==null&&d.error!=null&&(s=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(t=!0),e.userMessage&&o(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)o(p.info),i(p.parts);return c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function uj(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function pj(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let s=r.state.time;typeof s?.start=="number"&&(t=Math.min(t,s.start)),typeof s?.end=="number"&&(n=Math.max(n,s.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function WS(e,t){let n=t.map(He),r=uj(n);return{id:n[0].callID,family:e,label:r==="error"?Rf(e,n):Br(e,n),parts:t,status:r,durationMs:r==="running"?void 0:pj(n)}}function Ef(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(WS(n,r)),n=null,r=[]};for(let o of e){let i=He(o),a=Sn(i.tool);if(a!=="hidden"&&!zs(i)){if(Gg(i.tool)){s(),t.push(WS(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function Go(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function If(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of Ef(s))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});s=[]}};for(let a of e)if(t(a)!=="plumbing"){if(Ae(a)){let c=a.text?.trim();if(!c)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(c);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=Go(a);continue}if(o(),te(a)){s.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}o(),i();for(let a=0;a<n.length-1;a++){let c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var dj=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function gj(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]*)`/g,"$1").replace(/^#{1,6}\s*/gm,"").replace(/\*\*([^*]*)\*\*/g,"$1").replace(/(^|\s)[*_]([^*_]+)[*_]/g,"$1$2").replace(/^\s*[-*+]\s+/gm,"").replace(/\s+/g," ").trim()}function mj(e){let t=e.flatMap(s=>{let o=gj(s);return o?[o]:[]}).join(" ").trim();return t?dj.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function YS(e){return e?.info?.time??{}}function fj(e){let t=YS(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Wo=6e4,yj=10080*Wo,KS=1440;function VS(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function hj(e,t){let n=t.getTime()-e.getTime(),r=n/Wo,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<KS)return s(Math.round(r/60),"hour");let o=(n-(VS(t)-VS(e)))/Wo;return s(Math.round(o/KS),"day")}function JS(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}var HS=new Map;function _j(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=HS.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),HS.set(r,s)),s}function Ko(e,t,n){return _j(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?bj(r.value,n):r.value).join("")}function bj(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function zS(e,t){return Ko(e,{year:"numeric"},t)}function Sj(e,t,n={}){let r=JS(e);if(!r)return"";let s=i=>Ko(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return s(!0);let o=Math.max(0,t-r.getTime());return o<Wo?"just now":o<yj?hj(r,new Date(t)):s(zS(r,n)!==zS(new Date(t),n))}function Pj(e,t={}){let n=JS(e);if(!n)return"";let r=Ko(n,{month:"long",day:"numeric",year:"numeric"},t),s=Ko(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function Mf(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!Wg(o)){if(De(o)){s(),n.push({kind:"text",part:o});continue}if(te(o)&&(Kg(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function xj(e){let t=he(e);return t==="show"||t==="show_user"}function Of(e,t={}){let n=[],r=[],s=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(o=>o.part)}),r=[]};for(let o of e){if(o.kind==="standalone"&&xj(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var wj=["title","description","path","url","content","language","aspect_ratio","attachment"];function QS(e,t){if(!t||typeof t!="object")return null;let n=t;if(or(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of wj){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function vj(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function Df(e){let t=[];for(let n of e){let r=n.state,s=r.input??{};if(r.status==="error"){let a=typeof s.title=="string"&&s.title?s.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let o=vj(s.items),i=o?o.map(a=>QS(n.callID,a)).filter(a=>!!a):[QS(n.callID,s)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function jf(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Ur=e=>"id"in e?e.id:e.userMessage.info.id,XS=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,Aj=e=>e.time?.completed;function kj(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function Rj(e,t){let n=Ur(e);return t.pendingTurnIds.has(n)||XS(e)===0&&t.pendingPromptIds.has(n)}function Cj(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Ur(r)));if(t)return Ur(t);let n=e.turns.findIndex(r=>Rj(r,e));return n<=0?null:Ur(e.turns[n-1])}function Tj(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function Ej(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function Ij(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:jf({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function Mj(e,t){for(let n=e.length-1;n>=0;n--){let r=Ur(e[n]);if(t(r))return XS(e[n])===0?r:null}return null}function Lf(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),s=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(c=>c.userMessage.info.id)}),o=e.hintMessageId??null;if(o){if(n>=0&&t[n].userMessage.info.id===o)return s(n);let a=r.indexOf(o);if(a>=0)return s(n+1+a)}if(n>=0){let a=t[n],c=a.assistantMessages[a.assistantMessages.length-1];if(!Aj(c.info)&&!c.info.error)return s(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return s(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:s(n)}function Oj(e,t){for(let n=t.length-1;n>=0;n--)if(t[n].info.role==="user")return t[n].info.id===e;return!1}function Dj(e,t){return!t||!e?!1:e.type!=="idle"}function jj(e,t){return!e&&!!t}function Lj(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return we(n.error)?.message||_e(n.error)}}function $j(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Rr(n.error)}}function Bj(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return we(n.error)}}function $f(e){if(e){if(te(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(Ae(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(De(e))return"Gathering thoughts..."}}function Bf(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,s=te(r)?r:void 0;if(s&&(s.tool==="task"||s.tool==="agent_task"||s.tool==="agent-task"||s.tool==="task_create"||s.tool==="task-create"||s.tool==="task_start"||s.tool==="task-start")&&s.state.status==="running"&&t&&t.length>0){for(let i=t.length-1;i>=0;i--){let a=t[i];if(a.info.role==="assistant")for(let c=a.parts.length-1;c>=0;c--){let p=$f(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let o=$f(r);if(o)return o}return"Figuring out what\u2019s next..."}function Uf(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}function Ff(e){let t={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},n=!1,r=i=>{n=!0,t.input+=i.input??0,t.output+=i.output??0,t.reasoning+=i.reasoning??0,t.cacheRead+=i.cache?.read??0,t.cacheWrite+=i.cache?.write??0},s=new Set;for(let{part:i,message:a}of e){if(i.type!=="step-finish")continue;let c=i.tokens;c&&(s.add(a.info.id),r(c))}let o=new Set;for(let{message:i}of e){if(i.info.role!=="assistant"||s.has(i.info.id)||o.has(i.info.id))continue;o.add(i.info.id);let a=i.info.tokens;a&&r(a)}return n?t:void 0}function Uj(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function Fj(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function Nj(e){if(!e||e.type!=="retry")return;let t=e,n=_e(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:we(t.message)}}function qj(e){if(!(!e||e.type!=="retry"))return _e(e.message)}function Gj(e){return(e.info.summary?.diffs?.length??0)>0}function ZS(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=he(e.part.tool);return t==="show"||t==="show_user"}function Wj(e){return e.kind==="text"&&!e.part.text?.trim()}function Nf(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(ZS(o)||Wj(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):ZS(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function Kj(e){let t=e==null?"":Uf(e);return t?`Worked for ${t}`:"Worked"}function eP(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>De(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return te(s)&&s.tool==="bash"}function Vj(e){if(eP(e))return e.assistantMessages[0].parts[0]}function Hj(e){if(!e)return"";let t=e;return t=t.replace(/^##\s*Worker Result\s*\n/i,""),t=t.replace(/^\*\*Agent:\*\*.*\n?/m,""),t=t.replace(/^\*\*Task:\*\*.*\n?/m,""),t=t.replace(/^\*\*Status:\*\*.*\n?/m,""),t=t.replace(/^\*\*Session:\*\*.*\n?/m,""),t=t.replace(/^\*\*Duration:\*\*.*\n?/m,""),t=lS(t,"beeuni_goal_system"),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created and started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created:.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* failed to start.*$/gm,""),t=t.replace(/^Message sent to task.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* approved.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* cancelled.*$/gm,""),t=t.replace(/Worker session: ses_[a-zA-Z0-9]+/g,""),t=t.replace(/^---\s*\n/gm,""),t=t.trim(),t||""}function zj(e){return e?e.split(`
|
|
84
|
+
`).filter(n=>n.trim()).length<=3:!1}function Yj(e){if(!e)return null;let n=e.split(`
|
|
85
|
+
`).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function Jj(e){if(!e)return[];let t=[],n=e.split(`
|
|
86
|
+
`).filter(r=>r.trim());for(let r of n){let s=gS(r);if(s){let o=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...s,sessionId:o?.[0]})}}return t}var ht={write:{verb:"Wrote",running:"Writing",failed:"Couldn't write"},edit:{verb:"Edited",running:"Editing",failed:"Couldn't update"},delete:{verb:"Deleted",running:"Deleting",failed:"Couldn't delete"},rename:{verb:"Renamed",running:"Renaming",failed:"Couldn't rename"},change:{verb:"Changed",running:"Changing",failed:"Couldn't apply"},read:{verb:"Read",running:"Reading",failed:"Couldn't read"},list:{verb:"Listed",running:"Listing",failed:"Couldn't list"}};function Qj(e,t){let n=ht[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function Xj(e,t){return t?"failed":e?"running":"done"}var Zj={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function eL(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.beeuni\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function tL(e,t){if(!e)return null;let n=e.indexOf(`
|
|
87
|
+
`),r=n===-1?e:e.slice(0,n),s=n===-1?"":e.slice(n+1);if(pS(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
|
|
86
88
|
`).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
|
|
87
89
|
`)};if(/files and directories/i.test(r)){let o=t.replace(/\/$/,""),i=[];for(let a of s.split(`
|
|
88
|
-
`)){if(!a.trim())continue;let 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
|
|
90
|
+
`)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var nL={add:{...ht.write,icon:"create"},delete:{...ht.delete,icon:"delete"},move:{...ht.rename,icon:"edit"},update:{...ht.edit,icon:"edit"}},tP={...ht.change,icon:"edit"};function rL(e){if(e.length===0)return tP;let t=nP(e[0]);for(let n=1;n<e.length;n++)if(nP(e[n])!==t)return tP;return nL[t]}function nP(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function sL(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.startsWith("Error:")?{success:!1,action:"unknown",error:e.replace(/^Error:\s*/,"")}:null}}function qf(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],s;for(;(s=n.exec(e))!==null;)r.push(s[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(o,i)=>r[i]?[r[i]]:[])}function oL(e){if(!e)return null;let t=Er(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=pf(e,"content");if(r!==null){let o=r.split(`
|
|
89
91
|
`).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
|
|
90
|
-
`);return{path:n,type:"file",content:o}}let s=
|
|
91
|
-
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function
|
|
92
|
-
\u2026`:e}function
|
|
92
|
+
`);return{path:n,type:"file",content:o}}let s=pf(e,"entries");if(s!==null){let o=s.split(`
|
|
93
|
+
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function iL(e){let t=cS(e,"skill_content");return t!==null?t.trim():e}function rP(e){let t=Er(e,"<skill_files>","</skill_files>");return t===null?[]:uS(t,"<file>","</file>").map(n=>n.trim())}function aL(e){let t=aS(e,"skill_content");if(t===null)return"";for(let n of["dir","directory","path","base","baseDir","base_dir"]){let r=t.match(new RegExp(`\\b${n}\\s*=\\s*["']([^"']+)["']`,"i"));if(r?.[1]?.trim())return r[1].trim()}return""}function cL(e){return dS(e,["Base directory","Directory","Skill directory"])?.trim()??""}function sP(e){return tt(aL(e)||cL(e))}function lL(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return tt(n.trim())}return""}var uL="skills";function pL(e){let t=iS(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(s=>s.trim());if(n.some(s=>s===".."||s==="."))return"";let r=n.at(-1)??"";return r?`${uL}/${r}`:""}function dL(e,t,n){let s=tt(t?.trim()??"")||sP(e)||pL(n),o=rP(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(o){if(o.startsWith("/"))return o;if(s)return`${s}/${o}`}return s?`${s}/SKILL.md`:null}var gL=4e3;function Fr(e,t=gL){return e.length>t?`${e.slice(0,t)}
|
|
94
|
+
\u2026`:e}function oP(e){if(e!==void 0)try{return Fr(JSON.stringify(e,null,2))}catch{return}}function re(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function xn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function mL(e){let t=re(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=xn(e.outputParsed);if(!n)return{kind:"web-search",query:t};let s=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(o=>{let i=xn(o)??{};return{title:re(i.title)??"",url:re(i.url,i.link)??"",snippet:re(i.snippet,i.description,i.source)}});return{kind:"web-search",query:re(n.query)??t,results:s.length>0?s:void 0,answer:re(n.answer)}}var fL=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Wf(e){let t=e.match(fL);return t?Number(t[1]):void 0}function yL(e,t,n){let r="",s=0;for(;;){let o=e.indexOf(t,s);if(o===-1)return r+e.slice(s);let i=e.indexOf(n,o+t.length);if(i===-1)return r+e.slice(s);r+=e.slice(s,o),s=i+n.length}}var hL=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function _L(e){let t=-1;for(let n of hL){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var bL=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function SL(e){return e.replace(bL,"")}function PL(e){let t=re(e.input?.command)??"",n=e.output??"",r=Wf(n),o=SL(_L(yL(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:o||void 0,exitCode:r}}function Kf(e){return re(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function xL(e){let t=e.status==="error"?e.error:e.output&&Fr(e.output)||void 0;return{kind:"file-read",path:Kf(e),preview:t}}function wL(e){let t=re(e.input?.content),n=e.status==="error"?e.error:Fr(t??e.output??"")||void 0;return{kind:"file-write",path:Kf(e),preview:n}}var vL=256*1024;function AL(e,t){if(e.length+t.length>vL)return;let n=e.split(`
|
|
93
95
|
`),r=t.split(`
|
|
94
|
-
`),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let 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
|
|
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$);})();
|
|
96
|
+
`),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let c=0;c<s;c++)a.push({type:"unchanged",text:n[c]});for(let c=s;c<o;c++)a.push({type:"removed",text:n[c]});for(let c=s;c<i;c++)a.push({type:"added",text:r[c]});for(let c=o;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function kL(e){let t=Io(e.input),n=t.map(([s,o])=>AL(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:Kf(e),diff:r}}var aP=/^Found\s+(\d+)\s+match/i,RL=/^(\/[^:]+?):\s*/,iP=/Line\s+(\d+):/g;function CL(e){let t=e.trim(),n=t.match(aP),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let s=[];for(let o of r.split(/\n\n+/)){let i=o.trim();if(!i)continue;let a=i.match(RL);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(iP.lastIndex=0;(g=iP.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,f).trim();s.push({path:c,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return s}function TL(e){return e.trim().split(`
|
|
97
|
+
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function EL(e){let t=re(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=aP.test(e.output.trim())?CL(e.output):TL(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function IL(e){let t=re(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=re(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function Gf(e){let t=xn(e)??{};return{content:re(t.content)??"",status:re(t.status)??"pending",priority:re(t.priority)}}function ML(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(Gf)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(Gf)};let n=xn(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(Gf)}:{kind:"todo",items:[]}}function OL(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=xn(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let c=xn(a),p=c&&re(c.label);return p?[{label:p,description:c?re(c.description):void 0}]:[]});return{question:re(s.question)??"",header:re(s.header),options:i}})}}function DL(e){let n=e.input&&Object.keys(e.input).length>0?oP(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Fr(e.outputParsed):oP(e.outputParsed):e.outputText!==void 0?r=Fr(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function cP(e){switch(le(e.name)){case"web_search":return mL(e);case"bash":return PL(e);case"read":return xL(e);case"write":return wL(e);case"edit":return kL(e);case"grep":case"glob":return EL(e);case"task":return IL(e);case"todowrite":return ML(e);case"question":return OL(e);default:return DL(e)}}var jL=new Set(["AbortError","MessageAbortedError"]),LL=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],$L=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function lP(e){let t=e.toLowerCase();return $L.some(n=>t.includes(n))?!1:LL.some(n=>t.includes(n))}function BL(e){let t=e.data,n=t&&typeof t=="object"?t.message:void 0;return typeof n=="string"?n:typeof e.message=="string"?e.message:void 0}function Nr(e){if(typeof e=="string")return lP(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&jL.has(n))return!0;let r=BL(t);return typeof r=="string"?lP(r):!1}var uP=["user","runtime-disposed","orphan-finalized","wake"],UL=["orphan-finalized","wake"];function FL(e){if(!e||typeof e!="object")return;let t=e.data;if(!t||typeof t!="object")return;let n=t.reason;if(!(typeof n!="string"||!n))return uP.includes(n)?n:void 0}function Gr(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e??"")}function Vf(e){let t=Gr(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}var NL=Vf;function Vo(e){let t=Vf(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var qL=Vo;function pP(e){return Vo(e)!==null}var GL=pP,WL=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],KL=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],VL=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function dP(e){return VL.test(Gr(e))}function wn(e){let t=Gr(e);return t?dP(t)||WL.some(n=>n.test(t)):!1}var HL=/server url not ready|sandbox is still loading/i;function zL(e){return HL.test(Gr(e))||wn(e)}var qr=class extends Error{constructor(t){let n=t?.trim();super(n&&wn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function gP(e){let t=Vo(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${a}`,detail:o?`${i?`${i}: `:""}${o}`:void 0}}let n=Gr(e);return wn(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var YL=gP;function Hf(e){if(!e.external_id){if(e.base_url)return e.base_url;throw new Error(`Cannot build sandbox URL: missing external_id for ${e.provider} sandbox "${e.sandbox_id}"`)}return`${lt()}/p/${e.external_id}/${Je.BEEUNI_MASTER}`}function JL(e,t){return e.external_id?`${lt()}/p/${e.external_id}/${t}`:null}async function QL(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function mP(e){let t=await ur();if(t)return{sandbox:t.sandbox,created:!1};let r=(await At())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await Et(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await it(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Qs(r,s,o),created:!0}}async function XL(){return(await ur().catch(()=>null))?.sandbox??null}async function ZL(e){return{sandbox:(await mP(e)).sandbox}}async function e$(e){let t=lr(e);if(!t)return null;try{let n=await Rm(t);return n?Qs(await kt(n.project_id),n,null):(await ur(t))?.sandbox??null}catch{return null}}async function t$(e,t){throw await Xs(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function n$(e){let t=lr(e);return(await km().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function r$(){return null}async function s$(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Xs(e);if(!t)throw new Error("Project session sandbox not found");await Xn(t.projectId,t.sessionId)}async function o$(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Xs(e);if(!t)throw new Error("Project session sandbox not found");await Zn(t.projectId,t.sessionId)}async function i$(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function a$(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function zf(e,t,n){let r=Hf(e),s=await j(`${de(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function c$(e,t){return zf(e,`/beeuni/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function l$(e,t,n,r="member"){await zf(e,`/beeuni/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function u$(e,t,n){await zf(e,`/beeuni/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var Yf="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function p$(e){throw G("getInvite",Yf)}async function d$(e){throw G("acceptInvite",Yf)}async function g$(e){throw G("declineInvite",Yf)}async function m$(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function f$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function y$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function h$(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function _$(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function b$(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}async function fP(e){let t=e?`?channel=${e}`:"",r=await(await Fe(`${lt()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await Jf(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function Jf(e){let t=e?`?channel=${e}`:"";return(await(await Fe(`${lt()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function yP(){return(await Fe(`${lt()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}var vn=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function hP(e,t){let n=new Headers(e.headers);return n.set("Accept","application/json"),t&&n.set("Content-Type","application/json"),e.accessToken&&n.set("Authorization",`Bearer ${e.accessToken}`),n}async function _P(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function bP(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function ue(e,t,n){let r=n?.body!==void 0,s=await fetch(`${It(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:hP(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await _P(s);if(!s.ok)throw new vn(bP(s,o),s.status,o);return o}function S$(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString();return n?`?${n}`:""}function SP(e,t){return ue(`/marketplace/items${S$(t)}`,e)}function PP(e){return ue("/marketplace/marketplaces",e)}function xP(e,t){return ue(`/marketplace/items/${encodeURIComponent(e)}`,t)}function wP(e,t,n){return ue(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function vP(e,t){return ue("/access/check-email",t,{method:"POST",body:{email:e}})}function AP(e,t){return ue("/access/request-access",t,{method:"POST",body:e})}function kP(e){return ue("/auth/logout",e,{method:"POST",body:{}})}function RP(e,t){return ue(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function CP(e,t){return ue("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function TP(e,t){return ue(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function EP(e,t){return ue(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function IP(e,t,n={}){return ue(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function MP(e,t){return ue(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function OP(e,t,n,r){return ue(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function DP(e,t){return ue(`/p/public-share/${encodeURIComponent(e)}`,t)}function jP(e,t,n){return ue(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function LP(e,t){return ue("/system/demo-request",t,{method:"POST",body:e})}async function $P(e,t,n){let r=await fetch(`${It(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Jt(t)}`,{headers:hP(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await _P(r);throw new vn(bP(r,s),r.status,s)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}function BP(e,t){throw G("buildPublicTemplateUrl")}async function UP(e,t,n){throw G("getPublicTemplate")}var P$="beeuni:connect-link:";function Qf(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);t=Math.imul(t^s,16777619)>>>0,n=Math.imul(n^s,1540483477)>>>0}return`${P$}${t.toString(36)}${n.toString(36)}`}function x$(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(Qf(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(Qf(i));return}return c}catch{return}},o=(i,a)=>{if(t)try{t.setItem(Qf(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=s(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var FP="Could not start the connect flow.";async function w$(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:FP}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:FP};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var NP=3e3,qP=5e3,GP=5*6e4;function v$(e,t){let n=e===0?NP:qP;return t+n>GP?null:n}function A$(e){let t=e.project_name?.trim();return{app:e.name?.trim()||e.app?.trim()||e.slug,project:t&&t!=="this project"?t:null}}var y2="1";var k$="beeuni.query-cache";function KP(e){return!!e&&typeof e.then=="function"}function WP(e){return KP(e)?e:Promise.resolve()}function R$(e){if(e[0]!=="kx")return!1;let t=e[1];if(t==="accounts")return e.length===3&&typeof e[2]=="string"&&e[2]!=="anonymous";if(t==="projects")return e.length===3;if(t!=="project"||typeof e[2]!="string")return!1;let n=e[3];if(e.length===4)return n==="summary"||n==="detail";if(n!=="sessions")return!1;if(e.length===6)return e[4]==="list-paged";if(e.length===7&&e[4]==="list-paged"){let r=e[6];return typeof r=="object"&&r!==null&&!r.q}return e.length===7&&e[4]==="list-children"?e[6]==="":e.length===5&&e[4]!=="list"&&e[4]!=="list-paged"}function C$(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=k$,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),S=()=>{try{return WP(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},E=(v,b)=>{if(!b)return 0;let P;try{P=JSON.parse(b)}catch{return S(),0}if(!P||P.v!==s||P.user!==n||!Array.isArray(P.queries)||p()-P.at>o)return S(),0;let O=0;for(let A of P.queries){if(!A||!Array.isArray(A.k)||A.d===void 0||typeof A.t!="number"||p()-A.t>o||!r(A.k))continue;let $=v.getQueryState(A.k);$&&$.data!==void 0&&$.dataUpdatedAt>=A.t||(v.setQueryData(A.k,A.d,{updatedAt:A.t}),v.invalidateQueries?.({queryKey:A.k,exact:!0,refetchType:"none"}),O+=1)}return O},L=v=>v.getQueryCache().getAll().filter(b=>b.state.data!==void 0&&r(b.queryKey)).map(b=>({k:b.queryKey,d:b.state.data,t:b.state.dataUpdatedAt})).sort((b,P)=>P.t-b.t),D=(v,b)=>{let P=[],O=0;for(let A of v){let $=JSON.stringify(A).length+1;O+$>b||(P.push(A),O+=$)}return P},w=async v=>{let b=D(L(v),i);for(;;){let P={v:s,user:n,at:p(),queries:b};try{await WP(t.setItem(d,JSON.stringify(P)));return}catch{if(b.length===0)return;b=b.slice(0,Math.floor(b.length/2))}}},y=()=>{f!==null&&(clearTimeout(f),f=null)},_=()=>{y();let v=g;return!v||!m||(m=!1,h=h.then(()=>w(v)).catch(()=>{})),h},R=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,_()},a))};return{storageKey:d,restore(v){let b;try{b=t.getItem(d)}catch{return 0}return KP(b)?b.then(P=>E(v,P)).catch(()=>0):E(v,b)},persist(v){g=v,m=!0;let b=v.getQueryCache().subscribe(P=>{P.type!=="updated"&&P.type!=="removed"&&P.type!=="added"||r(P.query.queryKey)&&R()});return()=>{b(),g===v&&(g=null,y())}},flush(){return _()},async clear(){y(),g=null,m=!1,await h,await S()}}}function T$(){let e;try{e=globalThis.localStorage}catch{e=void 0}if(!e)return null;let t=e;return{getItem:n=>{try{return t.getItem(n)}catch{return null}},setItem:(n,r)=>t.setItem(n,r),removeItem:n=>{try{t.removeItem(n)}catch{}}}}var VP="/beeuni/part/";function HP(e){return typeof e=="string"&&e.startsWith(VP)}async function E$(e){if(!HP(e))throw new Error(`not an attachment part reference: ${e}`);let t=Xe();if(!t)throw new Error("runtime url not bound");let n=await j(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function zP(e){try{let t=new URL(e);if(/^\/proxy\/\d+(?:\/|$)/.test(t.pathname))return`${t.origin}/v1/p/auth`;let n=t.pathname.indexOf("/p/");return n!==-1?`${t.origin}${t.pathname.slice(0,n)}/p/auth`:`${t.origin}/v1/p/auth`}catch{return null}}function I$(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.has(n.origin)}catch{return!1}}function Xf(e,t){return I$(e,t)?(t?zP(t):null)??zP(e):null}function Wr(e){try{let{hostname:t}=new URL(e);return/^p\d+-[^.]+\./.test(t)||/^(?:dev|staging|prod|preview)-p\d+-[a-z0-9-]+\./i.test(t)}catch{return!1}}function Zf(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var M$=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function O$(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function D$(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let s=(t.slice(n+3).split("/")[0]??"").toLowerCase(),o=`${r}://${s}`.split("{port}").map(i=>i.split("{sandbox}").map(O$).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function j$(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function YP(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function L$(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:M$.test(n.hostname)?t.backendUrls.some(r=>{let s=j$(r);return s!==null&&YP(s)===YP(n)}):t.templates.some(r=>D$(n.origin,r))}async function JP(e,t={}){if(!Wr(e))return!1;let n=C().backendUrl;n&&await ut(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return L$(e,{templates:g_(),backendUrls:r})}async function QP(e,t={}){let n=Xf(e,t.serverUrl||C().backendUrl||void 0);if(!n)return!1;let r=await st();if(!r)return!1;try{return(await fetch(n,{method:"POST",credentials:"include",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).ok}catch{return!1}}async function $$(e,t={}){if(Wr(e)){if(!await JP(e,t))return e;let n=await st();return n?Zf(e,n):e}return await QP(e,t),e}var B$=3e3;function XP(e){return!Number.isFinite(e)||e<100||e>599?"unknown":e===502||e===503||e===504?"unreachable":e===401||e===403?"unknown":"reachable"}async function U$(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return XP(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function F$(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function N$(e,t){throw G("buildPresentationTemplatePdfUrl")}function q$(e,t){throw G("buildPresentationTemplateImageUrl")}function ZP(e,t){return`${F$(e)}/presentation/convert-to-${t}`}async function G$(e,t,n,r){let s=ZP(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!1;for(;;){let p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,S)=>{let E=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(E),S(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let h=JSON.parse(m);f=String(h.error||h.detail||h.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function W$(e){return e.activityFresh||e.runtimeReady?"live":e.unreachable||e.stalled?"unreachable":e.sandbox==="stopped"||e.sandbox==="archived"||e.sandbox==="provisioning"||e.sandbox==="queued"||e.sandbox==="branching"?"waking":e.sandbox==="completed"?"unknown":e.sandbox==="failed"?"unreachable":e.sandbox==="running"?"connecting":"unknown"}function K$(e){return e==="unreachable"}function V$(e){return!e||e.status===0?"unknown":e.ok&&Qm(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var ex=1e4,H$={connection:"unknown",faultSinceMs:null};function z$(e,t,n,r=ex){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let s=e.faultSinceMs??n;return n-s>=r?{connection:t,faultSinceMs:s}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:s}}function tx({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<Ho,c=!!t&&i-t.atMs<Jo;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:c,abortFloor:c?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=zo,streamFresh:!!s&&i-s.atMs<=An,inboxFresh:!!n&&i-n.atMs<=Yo,activityFresh:!!o&&i-o.atMs<=An}}function kn(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function ey(e,t,n){if(!t)return!1;let r=kn(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=kn(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function Y$(e,t,n,r){let{activity:s,server:o}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!ey(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function J$(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,c=i?s.turns.filter(g=>!ey(g,n,s)):[],p=c.find(g=>g.state==="active")??c[0],d=!!o&&!(o.type==="idle"&&o.origin==="local");return p&&s.atMs>=a&&(!d||s.atMs>=o.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:kn(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function Q$(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&o.type!=="idle"&&(!p||o.atMs>s.atMs)&&o.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&s.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function X$(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,S=c&&!n&&s.atMs>=p,E=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(S&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:kn(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(E)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let L=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:a};return{state:"idle",source:L.source,turnId:null,since:L.atMs,serverOpenTurnToken:r}}function nx(e){let t=tx(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=Y$(e,t,s,o);if(i)return i;let{result:a,openTurn:c}=J$(e,t,s,o);return a??Q$(e,t,o)??X$(e,t,c,o)}var Ho=6e4,zo=45e3,An=45e3,Yo=1e4,Z$=3e3,Jo=15e3;function e0(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function t0(e){let t=0;for(let n of e)(n.state==="queued"||n.state==="delivering"||n.state==="waiting"&&n.reason!=="held")&&(t+=1);return t}function n0(e){return nx(e)}function r0(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,c=[null,t?t.atMs+Ho:null,n?n.atMs+Jo:null,r?r.atMs+Yo:null,s?s.atMs+zo:null,o?o.atMs+An:null,i?i.atMs+An:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function rx(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(o=>o.message_id===t),r=e.last_ended,s=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!s?.message||Nr({name:s.name??void 0,message:s.message})?null:s}var s0="SandboxMemoryGuard";function o0(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=rx(e,t);if(r?.message){if(r.name!==s0)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let s=e.recent_failures?.find(a=>a.message_id===t);if(!s)return null;let o=s.ended_at?Date.parse(s.ended_at):Number.NaN;return Number.isFinite(o)&&typeof e.atMs=="number"&&e.atMs-o<2500?null:{kind:"unexplained"}}var i0=6e4;function a0(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function c0(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var sx=9e4;function l0(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+sx}var u0=75e3,p0=2,d0=2e4;function ty(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function g0(e){return e.filter(t=>t!=null).join("|")}function m0(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function f0(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...ty(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...ty(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!c&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return g;let f=m0(e.attempts,s);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var y0={"retry-start":"retrying",restart:"restarting"};function h0(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${y0[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function _0(e){return e===1?"once":e===2?"twice":`${e} times`}function b0(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(s=>s.step==="restart").length,n=e.attempts.some(s=>s.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${_0(t)}`),`Tried: ${r.join(", then ")}.`}var S0={"needs-you":{label:"Needs you",tone:"actionable",description:"Waiting for your review"},starting:{label:"Starting",tone:"progress",description:"Its computer is starting"},running:{label:"Running",tone:"live",description:"Its computer is up"},done:{label:"Done",tone:"muted",description:"Finished"},stopped:{label:"Stopped",tone:"muted",description:"Asleep. Opening it wakes its computer"},failed:{label:"Failed",tone:"danger",description:"Its computer didn't start"},legacy:{label:"Legacy",tone:"muted",description:"Imported. Open it to restore"}};function ox(e){return!!(e.metadata??{}).legacy_migration}function P0(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return"running";case"completed":case"stopped":return ox(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function x0(e){switch(e){case"waking":return{label:"Waking computer",tone:"progress"};case"connecting":return{label:"Connecting",tone:"progress"};case"unreachable":return{label:"Can't reach computer",tone:"danger"};default:return null}}var w0={unreachable:"Lost contact with this session's computer. Messages you send are queued until it reconnects.",unreachableMidTurn:"Lost contact with this session's computer while a turn is still open. Messages you send stay queued until it answers.",stalled:"Waking this session's computer is taking longer than usual. Messages you send are queued.",starting:"Starting this session's computer. Your message sends automatically.",idle:"This session's computer is asleep. Your next message wakes it up and is delivered.",waking:"Waking this session's computer. Messages you send are queued and go out automatically."};function v0(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function Qo(e){return e.runtime_sessions??e.opencode_sessions??[]}function ix(e){let t=Qo(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function A0(e){let t=ix(e);return t?Qo(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function k0(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>Qo(r).some(s=>s.id===t))??null)}var R0=new Set;function ax(e){for(let t of[...R0])try{t(e)}catch{}}var dx={schema:pe,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var gx=e=>Object.values(e.ext??{}).find(t=>t.version===ke),mx=e=>!!e&&gx(e)!==void 0,C0=e=>{let t=gx(e);return t?t.native_id??null:e.thread_id},cx=new WeakMap;function fx(e,t){let n=C0(e),r=cx.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=Vs({...dx,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return cx.set(t,{native:n,rows:o}),o}var ny=e=>e.info.time?.created;var T0=(e,t)=>(ny(e)??-1/0)-(ny(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var lx=new WeakMap,ux=new WeakMap,yx=e=>typeof e=="object"&&e!==null,E0=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,I0=e=>e.info.role==="user"&&e.parts.some(t=>yx(t)&&t.type==="compaction"),M0=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},px=new WeakMap;function O0(e,t,n){let r=t.info,s=`${e}|${String(r.id)}|${String(r.time?.created)}`,o=!1,i=n.blocks.map((a,c)=>{let p=t.parts[c];if(!yx(p)||a.type==="compaction")return a;let d=`${s}|${c}|${a.id}`,g=px.get(p);return g&&g.key===d?(o=!0,g.block):(px.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function D0(e){let t=new Map,n=new Set;for(let r of e){if(!I0(r))continue;let s=e.find(o=>!n.has(o)&&M0(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function j0(e,t,n,r,s){let o=lx.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=Hs({session_id:e,root_id:t,rows:(r?[n,r]:[n]).map(d=>({runtime_session_id:t,info:d.info,parts:d.parts}))},{live:!0}),c=O0(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:s,message:{...c,seq:s},lost:a.grade_counts};return lx.set(n,p),p}function hx(e,t,n){let r=ux.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(T0),{paired:o,used:i}=D0(s),a={tool_input:0,cut_point:0,attachment:0},c=[];for(let m of s){if(i.has(m))continue;let f=j0(e,t,m,o.get(m),c.length+1);for(let h of["tool_input","cut_point","attachment"])a[h]+=f.lost[h];c.push(f.message)}let p=E0(s.map(ny).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=c.filter(m=>m.role==="user"&&m.kind==="turn"),g={...dx,session_id:e,created_at:p,restore_grade:a.tool_input+a.cut_point+a.attachment>0?"partial":"converted",grade_counts:a,harness:{current:"opencode",history:[]},selection:{agent:d.at(-1)?.agent??null,model:d.at(-1)?.model??null},threads:[{schema:pe,v:1,thread_id:t,parent_thread_id:null,spawned_by:null,agent:d[0]?.agent??null,title:null,created_at:c[0]?.created_at||p,messages:c,ext:{opencode:{version:ke,native_id:t}}}]};return ux.set(n,{sessionId:e,native:t,log:g}),g}var ry=new WeakMap,Rn=new WeakMap,_x=new WeakMap;function Xo(e){let t,n=Rn.get(e);return n&&(t=L0(n).get(e.id)),t?(ry.set(t,e),t):(e.type!=="harness"?t=Ng(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=_x.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},_x.set(e,t)),t&&ry.set(t,e),t)}var Kr=e=>ry.get(e),Bt=e=>e.flatMap(t=>Xo(t)??[]),bx=new WeakMap;function L0(e){let t=bx.get(e);return t||bx.set(e,t=new Map(_t(e)[0]?.parts.map(n=>[n.id,n]))),t}var Sx=new Map;function _t(e){let t=Sx.get(e.thread_id);return t||(t={schema:pe,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},Sx.set(e.thread_id,t)),fx(t,e)}var $0="beeuni-v1-import";function kx(e,t){let n=Ff(e);return n?{cost:null,tokens:n}:void 0}var sy={schema:pe,v:1};function Zo(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var oy=e=>e.type==="tool_call",B0=e=>e.status==="pending"||e.status==="running",iy=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function Rx(e,t){let n=iy(e);return!B0(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var Px=new WeakMap;function Cx(e,t){let n=Px.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),s={...sy,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"beeuni-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return Px.set(e,s),s}var xx=new WeakMap;function U0(e){let t=xx.get(e);return t||(t={...sy,message_id:e.reply_to,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},xx.set(e,t)),t}var wx=new WeakMap;function F0(e){let t=wx.get(e);return t||(t={...sy,message_id:`${e.message_id}:continued`,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},wx.set(e,t)),t}var N0=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function q0(e,t){let n=[],r=new Map;for(let g of e){if(g.role!=="user"||g.kind==="context"||r.has(g.message_id))continue;let m={user:g,assistant:[],partial:!1};r.set(g.message_id,m),n.push(m)}let s=[],o=[],i=new Map,a=new Map,c=null,p=null;for(let g of e){if(g.role==="user"){let S=r.get(g.message_id);S&&!t.has(g.message_id)&&(c=S,i.has(S)||i.set(S,i.size),S.user.kind==="compaction"&&(p=S));continue}if(g.role!=="assistant"||N0(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??c;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let S=a.get(p);S||(S={user:F0(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,S)),f=S}if(f){f.assistant.push(g);continue}if(!g.reply_to){o.push(g);continue}let h=s[s.length-1];h&&h.user.message_id===g.reply_to?h.assistant.push(g):s.push({user:U0(g),assistant:[g],partial:!0})}if(o.length){let g=n[0]??s[0];g?g.assistant.unshift(...o):n.push({user:o[0],assistant:o.slice(1),partial:!1})}let d=n.filter(g=>!t.has(g.user.message_id)).flatMap(g=>{let m=a.get(g);return m?[g,m]:[g]});return[...s,...d,...[...t].flatMap(g=>r.get(g)??[])]}function G0(e,t){if(!t)return t;let n=t;for(let r of e){let s=r.continues;s&&(n===s.marker||n===s.prompt||t===s.prompt)&&(n=r.user.message_id)}return n}function W0(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=_t(n)[0]?.info?.error??n.error.message,s=we(r),o=Rr(r);return{code:n.error.code,message:s?.message||_e(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function K0(e,t,n){return e.length&&e.every(t)?kx(e.flatMap(r=>_t(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:ay(e,n)}function ay(e,t){let n=e.flatMap(r=>{let s=r.usage;if(!s)return[];let o={type:"step-finish",cost:s.cost??0,tokens:{input:s.input,output:s.output,reasoning:s.reasoning??0,cache:{read:s.cache_read,write:s.cache_write}}};return[{part:o,message:{info:{id:r.message_id,role:"assistant",providerID:r.model?.provider,modelID:r.model?.model},parts:[o]}}]});return kx(n,t)??null}function V0(e){if(e.kind!=="compaction")return null;let t=e.blocks.find(n=>n.type==="compaction")??null;return{block:t,hasContent:!!t?.summary?.trim(),inFlight:e.status==="streaming"}}function H0(e){let t=e.user.blocks;if(!t.length||!t.every(r=>r.type==="text"&&r.synthetic))return null;let n=e.assistant.length===1&&e.assistant[0].blocks.length===1?e.assistant[0].blocks[0]:null;return n&&oy(n)&&n.name==="bash"?n:null}function z0(e,t,n,r){if(!n.length)return[];let s=new Set(e.assistant.map(i=>i.message_id)),o=new Set;for(let i of n)i.spawned_by&&s.has(i.spawned_by.message_id)&&o.add(i.thread_id);for(let i of t){let a=i.type==="subtask"?i.thread_id:oy(i)?Or(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var Y0=e=>e.assistant.some(t=>t.blocks.some(n=>oy(n)&&le(n.name)==="todowrite"&&_n(n))),vx=new WeakMap,J0=[];function cy(e){let t=Zo(e.messages,n=>n.role==="assistant");return!!t&&wf(_t(t))}var Ax=new WeakMap;function Q0(e){let t=Ax.get(e);if(!t){let n=e.messages.filter(r=>r.in_context||r.status==="streaming");t=n.length===e.messages.length?e:{...e,messages:n},Ax.set(e,t)}return t}function ei(e,t={}){let n=t.hideOutOfContext?Q0(e):e,r=new Set(t.held??J0),s=q0(n.messages,r),o=Zo(n.messages,f=>f.role==="assistant"),i=cy(n),a=Lf({turns:s.map(f=>({userMessage:{info:{id:f.user.message_id}},assistantMessages:f.assistant.map(h=>({info:{time:h.status==="streaming"?{}:{completed:1},error:h.error??void 0}}))})),hintMessageId:G0(s,t.liveMessageId),unrunTurnIds:r}),c=Zo(s,Y0)??s[s.length-1],p=mx(n),d=f=>p||f.producer.harness===$0,g=t.threads??[],m=new Set(g.map(f=>f.thread_id));return s.map(f=>{let h=t.busy===!0&&a.workingTurnId===f.user.message_id,S=a.pendingTurnIds.includes(f.user.message_id),E=i&&f.assistant.includes(o),L=`${f.partial}|${h}|${S}|${f===c}|${E}`,D=vx.get(f.user);if(D&&D.key===L&&D.pricing===t.pricing&&D.heads===t.threads&&D.assistant.length===f.assistant.length&&D.assistant.every((v,b)=>v===f.assistant[b]))return D.turn;let w=f.assistant.flatMap(v=>v.blocks);for(let v of f.assistant)for(let b of v.blocks)Rn.set(b,v);let y=z0(f,w,g,m),_=f.assistant[f.assistant.length-1],R={id:f.user.message_id,user:f.user,assistant:f.assistant,partial:f.partial,continues:f.continues??null,blocks:w,status:E?"streaming":_?_.status:f.user.kind==="compaction"?f.user.status:"pending",error:W0(f),cost:K0([f.user,...f.assistant],d,t.pricing),compaction:V0(f.user),threads:y,plan:f===c,shell:H0(f),response:Zo(w,v=>v.type==="text"&&!!v.text.trim())??null,attachments:f.user.blocks.filter(v=>v.type==="attachment"&&(v.mime.startsWith("image/")||v.mime==="application/pdf")),live:h,queued:S,retrying:E};return vx.set(f.user,{assistant:f.assistant,key:L,pricing:t.pricing,heads:t.threads,turn:R}),R})}var ly=e=>Kr(e);function Mx(e,t={}){return Of(Mf(Bt(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(Kr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(ly)}:n.kind==="text"?{kind:n.kind,block:Kr(n.part)}:{kind:n.kind,block:ly(n.part)})}var X0=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:Bt(e.blocks)}:{kind:e.kind,part:Xo(e.block)};function Ox(e,t){let n=new Map(e.map(o=>[X0(o),o])),r=Nf([...n.keys()],t);if(!r)return null;let s=o=>o.map(i=>n.get(i));return{work:s(r.work),hoisted:s(r.hoisted),final:s(r.final)}}function Z0(e){if(!te(e)||!qg(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=bf(e);return(n.answers??qf(n.outputText??"",t.length)??[]).length>0}function Dx(e){return If(Bt(e),n=>Pn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(Z0)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:Kr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(ly),family:n.step.family,label:n.step.label,status:n.step.status,durationMs:n.step.durationMs};let r=e.find(o=>o.id===n.key.slice(8)),s=r&&Rn.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function jx(e,t){return Bf(Bt(e.blocks).map(n=>({part:n})),t?.flatMap(_t))}function Lx(e){return qo(Bt(e))}function $x(e){return Tf(Bt(e))}function Bx(e,t){return t.working?t.trailing?!0:e.some(n=>{if(n.type==="tool_call")return n.status==="pending"||n.status==="running";if(n.type!=="reasoning")return!1;let r=Xo(n),s=Rn.get(n);return!!r&&Ae(r)&&Go(r)&&(!s||s.status==="streaming")}):!1}var Tx=new WeakMap;function Ux(e){if(!iy(e))return e;let t=Tx.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},Tx.set(e,t)}return t}function eB(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function Fx(e){let t=e.map(ae),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=Df(t).map(eB);return ar({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function Nx(e,t,n){let r=ae(e),s=r.state;return ar({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function qx(e){let t=_t(e).map(r=>jo(r)),n=t.find(r=>r.error)?.error;return{parts:t.flatMap(r=>r.parts),error:n,isEmpty:t.every(r=>r.isEmpty)&&!n}}var Ex=Object.freeze([]),Ix=new WeakMap;function Gx(e){if(!e)return Ex;let t=Ix.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&_n(s)):[]);t=n.length?n:Ex,Ix.set(e,t)}return t}function Wx(e,t={}){let n={cost:null,messages:{all:0,user:0,assistant:0},tokens:{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},context:null};for(let r of ei(e)){let s=ay([r.user,...r.assistant],t.pricing);if(s)for(let o of Object.keys(n.tokens))n.tokens[o]+=s.tokens[o]}for(let r of e.messages){r.role==="user"?n.messages.user++:r.role==="assistant"&&n.messages.assistant++,r.kind==="compaction"&&r.status!=="streaming"&&n.messages.assistant++;let s=r.usage;(r.role==="assistant"||r.kind==="compaction")&&s&&s.input+s.output+(s.reasoning??0)+s.cache_read+s.cache_write>0&&(n.context=r)}return n.messages.all=n.messages.user+n.messages.assistant,n}var tB="prt_beeuni_restore_g";function Vx(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(tB))}function Hx(e,t){let n=new Map,r=[...e??[]].sort((s,o)=>s.from_seq-o.from_seq);for(let s=1;s<r.length;s++){let o=r[s],i=r[s-1].harness;if(o.harness===i)continue;let a=t.findIndex(c=>c.user.seq>=o.from_seq);a<0||a===0&&t[0].user.seq!==o.from_seq||n.set(t[a].id,{harness:o.harness,previous:i,version:o.version,at:o.at})}return n}var uy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nt=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,nB=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function zx(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.beeuni?.data,n=uy(t)?t.restore:void 0;if(!uy(n))return null;let r=uy(n.dropped)?n.dropped:{},s=e.grade_counts,o=[{kind:"message",count:nt(r.message)},{kind:"attachment",count:nt(s?.attachment)},{kind:"text",count:nt(r.text)+nt(n.truncated)},{kind:"tool_input",count:nt(s?.tool_input)},{kind:"tool_result",count:nt(r.tool_result)},{kind:"cut_point",count:nt(s?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,c])=>nB.has(a)?i:i+nt(c),0)}];return{generation:nt(n.generation),missing:o.filter(i=>i.count>0)}}var Yx=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function Jx(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of Yx(r))s.ref&&s.bytes!==void 0&&!t.has(s.ref)&&t.set(s.ref,s.bytes);return[...t].map(([n,r])=>({ref:n,bytes:r}))}var Qx=(e,t)=>{let n=e.ref===void 0?void 0:t.get(e.ref);if(n===void 0)return e;let{ref:r,bytes:s,...o}=e;return{...o,text:n}},rB=(e,t)=>e.map(n=>n.type==="text"?Qx(n,t):n),Kx=new WeakMap;function sB(e,t){let n=Kx.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>Yx(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?Qx(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:rB(s.result.content,t)}}:s)}:e;return Kx.set(e,{texts:t,out:r}),r}var ti=1024*1024;function Xx(e){return e.reduce((t,n)=>t+n.bytes,0)>ti?"download":"inline"}function Zx(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>ti)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function ew(e,t){if(t.size===0)return e;let n=e.messages.map(r=>sB(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function oB(e){return e==="TIMEOUT"||e==="request_deadline"}function iB(e){let t=nw(e)?e.code:void 0;return typeof t=="string"?t:void 0}var nw=e=>typeof e=="object"&&e!==null;function tw(e){let t=e?.metadata;return!!nw(t)&&t.warm===!0}var aB=5,cB=2e3,lB=e=>new Promise(t=>setTimeout(t,e));async function uB(e,{attempts:t=aB,delayMs:n=cB,sleep:r=lB}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function pB(e,t){let n=new Map,r=new Set,s=new Set,o=new Set,i=0,a=(c,p,d)=>{if(r.has(c)||n.has(c))return Promise.resolve();r.add(c);let g=i,m=(async()=>{let f=null;try{let h=await e.ensure(c,p);if(g!==i)return;s.has(h.sessionId)?f=h.sessionId:n.set(c,h)}catch{}finally{g===i&&r.delete(c)}f&&d>0&&await a(c,f,d-1)})();return o.add(m),m.finally(()=>o.delete(m)),m};return{ensure:(c,p)=>a(c,p?.excludeSessionId,1),take:(c,p,{replenish:d})=>{let g=n.get(c);return g?(n.delete(c),s.add(g.sessionId),d&&a(c,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(c,p,d)=>{try{return await e.claim(c,d),!0}catch(g){return oB(iB(g))?uB(async()=>!tw(await e.read(c,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:c=>{for(let[p,d]of n)if(d.sessionId===c)return n.delete(p),s.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(tw(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),s.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),s.clear()},settled:async()=>{for(;o.size>0;)await Promise.all([...o])}}}var dB=12e4,ni=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},gB=1e3,mB=15e3,rw=100,fB=50,yB=10;function sw(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let i=new URLSearchParams({limit:String(r)});s&&i.set("before",s);let a=await e.getToken?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!c.ok)throw c.status===503?new qr(`session ${c.status}`):new x(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function ow(e){return hB(sw(e))}function iw(e){return new py({...e,loadPage:sw(e)})}async function hB(e){let t=[],n=new Set,r;do{let i=await e({limit:rw,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])o.has(a.info.id)||(o.add(a.info.id),s.push(a));return s}var _B={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},py=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??_B,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??dB,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed||t==="visible"&&this.streamReliable&&this.snapshot.freshness==="fresh"?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof ni;if(!r&&Nr(n))return;if(r||this.update({freshness:wn(n)?"loading":"error"}),n instanceof x&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(gB*2**this.retryAttempt,mB);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?fB:rw,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,s=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",s,{once:!0});let o,i=new Promise((c,p)=>{o=this.startTimer(()=>{let d=new ni(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(o),n.removeEventListener("abort",s)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let i=[...t.messages],a=new Set(this.knownUserMessageIds),c=new Set(s?[s]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<yB&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw o?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,o?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,i=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};var bB=5e3,cw=40,mQ=5*6e4,SB=16,Vr=new Map;function lw(e,t,n,r=Date.now()){let s=uw(e,t);for(Vr.delete(s),Vr.set(s,{envelope:n,atMs:r});Vr.size>SB;){let o=Vr.keys().next().value;if(o===void 0)break;Vr.delete(o)}}var aw=new Map;function uw(e,t){return`${e}/${t}`}function PB(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=bB}function pw(e,t,n=Date.now()){if(!e||!t)return null;let r=uw(e,t),s=aw.get(r);return s?PB(s,n)?s.promise:(aw.delete(r),null):null}function dw(e){let t=e.transcript;if(!t||t.known!==!0||t.requested!==!0)return null;let{known:n,requested:r,...s}=t;if(!s.available)return s;let o=e.session?.runtime_session_id??e.session?.opencode_session_id,i=s.runtime_session_id??s.opencode_session_id;return o&&i===o?s:null}var xB=2e3;async function wB(e,t,n){let r=pw(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??xB,null)})]).finally(()=>clearTimeout(s)):null;return(o&&dw(o))??Yn(e,t,{limit:cw,history:!0,signal:n.signal})}async function gw(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s;try{s=await wB(t,n,{})}catch{return{envelope:null,empty:!1}}if(lw(t,n,s),dy(s)!==r)return{envelope:s,empty:!1};try{let o=await Jn(t,n);return{envelope:s,empty:gy({savedEmptyRoot:r,rootSessionId:r,turnRead:!0,hasEndedTurn:o.last_ended!=null,hasOpenOrQueuedTurn:o.turns.length>0})}}catch{return{envelope:s,empty:!1}}}function dy(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function gy(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function vB(e){throw G("buildTunnelEventStreamUrl")}function AB(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(w,y){o?.(w,y);let _=d.get(w);if(_)for(let R of _)try{R(y)}catch{}}async function S(){if(m)return;let w=new AbortController;g=w,p&&(p.aborted?w.abort():p.addEventListener("abort",()=>w.abort(),{once:!0}));let y=w.signal;try{let _={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(_["Content-Type"]="application/json"),f&&(_["Last-Event-ID"]=f);let R=await fetch(t,{method:r,headers:_,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:y,credentials:"include"});if(!R.ok)throw new Error(`SSE connection failed: ${R.status} ${R.statusText}`);if(!R.body)throw new Error("SSE response has no body");i?.();let v=R.body.getReader(),b=new TextDecoder,P="",O="message",A=[],$=T=>{if(T===""){A.length>0&&h(O,A.join(`
|
|
98
|
+
`)),O="message",A=[];return}if(T.startsWith(":"))return;let q=T.indexOf(":"),W=q===-1?T:T.slice(0,q),H=q===-1?"":T.slice(q+1);H.startsWith(" ")&&(H=H.slice(1)),W==="event"?O=H.trim()||"message":W==="data"?A.push(H):W==="id"&&!H.includes("\0")&&(f=H)},N=T=>{let q="";!T&&P.endsWith("\r")&&(q="\r",P=P.slice(0,-1));let W=P.split(/\r\n|\n|\r/);P=(W.pop()??"")+q;for(let H of W)$(H)};for(;!m;){let{done:T,value:q}=await v.read();if(T)break;P+=b.decode(q,{stream:!0}),N(!1)}m||(P+=b.decode(),N(!0),c?.())}catch(_){if(m||_ instanceof DOMException&&_.name==="AbortError")return;a?.(_ instanceof Error?_:new Error(String(_)))}}function E(){m=!0,g?.abort(),g=null,d.clear()}function L(w,y){let _=d.get(w)??new Set;_.add(y),d.set(w,_)}function D(w,y){d.get(w)?.delete(y)}return{connect:S,close:E,addEventListener:L,removeEventListener:D}}function kB(e,t){throw G("createTunnelEventStream")}var mw="/_beeuni/viewer",ri=6e4,Cn=new Map;function fw(){Cn.clear(),Hr.clear()}async function RB(e,t){let n;try{n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}})}catch{return null}if(n.status===401||n.status===404||!n.ok)return null;let r=await n.json().catch(()=>null);return r&&typeof r.user_id=="string"?r:null}async function my(e={}){let t=e.path??mw,n=e.fetch??((o,i)=>fetch(o,i)),r=Cn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=RB(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-ri:Date.now()+ri;return Cn.set(t,{session:o,expiresAt:a}),o});return Cn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function yw(e={}){let t=e.path??mw;return Object.assign(async()=>(await my(e))?.access_token??null,{invalidate:n=>{let r=Cn.get(t);r&&!r.inflight&&r.session?.access_token===n&&Cn.delete(t)}})}var Hr=new Map;async function CB(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let o=await n.json().catch(()=>null);o?.error==="app_not_linked"&&console.warn(`[beeuni] ${String(o.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let s=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return Hr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-ri:Date.now()+ri}),r.token}catch{return null}}function fy(e={}){let t=e.path??"/_beeuni/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((s,o)=>fetch(s,o));return async(s={})=>{let o=Hr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=CB(n,r).then(a=>(a===null&&Hr.delete(n),a));return Hr.set(n,i),i}}function hw(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("beeuniBinding needs the App origin: pass { origin } outside a browser.");return{url:`${de(n)}/_beeuni/apps/${encodeURIComponent(e)}`,token:fy({audience:e,fetch:t.fetch})}}var bt=class extends Error{code;constructor(t,n){super(n),this.name="BeeuniMemberError",this.code=t}},ve=e=>typeof e=="string"&&e.length>0?e:null;function _w(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function si(e){if(!e||typeof e!="object")return null;let t=e,n=ve(t.sub)??ve(t.subject)??ve(t.user_id)??ve(t.userId);return n?{userId:n,email:ve(t.email),name:ve(t.name),picture:ve(t.picture)??ve(t.pictureUrl),groups:_w(t.groups),groupIds:_w(t.group_ids??t.groupIds),role:ve(t.role),accountId:ve(t.account_id)??ve(t.accountId),projectId:ve(t.project_id)??ve(t.projectId)}:null}function Sw(e,t={}){let n=si(e);if(!n)throw new bt("unauthenticated","Sign in with Beeuni to continue.");let{groups:r,roles:s}=t;if(r&&!r.some(o=>n.groups.includes(o)||n.groupIds.includes(o)))throw new bt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new bt("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var TB=60,yy=new Map;function Pw(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function bw(e){return JSON.parse(new TextDecoder().decode(Pw(e)))}async function EB(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),s=e.slice(n+1),o=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(s),i=>i.charCodeAt(0))):decodeURIComponent(s);return JSON.parse(o)}if(/^https?:\/\//.test(e)){let n=yy.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>yy.delete(e)),yy.set(e,n)),n}return JSON.parse(e)}async function xw(e,t={}){let n=w=>{throw new bt("unauthenticated",`Beeuni sign-in token refused: ${w}.`)},r=t.jwks??ct("BEEUNI_AUTH_JWKS"),s=t.issuer??ct("BEEUNI_AUTH_ISSUER"),o=t.audience??ct("BEEUNI_AUTH_AUDIENCE");if(!r)return n("no key set configured (BEEUNI_AUTH_JWKS)");if(o!==!1&&!o)return n("no audience configured (BEEUNI_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,c,p]=i,d,g;try{d=bw(a),g=bw(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await EB(r,t.fetch??((w,y)=>fetch(w,y)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(w=>w.kty==="EC"&&(d.kid===void 0||w.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${c}`),S;try{S=Pw(p)}catch{return n("malformed")}let E=!1;for(let w of f)try{let{kid:y,alg:_,use:R,key_ops:v,...b}=w,P=await crypto.subtle.importKey("jwk",b,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},P,S,h)){E=!0;break}}catch{}if(!E)return n("bad signature");let L=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+TB<L)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let w=g.aud;if(!(w===o||Array.isArray(w)&&w.includes(o)))return n("wrong audience")}let D=si(g);return D||n("no subject")}function hy(e){let t=e.agents.map(IB),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function IB(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function _y(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Js(n?{...r,mode:null}:r))}function ww(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let o=e.selectedAgent?.trim();return o?{selected:o,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=_y(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(o=>o.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let s=e.defaultAgent?.trim();return s&&n.some(o=>o.name===s)?{selected:s,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var vw=hy;function Aw(e){return e.providerID==="beeuni"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function by(e){return{providerID:"beeuni",modelID:e}}function oi(e,t){let n=e.startsWith("beeuni/")?e.slice(7):e;if(!t){let r=n.indexOf("/");if(r>0&&r<n.length-1)return{providerID:n.slice(0,r),modelID:n.slice(r+1)}}return by(n)}var Sy=[{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"poe",env:["POE_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"infer",env:["INFER_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"bee",env:["BEE_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]}];function Py(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function OB(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"beeuni":e.id.slice(0,t)}function kw(e,t){let n=new Map;for(let r of e){let s=t(r),o=n.get(s);o?o.push(r):n.set(s,[r])}return n}function Se(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function Rw(e){return e.reduce((t,n)=>{let r=Py(n)??0,s=Py(t)??0;return r!==s?r>s?n:t:Se(n.id)>Se(t.id)?n:t})}function xy(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of kw(e,OB)){let a=[...kw(o,p=>p.family||p.id).values()].map(Rw),c=a.filter(p=>{let d=Py(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[Rw(a)])s.add(p.id)}return s}function ii(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>Se(r.id)>0)?n.filter(r=>Se(r.id)>0):n}function zr(e){let t;for(let n of ii(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&Se(n.id)>Se(t.id))&&(t=n)}return t}var DB={"amazon-bedrock":{methods:[{label:"Bearer token",envVars:["AWS_BEARER_TOKEN_BEDROCK","AWS_REGION"]}]},google:{methods:[{envVars:["GOOGLE_GENERATIVE_AI_API_KEY"]},{envVars:["GOOGLE_API_KEY"]},{envVars:["GEMINI_API_KEY"]}]}};function Cw(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var jB=(()=>{let e=new Map;for(let{id:n,env:r}of Sy)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let s=[...r].sort((o,i)=>o.length-i.length||o.localeCompare(i));t.set(n,r.find(o=>Cw(o)===n)??s[0])}return t})();function Tw(e){let t=DB[e.id];if(t)return t;let n=e.env??[],r=n.length===1?jB.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[Cw(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function wy(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var LB=["low","medium","high"];function Ew(e){if(!e)return{temperature:!1,topP:!1};let t=e.reasoning_options?.find(a=>a.type==="effort"),n=e.reasoning_options?.find(a=>a.type==="budget_tokens"),r=t?.values?.length?{values:t.values}:n?{values:[...LB]}:void 0,s=e.temperature===!0,o=e.limit?.output,i=typeof o=="number"&&o>0?{ceiling:o}:void 0;return{reasoningEffort:r,temperature:s,topP:s,maxOutputTokens:i}}var Iw=Sy;var $B=[{id:"gpt-6-astra",name:"GPT-6 Astra",upstreamModelId:"openai/gpt-6-astra",transport:"openrouter",pricingRef:"openrouter/openai/gpt-6-astra",pricing:{inputPerMillion:10,cachedInputPerMillion:1,cacheWritePerMillion:12.5,outputPerMillion:50,contextOver200k:{contextThreshold:272e3,inputPerMillion:20,cachedInputPerMillion:2,cacheWritePerMillion:25,outputPerMillion:75}},tier:"flagship",vision:!0,limit:{context:105e4,output:128e3},openrouterProvider:{order:["openai"],allow_fallbacks:!0}},{id:"gpt-6-sol",name:"GPT-6 Sol",upstreamModelId:"openai/gpt-6-sol",transport:"openrouter",pricingRef:"openrouter/openai/gpt-6-sol",pricing:{inputPerMillion:2.2,cachedInputPerMillion:.22,cacheWritePerMillion:2.75,outputPerMillion:11,contextOver200k:{contextThreshold:272e3,inputPerMillion:4.4,cachedInputPerMillion:.44,cacheWritePerMillion:5.5,outputPerMillion:16.5}},tier:"balanced",vision:!0,limit:{context:105e4,output:128e3},openrouterProvider:{only:["azure/us"],allow_fallbacks:!1,zdr:!0,data_collection:"deny"}}],OQ=new Map($B.map(e=>[e.id,e]));var Mw=["gpt-6-astra","gpt-6-sol"],Ow="gpt-6-astra",Dw="gpt-6-sol";var Lw=Iw.map(e=>({id:e.id,authRequirement:Tw(e)})),Yr=new Set(["beeuni"]),vy=new Set(["beeuni"]);function Tn(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,s=Array.isArray(r)?r:[];return s.length===0?{...e,all:[],connected:[]}:{...e,all:s,connected:s.map(o=>o.id)}}function BB(e){if(!e)return!1;let t=Tn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(s=>r.includes(s.id)&&s.models&&Object.keys(s.models).length>0)}function UB(e){let t=Tn(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(s=>!vy.has(s.id)),connected:r.filter(s=>!vy.has(s))}}function FB(e,t,n){let r=Tn(e),s=Array.isArray(r.all)?r.all:[],o=new Set(s.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)o.has(a.id)&&wy(a.authRequirement,c=>t.has(c))&&i.add(a.id);return o.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var NB=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function qB(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var Ay="opencode";function GB(e){return e.cost?.input===0&&e.cost?.output===0}function jw(e){return e===Ay?Number.MAX_SAFE_INTEGER:NB.get(e)??Number.MAX_SAFE_INTEGER-1}function WB(e,t){let n=VB(t),r={},s=(e.providers??[]).map(o=>{let i=(o.models??[]).filter(a=>a.status!=="deprecated");return o.id===Ay&&!n.has(Ay)?{...o,models:i.filter(GB),keyless:!0}:{...o,models:i,keyless:!1}}).filter(o=>(o.keyless||n.has(o.id))&&!vy.has(o.id)&&(o.models?.length??0)>0).sort((o,i)=>jw(o.id)-jw(i.id)).map(o=>{let i=[...o.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||Se(p.id)-Se(c.id)),a=zr(i)?.id??i[0]?.id;return a&&(r[o.id]=a),{id:o.id,name:o.name,source:o.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=qB(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:s,connected:s.map(o=>o.id),default:r}}function KB(e,t){if(!e)return t;if(!t)return e;let n=Tn(e),r=Tn(t),s=new Map;for(let d of Array.isArray(r.all)?r.all:[])s.set(d.id,d);let o=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])o.push(s.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(o.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=s.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:o,connected:a,default:p}}function VB(e){let t=new Set;for(let n of Lw)wy(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function HB(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="beeuni/auto").map(([r,s])=>{if(s.variants&&Object.keys(s.variants).length>0)return[r,s];let o=Ew({id:r,name:s.name,reasoning:s.reasoning,reasoning_options:s.reasoning_options}).reasoningEffort?.values;return o?.length?[r,{...s,variants:Object.fromEntries(o.map(i=>[i,{}]))}]:[r,s]})),n=Object.keys(t)[0];return{default:n?{beeuni:n}:{},connected:["beeuni"],all:[{id:"beeuni",name:"Beeuni",source:"gateway",models:t}]}}function zB(e,t){return UB(FB(Tn(e),t,Lw))}function $w(e){if(e.gatewayEnabled)return e.modelPicker?HB(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?zB(e.runtimeProviders,t):void 0;return KB(e.llmCatalogProviders?WB(e.llmCatalogProviders,t):void 0,BB(n)?n:void 0)}function YB(e){return"capabilities"in e&&e.capabilities!=null}function ai(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function Bw(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],s=Array.isArray(e.connected)?e.connected:[],o=[];for(let i of r)if(s.includes(i.id)&&!(n==="gateway"?!Yr.has(i.id):Yr.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="beeuni/auto")continue;let p;if(YB(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}o.push({id:Aw({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return o}function Uw(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var JB=new Set([Ow]),QB="beeuni",Fw="codex",XB=new Set(Mw);function ZB(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function En(e){return JB.has(e.modelID)}function eU(e){return xy(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function Nw(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=eU(e.catalogModels),s=Uw(e.catalogModels),o=new Map;for(let i of e.pins??[])o.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,c=o.get(a);if(c==="hide")return!1;if(i.providerID===QB){let d=ZB(i.modelID,i.provider),g=d===Fw?t?.has(Fw)??!1:t?.has(d)??!1;if(XB.has(i.modelID))return!n||i.modelID===Dw;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return En(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return En(i)}catch{return En(i)}return!1}if(c==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return En(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return En(i)}catch{return En(i)}return!1}}function qw(e,t){return t.search.trim().length>0||e.providerID==="beeuni"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function Gw(e,t){if(!e||Yr.has(e.providerID)||Se(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>Se(i.modelID)>0))return e;let r=i=>Se(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,o=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??zr(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!o||o===e.modelID?e:{...e,modelID:o}}function Ww(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?by(n):void 0}function Kw(e){for(let t=(e?.length??0)-1;t>=0;t--){let n=e[t],{provider:r,model:s}=n.model??{};if(n.role==="user"&&r&&s)return{providerID:r,modelID:s}}}var tU=new Set(["explicit","repointed"]);function Vw(e){let t=e.session?er(e.session):null,n=t?oi(t,e.gatewayEnabled):void 0;return(tU.has(String(e.session?.metadata?.opencode_model_source))?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(o=>!!o)}function Hw(e){let{models:t,providers:n}=e,r=c=>ai(t,c),s=c=>c.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=c[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of ii(Object.keys(m.models).map(S=>({id:S})))){let S={providerID:m.id,modelID:h.id};if(r(S))return S}}}})(),i=s(e.picks??[]),a=i??s([e.serverDefault,e.globalDefault,e.agentModel,o]);return{model:Gw(a,t),explicit:i,fallback:o}}return ev(nU);})();
|