@kortix/sdk 0.13.48 → 0.13.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/core/client/kortix.d.ts +5 -0
  2. package/dist/core/client/kortix.d.ts.map +1 -1
  3. package/dist/core/client/project-core.d.ts +1 -0
  4. package/dist/core/client/project-core.d.ts.map +1 -1
  5. package/dist/core/client/session-actions-security.d.ts +2 -0
  6. package/dist/core/client/session-actions-security.d.ts.map +1 -1
  7. package/dist/core/client/session-handle.d.ts +2 -0
  8. package/dist/core/client/session-handle.d.ts.map +1 -1
  9. package/dist/core/http/auth.d.ts +3 -2
  10. package/dist/core/http/auth.d.ts.map +1 -1
  11. package/dist/core/http/auth.js +2 -1
  12. package/dist/core/http/auth.js.map +1 -1
  13. package/dist/core/rest/platform-client/connector-setup.d.ts +91 -0
  14. package/dist/core/rest/platform-client/connector-setup.d.ts.map +1 -0
  15. package/dist/core/rest/platform-client/connector-setup.js +171 -0
  16. package/dist/core/rest/platform-client/connector-setup.js.map +1 -0
  17. package/dist/core/rest/platform-client/host-boundary.d.ts +15 -3
  18. package/dist/core/rest/platform-client/host-boundary.d.ts.map +1 -1
  19. package/dist/core/rest/platform-client/host-boundary.js +19 -30
  20. package/dist/core/rest/platform-client/host-boundary.js.map +1 -1
  21. package/dist/core/rest/platform-client/index.d.ts +1 -0
  22. package/dist/core/rest/platform-client/index.d.ts.map +1 -1
  23. package/dist/core/rest/platform-client/index.js +1 -0
  24. package/dist/core/rest/platform-client/index.js.map +1 -1
  25. package/dist/core/rest/platform-client/lifecycle.d.ts +5 -0
  26. package/dist/core/rest/platform-client/lifecycle.d.ts.map +1 -1
  27. package/dist/core/rest/platform-client/lifecycle.js +6 -25
  28. package/dist/core/rest/platform-client/lifecycle.js.map +1 -1
  29. package/dist/core/rest/platform-client/shared.d.ts +0 -7
  30. package/dist/core/rest/platform-client/shared.d.ts.map +1 -1
  31. package/dist/core/rest/platform-client/shared.js +2 -8
  32. package/dist/core/rest/platform-client/shared.js.map +1 -1
  33. package/dist/core/rest/projects-client/account-secret-resources.d.ts +7 -0
  34. package/dist/core/rest/projects-client/account-secret-resources.d.ts.map +1 -1
  35. package/dist/core/rest/projects-client/account-secret-resources.js.map +1 -1
  36. package/dist/core/rest/projects-client/accounts.d.ts +3 -0
  37. package/dist/core/rest/projects-client/accounts.d.ts.map +1 -1
  38. package/dist/core/rest/projects-client/accounts.js.map +1 -1
  39. package/dist/core/rest/projects-client/billing.d.ts +4 -0
  40. package/dist/core/rest/projects-client/billing.d.ts.map +1 -1
  41. package/dist/core/rest/projects-client/billing.js.map +1 -1
  42. package/dist/core/rest/projects-client/model-defaults.d.ts +2 -2
  43. package/dist/core/rest/projects-client/model-defaults.d.ts.map +1 -1
  44. package/dist/core/rest/projects-client/projects.d.ts +28 -5
  45. package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
  46. package/dist/core/rest/projects-client/projects.js +0 -1
  47. package/dist/core/rest/projects-client/projects.js.map +1 -1
  48. package/dist/core/rest/projects-client/session-sandbox.d.ts +3 -1
  49. package/dist/core/rest/projects-client/session-sandbox.d.ts.map +1 -1
  50. package/dist/core/rest/projects-client/session-sandbox.js.map +1 -1
  51. package/dist/core/rest/projects-client/sessions.d.ts +52 -6
  52. package/dist/core/rest/projects-client/sessions.d.ts.map +1 -1
  53. package/dist/core/rest/projects-client/sessions.js +28 -2
  54. package/dist/core/rest/projects-client/sessions.js.map +1 -1
  55. package/dist/core/runtime/runtime-rest-client.d.ts +5 -0
  56. package/dist/core/runtime/runtime-rest-client.d.ts.map +1 -1
  57. package/dist/core/runtime/runtime-rest-client.js +2 -0
  58. package/dist/core/runtime/runtime-rest-client.js.map +1 -1
  59. package/dist/core/session/presentation.d.ts +10 -2
  60. package/dist/core/session/presentation.d.ts.map +1 -1
  61. package/dist/core/session/presentation.js +13 -4
  62. package/dist/core/session/presentation.js.map +1 -1
  63. package/dist/core/session/wire-message-id.d.ts +6 -7
  64. package/dist/core/session/wire-message-id.d.ts.map +1 -1
  65. package/dist/core/session/wire-message-id.js +6 -7
  66. package/dist/core/session/wire-message-id.js.map +1 -1
  67. package/dist/core/stream/fetch-sse.d.ts +7 -3
  68. package/dist/core/stream/fetch-sse.d.ts.map +1 -1
  69. package/dist/core/stream/fetch-sse.js +10 -11
  70. package/dist/core/stream/fetch-sse.js.map +1 -1
  71. package/dist/kortix.esm.min.js +33 -33
  72. package/dist/kortix.global.js +26 -26
  73. package/dist/react/connector-setup.d.ts +48 -0
  74. package/dist/react/connector-setup.d.ts.map +1 -0
  75. package/dist/react/connector-setup.js +173 -0
  76. package/dist/react/connector-setup.js.map +1 -0
  77. package/dist/react/index.d.ts +2 -0
  78. package/dist/react/index.d.ts.map +1 -1
  79. package/dist/react/index.js +10 -0
  80. package/dist/react/index.js.map +1 -1
  81. package/dist/react/use-admin-accounts.d.ts +7 -4
  82. package/dist/react/use-admin-accounts.d.ts.map +1 -1
  83. package/dist/react/use-admin-accounts.js +7 -4
  84. package/dist/react/use-admin-accounts.js.map +1 -1
  85. package/dist/react/use-opencode-sessions/sessions.d.ts +9 -0
  86. package/dist/react/use-opencode-sessions/sessions.d.ts.map +1 -1
  87. package/dist/react/use-opencode-sessions/sessions.js +34 -0
  88. package/dist/react/use-opencode-sessions/sessions.js.map +1 -1
  89. package/dist/react/use-project-apps.d.ts +2 -2
  90. package/dist/react/use-provider-secrets.d.ts +18 -0
  91. package/dist/react/use-provider-secrets.d.ts.map +1 -1
  92. package/dist/react/use-sandbox-image.d.ts +52 -0
  93. package/dist/react/use-sandbox-image.d.ts.map +1 -0
  94. package/dist/react/use-sandbox-image.js +144 -0
  95. package/dist/react/use-sandbox-image.js.map +1 -0
  96. package/package.json +2 -2
@@ -1,24 +1,24 @@
1
- "use strict";var Kortix=(()=>{var Co=Object.defineProperty;var wb=Object.getOwnPropertyDescriptor;var vb=Object.getOwnPropertyNames;var Ab=Object.prototype.hasOwnProperty;var kb=(e,t)=>{for(var n in t)Co(e,n,{get:t[n],enumerable:!0})},Rb=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vb(t))!Ab.call(e,o)&&o!==n&&Co(e,o,{get:()=>t[o],enumerable:!(r=wb(t,o))||r.enumerable});return e};var Ib=e=>Rb(Co({},"__esModule",{value:!0}),e);var iO={};kb(iO,{ABORT_REASONS:()=>uh,ABORT_REASONS_NOT_YET_EMITTED:()=>FT,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>Ko,ACTIVE_INSTANCE_COOKIE:()=>Fn,ANALYTICS_UNAVAILABLE_CODE:()=>No,ATTACHMENT_PART_REF_PREFIX:()=>Ah,ApiError:()=>b,AuthError:()=>X,BillingError:()=>Ee,CONNECTION_FAULT_GRACE_MS:()=>Oh,CONTEXT_TOOLS:()=>yy,COST_MARKUP:()=>jd,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>hy,DEFAULT_TRANSCRIPT_OPTIONS:()=>id,DESTRUCTIVE_PHASES:()=>Ph,FEATURE_DISABLED_CODE:()=>Qn,FEATURE_FLAG_KEYS:()=>o_,FEATURE_NOT_SUPPORTED_CODE:()=>Uo,FILE_VERBS:()=>Ne,FileExistsError:()=>wt,HeadlessAuthError:()=>mt,HostBoundaryError:()=>Te,IMPERSONATION_HEADER:()=>hg,INBOX_OBSERVATION_MAX_MS:()=>xo,INITIAL_SETTLED_CONNECTION:()=>$E,INSTANCE_SCOPED_ROUTES:()=>ph,KORTIX_TRANSCRIPT_SCHEMA:()=>ZS,MAX_PROMPT_ATTACHMENTS_BYTES:()=>H_,MAX_PROMPT_ATTACHMENT_BYTES:()=>Ia,MAX_PROMPT_ATTACHMENT_FILES:()=>Mg,MEMORY_VERBS:()=>XI,MODEL_NOT_SERVABLE_CODE:()=>Lo,NO_GROUP_ACTIVITY_TOOLS:()=>rm,OPTIMISTIC_ABORT_MAX_MS:()=>So,OPTIMISTIC_COMPACTION_MAX_MS:()=>YE,OPTIMISTIC_RECEIPT_MAX_MS:()=>_o,PERSISTED_QUERY_CACHE_VERSION:()=>NK,PLUMBING_TOOLS:()=>Oy,PREVIEW_PROBE_TIMEOUT_MS:()=>IE,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>cP,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>aP,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>Lg,PROVISION_IN_FLIGHT_CODE:()=>Fo,PublicSessionShareError:()=>_r,RUNTIME_NOT_READY_MARKERS:()=>XT,RUNTIME_PERMISSION_CAPABILITIES:()=>nw,RUNTIME_PERMISSION_REPLIES:()=>tw,RequestTooLargeError:()=>qe,RuntimeNotReadyError:()=>xt,SANDBOX_FS_ROOTS:()=>Qr,SANDBOX_PORTS:()=>ve,SERVER_COMPACTION_REVALIDATE_MS:()=>Uh,SERVER_OBSERVATION_MAX_MS:()=>Po,SESSION_LIST_STATUS:()=>lM,SESSION_NOTICE:()=>dM,STANDALONE_TOOLS:()=>om,STREAM_OBSERVATION_MAX_MS:()=>$t,SandboxNotReadyError:()=>Nn,SessionNotReadyError:()=>Ye,SessionStartError:()=>mr,TURN_END_LEDGER_LAG_MS:()=>qE,TURN_ERROR_CODES:()=>$m,WAKE_ESCALATION_COOLDOWN_MS:()=>tM,WAKE_MAX_RESTARTS:()=>eM,WAKE_NO_PROGRESS_MS:()=>ZE,WIRE_ID_BACKDATE_MS:()=>Nr,WIRE_ID_CLOCK_TOLERANCE:()=>De,WIRE_ID_TIME_MASK:()=>Ae,WIRE_ID_TIME_SCALE:()=>bt,WIRE_MESSAGE_ID:()=>Cm,__getConfigResolver:()=>Eb,__setConfigResolver:()=>Cb,abortErrorReason:()=>NT,acceptAccountInvite:()=>gs,acceptInvite:()=>bC,actReviewItem:()=>fu,activateConnection:()=>Ki,addComputerToProject:()=>Bi,addGroupMembers:()=>Gl,addMarketplaceSource:()=>Ju,advanceWakeEscalation:()=>oM,allDescendantIds:()=>Ty,appendPreviewToken:()=>Wd,approveProjectAccessRequest:()=>Bs,approveTask:()=>dw,archiveProject:()=>zt,assignTicket:()=>Pw,attachGroupToProject:()=>ei,authMfa:()=>Ur,authUser:()=>jr,authenticatedFetch:()=>j,authorizePreviewUrl:()=>RE,backendApi:()=>c,bindSlackIdentity:()=>OP,bindTeamsIdentity:()=>jP,brokerProjectSecretRequest:()=>di,browserKeyValueStorage:()=>_E,buildInstancePath:()=>gh,buildPresentationTemplateImageUrl:()=>EE,buildPresentationTemplatePdfUrl:()=>CE,buildPreviewAuthEndpoint:()=>Bd,buildPublicTemplateUrl:()=>Sh,buildRuntimePresentationConversionUrl:()=>Mh,buildSandboxTemplate:()=>Sa,buildScrapeFailureResults:()=>$y,buildStaticFileHealthPreviewUrl:()=>uA,buildStaticFileLocalUrl:()=>lA,buildStaticFilePreviewUrl:()=>cA,buildStaticFileServicePath:()=>hf,buildTunnelEventStreamUrl:()=>zh,buildWebProxyUrl:()=>fA,bulkActReviewItems:()=>yu,bulkDeletePolicies:()=>nx,bulkImportPolicies:()=>rx,burstSummary:()=>hR,burstSummaryLabel:()=>bR,callConnector:()=>Mi,cancelAccountDeletion:()=>qx,cancelAccountInvite:()=>ls,cancelSandbox:()=>dC,cancelSandboxUpdate:()=>MC,cancelScheduledChange:()=>Yc,cancelSubscription:()=>Hc,checkAccessEmail:()=>WC,childMapByParent:()=>oR,claimComputer:()=>UC,claimNext:()=>Kf,claimPerSeatBilling:()=>IP,claimWarmProjectSession:()=>nc,classifyPart:()=>Pd,classifyPreviewProbeStatus:()=>Eh,classifyPtyClose:()=>Fm,classifyTurn:()=>wy,cleanErrorMessage:()=>dR,cleanResultSnippet:()=>SR,cleanWorkerOutput:()=>WI,clearImpersonationSession:()=>Wo,clearKortixAppViewerCache:()=>Xh,clearModelDefault:()=>Ec,clearSessionFresh:()=>sP,closeChangeRequest:()=>qa,closeMilestone:()=>zw,collectTurnParts:()=>eR,commentTicket:()=>Sw,commitSessionChanges:()=>Wa,compactionExpiryAtMs:()=>XE,compactionTurnInfo:()=>_R,compareMessagesForDisplay:()=>Yk,completeInFlight:()=>qf,completeSlackInstall:()=>al,completeTeamsInstall:()=>cl,composerSelectableAgents:()=>eg,computeStatusFromPart:()=>Od,configureAutoTopup:()=>Zc,configureKortix:()=>Hn,confirmCheckoutSession:()=>Bc,connectEmail:()=>yl,connectSlack:()=>sl,connectionFromHealth:()=>DE,connectionIsFaulted:()=>jE,connectionSharedWithEveryone:()=>R_,connectorConnect:()=>Cg,connectorFinalize:()=>Eg,contextLabelForTool:()=>ER,contextToolSummary:()=>JA,contextToolTrigger:()=>ZA,convertPresentationToGoogleSlides:()=>Zx,convertRuntimePresentation:()=>ME,copyFile:()=>wn,costExportUrl:()=>tl,countLiveInboxPrompts:()=>BE,countReviewItemsBySegment:()=>tS,createAccount:()=>Jo,createAccountAuditWebhook:()=>Ku,createAccountSecretResource:()=>xi,createAccountToken:()=>Tu,createApp:()=>tp,createAppAccessSession:()=>cp,createAppDeployment:()=>up,createArtifactKind:()=>ZR,createAssignment:()=>lu,createAuditWebhook:()=>Ox,createBackup:()=>xC,createCheckoutSession:()=>Gc,createConnector:()=>oa,createFile:()=>Sn,createGatewayKey:()=>jl,createGroup:()=>Fl,createHttpSessionSyncController:()=>Bh,createInstance:()=>jC,createKortix:()=>Uf,createKortixPty:()=>Gp,createKortixSession:()=>Fr,createMarketplaceInstallSession:()=>yS,createMilestone:()=>Hw,createModelVisibility:()=>hb,createOAuthClient:()=>ou,createPerSeatCheckout:()=>RP,createPersistedQueryCache:()=>bE,createPolicy:()=>ZP,createPortalSession:()=>Wc,createProject:()=>ws,createProjectAgent:()=>Mw,createProjectCliToken:()=>ju,createProjectRepo:()=>vs,createProjectResourceGrant:()=>oi,createProjectSession:()=>He,createProjectTrigger:()=>wc,createPromptAttachmentController:()=>sd,createRole:()=>Ql,createSSEStream:()=>Yh,createSandbox:()=>sC,createSandboxShare:()=>xu,createSandboxTemplate:()=>_a,createSavedCopyStore:()=>MM,createScimToken:()=>ax,createServiceAccountApi:()=>Tx,createSessionPrompt:()=>rn,createSessionPublicShare:()=>Za,createSessionQueue:()=>Ff,createSessionReminder:()=>vu,createSsoGroupMapping:()=>Px,createTask:()=>lw,createTicket:()=>hw,createTunnelEventStream:()=>DM,currentSavedCopyStore:()=>jM,declineAccountInvite:()=>ms,declineInvite:()=>_C,deleteAccountImmediately:()=>Gx,deleteAccountSecretResource:()=>wi,deleteApp:()=>op,deleteAppDeployment:()=>yp,deleteAuditWebhook:()=>Dx,deleteBackup:()=>wC,deleteConnector:()=>ia,deleteCredential:()=>tv,deleteEnv:()=>Np,deleteFile:()=>et,deleteGatewayBudget:()=>Ml,deleteGitHubInstallation:()=>Ns,deleteGroup:()=>Kl,deleteInstance:()=>DC,deleteKortixProject:()=>Kw,deleteMilestone:()=>Qw,deleteOAuthClient:()=>au,deletePersonalProjectSecret:()=>bi,deletePolicy:()=>tx,deleteProjectAgent:()=>jw,deleteProjectProviderOAuth:()=>mi,deleteProjectResourceGrant:()=>si,deleteProjectSecret:()=>yi,deleteProjectSession:()=>gc,deleteProjectTrigger:()=>Ac,deletePromptAttachment:()=>ut,deleteRole:()=>Zl,deleteSandboxTemplate:()=>xa,deleteServiceAccountApi:()=>Ex,deleteSessionPrompt:()=>cc,deleteSessionReminder:()=>ku,deleteSsoGroupMapping:()=>xx,deleteSsoProvider:()=>bx,deleteTask:()=>gw,deleteTicket:()=>ww,describeAccountInvite:()=>ds,describeConnectorTool:()=>Ei,detachGroupFromProject:()=>ni,detectLocalhostUrls:()=>gf,directSubsessions:()=>mM,disableServiceAccountApi:()=>Cx,disconnectEmail:()=>hl,disconnectGitHubApp:()=>fE,disconnectSlack:()=>ul,discoverConnectionOAuth2:()=>E_,discoverConnectionOAuth2Resource:()=>M_,discoverConnectorAuth:()=>sa,discoverLocalSandbox:()=>lC,downloadAccountAudit:()=>aE,dropClientForUrl:()=>pv,dropPublicClientForUrl:()=>mv,editQueued:()=>Hf,editSessionPrompt:()=>lc,enqueue:()=>Nf,ensurePmSession:()=>Cw,ensurePreviewSessionCookie:()=>Ch,ensureProjectConnectorConnection:()=>I_,ensureSandbox:()=>_h,ensureWarmProjectSession:()=>tc,env:()=>Um,exchangeCode:()=>Er,exportAccountAudit:()=>Fu,extractGatewayErrorDetails:()=>ue,extractInstanceRoute:()=>jt,extractSkillBaseDir:()=>oh,extractSkillContent:()=>sT,extractSkillFiles:()=>rh,extractWorkerPreview:()=>VI,failInFlight:()=>Gf,fallbackBusyRowAfterTurnId:()=>vI,familyForTool:()=>go,featureDisabledKey:()=>jo,featureFlags:()=>Ip,fetchAccountStateWithToken:()=>AP,fetchAccountsWithToken:()=>r_,fetchAttachmentPart:()=>PE,fetchCostExportCsv:()=>MP,fetchKortixAppViewer:()=>Jd,fetchProjectArchive:()=>Ra,fetchProjectsForAccountWithToken:()=>g_,fetchSessionAttachment:()=>kp,filePhase:()=>QI,fileVerb:()=>YI,files:()=>nf,finalizeAppArtifact:()=>xr,finalizeConnectorSetupLink:()=>JC,findActiveTranscriptShare:()=>lP,findFiles:()=>Pn,findLastTextPart:()=>tR,findSessionAttachments:()=>DS,findText:()=>xn,fireProjectTrigger:()=>Rc,fixSandboxWithAgent:()=>ba,flattenModels:()=>mb,flattenThought:()=>aI,formatBillingErrorForUI:()=>$o,formatCost:()=>NI,formatDuration:()=>UI,formatJsonFailureOutput:()=>gR,formatMessageDay:()=>gI,formatMessageExact:()=>mI,formatOpenCodeRuntimeError:()=>tC,formatRawOutput:()=>xR,formatRuntimeError:()=>bh,formatTokens:()=>KI,formatTranscript:()=>zf,freshSendHint:()=>RI,generateSessionId:()=>Lf,getAccount:()=>Zo,getAccountBranding:()=>ts,getAccountDeletionStatus:()=>Nx,getAccountState:()=>$c,getAccountStateMinimal:()=>Uc,getActiveInstanceIdFromCookie:()=>fh,getAdminProviderAnalytics:()=>zx,getAdminProviderDistribution:()=>Wx,getAdminProviderFallback:()=>Qx,getAdminRole:()=>Bx,getAgentCardLabel:()=>xy,getAgentConfig:()=>PP,getAgentPersona:()=>Dw,getAllVersions:()=>TC,getAnsweredQuestionParts:()=>rR,getApp:()=>np,getAppAccess:()=>sp,getAppDeployment:()=>dp,getAppDeploymentLogs:()=>gp,getApprovalLink:()=>fS,getAuthToken:()=>lt,getAuthTokenWithRetry:()=>w_,getAutoTopupSettings:()=>Jc,getAutoTopupSetupStatus:()=>kP,getBillingCreditBreakdown:()=>Nc,getBillingTierConfigurations:()=>qc,getBillingTransactionsSummary:()=>Fc,getBillingUsageHistory:()=>Kc,getChangeRequest:()=>Ua,getChangeRequestDiff:()=>La,getChangeRequestMergePreview:()=>Fa,getChildSessionError:()=>gk,getChildSessionId:()=>yd,getChildSessionToolParts:()=>mk,getClient:()=>Ue,getClientForUrl:()=>fe,getConnectStatus:()=>ua,getConnectionOAuth2Application:()=>C_,getConnectionOAuth2Status:()=>U_,getConnectionPolicies:()=>L_,getConnectorCatalog:()=>Qt,getConnectorConfig:()=>ta,getConnectorPolicies:()=>Zi,getConnectorSetupLink:()=>QC,getCostSummary:()=>EP,getCurrentInstanceIdFromPathname:()=>mh,getCurrentInstanceIdFromWindow:()=>GT,getCurrentProject:()=>Xp,getDefaultAccountState:()=>Dc,getDiagnostics:()=>bk,getDirectory:()=>Py,getDiscoverConnector:()=>ur,getDiscoverIntegration:()=>B_,getEmailInstallation:()=>ml,getEmailMode:()=>fl,getEnterpriseDemo:()=>Ux,getFileStatus:()=>_n,getFileWithDir:()=>md,getFilename:()=>_y,getFullChangelog:()=>xh,getGatewayBreakdown:()=>Rl,getGatewayBudgets:()=>Cl,getGatewayErrors:()=>Tl,getGatewayKeys:()=>Ol,getGatewayLog:()=>vl,getGatewayOverview:()=>Al,getGatewayRoutingPolicy:()=>_l,getGatewaySeries:()=>kl,getGatewaySessions:()=>Il,getGitHubAppStatus:()=>pE,getGitHubInstallation:()=>Ms,getGoogleAuthUrl:()=>Jx,getGroup:()=>Ll,getHiddenToolParts:()=>ck,getImpersonationSession:()=>Pg,getInvite:()=>hC,getJustavpsServerTypes:()=>OC,getKortixProject:()=>Lw,getKortixProjectBySession:()=>Fw,getKortixPtyWebSocketUrl:()=>Hp,getLatestSandboxVersion:()=>IC,getMaintenanceConfig:()=>rE,getManagedGitBackend:()=>Ks,getManagedGitStatus:()=>l_,getMarketplaceCatalogItem:()=>Yu,getMarketplaceCatalogItemFile:()=>Qu,getMfaRequired:()=>lx,getMilestone:()=>Bw,getModelDefaults:()=>Tc,getOAuthClient:()=>ru,getOAuthConsentRequest:()=>zC,getOpenCodeConfigInvalidError:()=>zT,getPartText:()=>sk,getPatPolicy:()=>kx,getPermissionForTool:()=>_k,getProject:()=>Gt,getProjectActivity:()=>$w,getProjectCommit:()=>Ma,getProjectCommitDiff:()=>Oa,getProjectDetail:()=>Bt,getProjectFileHistory:()=>ja,getProjectGitToken:()=>Ss,getProjectLlmCatalog:()=>Wt,getProjectLlmCatalogProviders:()=>i_,getProjectModelAccess:()=>ln,getProjectModelPicker:()=>Ht,getProjectSandboxHealth:()=>Xt,getProjectSandboxProviderTransition:()=>u_,getProjectSession:()=>nn,getProjectSessionConfigState:()=>mc,getProjectSessionScope:()=>hc,getProrationPreview:()=>Qc,getProviders:()=>rC,getProxyBaseUrl:()=>pA,getPublicClientForUrl:()=>gv,getPublicMarketplaceItem:()=>GC,getPublicMarketplaceItemFile:()=>BC,getPublicSessionShare:()=>gS,getPublicSessionShareMessages:()=>mS,getPublicShareByToken:()=>tE,getPublicTemplate:()=>uE,getQuestionForTool:()=>Pk,getReferralCode:()=>qP,getReferralStats:()=>WP,getRetryInfo:()=>qI,getRetryMessage:()=>GI,getReviewItem:()=>gu,getRolePermissions:()=>zl,getRoleUsage:()=>Yl,getRuntimeConfigInvalidError:()=>yo,getSSHConnection:()=>AC,getSandbox:()=>oC,getSandboxById:()=>iC,getSandboxPortUrl:()=>nC,getSandboxProvisionStatus:()=>LC,getSandboxProvisionStreamUrl:()=>FC,getSandboxUpdateStatus:()=>RC,getSandboxUrl:()=>Nd,getSecretSetupLink:()=>ZC,getServerHealth:()=>Xr,getServiceLogs:()=>iv,getSessionAudit:()=>rc,getSessionCost:()=>FI,getSessionCostRecord:()=>cn,getSessionHealth:()=>td,getSessionMessageAuthors:()=>xc,getSessionOpenBundle:()=>uP,getSessionOversight:()=>dx,getSessionParticipants:()=>Qa,getSessionPolicy:()=>Sx,getSessionPreviewCandidates:()=>Xa,getSessionProviderSecretPool:()=>Ri,getSessionTranscript:()=>oc,getSessionTranscriptSync:()=>sc,getSessionTurn:()=>ic,getShellModePart:()=>TI,getSlackChannelFile:()=>pl,getSlackInstallation:()=>ol,getSlackManifest:()=>ll,getSlackMode:()=>il,getSsoProvider:()=>mx,getStaticFileHealthPath:()=>bf,getSupabaseAccessToken:()=>sr,getSupabaseAccessTokenWithRetry:()=>ct,getTask:()=>iw,getTaskStatus:()=>cw,getTemplate:()=>hS,getTicket:()=>fw,getToolInfo:()=>fk,getToolPrimaryArg:()=>ro,getTranscriptFilename:()=>Yf,getTurnCost:()=>LI,getTurnError:()=>OI,getTurnErrorDetails:()=>DI,getTurnErrorRawText:()=>jI,getTurnStatus:()=>$I,getUsageRollup:()=>el,getUserRolesWithToken:()=>sE,getVersionDiff:()=>Da,getWorkingState:()=>EI,grantAccountSecretResource:()=>vi,grantSandboxProjectAccess:()=>fC,grantSecretToAgent:()=>SP,groupMessagesIntoTurns:()=>Xk,groupShowSegments:()=>hI,groupSteps:()=>Ed,hasDiffs:()=>BI,hasLocalhostUrls:()=>sA,hasPreviewTarget:()=>yf,hasRetryingAssistantTurn:()=>iR,heartbeatGapEvent:()=>Bm,holdSessionPrompts:()=>pc,humanizeReviewActionPath:()=>_u,humanizeSearchQuery:()=>In,humanizeToolName:()=>bd,impersonationHeaders:()=>Ho,importSsoProviderFromMetadata:()=>yx,inboxObservationSupersedes:()=>GE,initialWakeEscalationState:()=>zd,inputPath:()=>Re,installTemplate:()=>bS,invalidateTokenCache:()=>ir,inviteAccountMember:()=>as,inviteProjectMember:()=>Ys,inviteRepoCollaborator:()=>Ps,isAbortError:()=>Ln,isAdminBypassEnabled:()=>vg,isAgentPart:()=>ek,isAppRouteUrl:()=>df,isAttachment:()=>ik,isAttachmentPartRef:()=>kh,isBillingError:()=>Do,isCompactionPart:()=>tk,isConfigured:()=>Vn,isContextTool:()=>XA,isDestructivePhase:()=>kC,isEmptyConversation:()=>Vh,isEmptyShowPart:()=>Sr,isErrorOutput:()=>aR,isExternalUrl:()=>bA,isFeatureDisabledError:()=>Oo,isFilePart:()=>fd,isImpersonationSessionLive:()=>bg,isInstanceDetailPath:()=>KT,isInstanceScopedAppPath:()=>dh,isInternalLocalhostUrl:()=>mA,isInvisibleActivityPart:()=>Pp,isInviteSent:()=>y_,isLastUserMessage:()=>CI,isLegacyMigratedSession:()=>Lh,isManagedGithubProject:()=>s_,isNoGroupActivityTool:()=>_p,isOfferedModel:()=>Io,isOpenCodeConfigInvalidError:()=>YT,isPaintableSavedCopy:()=>Qd,isPatchPart:()=>rk,isPersistableQueryKey:()=>hE,isPreviewUrl:()=>gA,isProxiableLocalhostUrl:()=>_f,isQuestionTool:()=>vS,isReasoningPart:()=>he,isRetryableTurnError:()=>Cy,isRuntimeConfigInvalidError:()=>yh,isRuntimeNotReadyResponse:()=>hh,isRuntimeReady:()=>ed,isRuntimeStartingError:()=>eC,isSandboxNotReadyError:()=>Dt,isSelectableAgent:()=>Ar,isServerReachable:()=>Jp,isSessionAttachmentRef:()=>TS,isSessionFresh:()=>Va,isSessionStartError:()=>fP,isShellActivityTool:()=>wS,isShellMode:()=>Qy,isShortOutput:()=>HI,isShowContentUnavailable:()=>xS,isShowPayloadEmpty:()=>pn,isSnapshotPart:()=>nk,isStandaloneActivityTool:()=>xp,isStepPart:()=>ok,isSubdomainPreviewUrl:()=>qn,isTextPart:()=>ye,isToolPart:()=>Y,isToolPartHidden:()=>lk,isTurnErrorCode:()=>ew,isUnderSandboxRoot:()=>Yp,isWebProxyUrl:()=>hA,isWireIdAheadOf:()=>Mm,kortixAppViewerToken:()=>Jh,kortixPty:()=>qm,leaveAccount:()=>hs,linkGitHubInstallation:()=>Ls,linkRepository:()=>Cs,listAccountAudit:()=>Uu,listAccountAuditWebhooks:()=>Nu,listAccountInvites:()=>cs,listAccountMembers:()=>is,listAccountResourceGrants:()=>XP,listAccountSecretResources:()=>Pi,listAccountSessions:()=>vx,listAccountTokens:()=>Iu,listAccounts:()=>Xo,listActions:()=>ox,listAdminSandboxes:()=>Hx,listAgentIdentities:()=>Hl,listAllConnections:()=>$i,listAppAgents:()=>ip,listAppDeployments:()=>pp,listApps:()=>ep,listAssignments:()=>cu,listAuditEvents:()=>$x,listAuditWebhooks:()=>Mx,listBackups:()=>PC,listBillingTransactions:()=>Lc,listChangeRequests:()=>$a,listChannelBindings:()=>FP,listColumns:()=>vw,listConnectSections:()=>q_,listConnectToolkits:()=>K_,listConnections:()=>Di,listConnectorAccounts:()=>Oi,listConnectorTools:()=>cr,listConnectors:()=>zi,listCostByProject:()=>CP,listCredentialEvents:()=>Jw,listCredentials:()=>Xw,listDiscoverConnectors:()=>lr,listDiscoverIntegrations:()=>G_,listDiscoverSections:()=>la,listEnv:()=>Lp,listFeaturedMarketplaces:()=>zu,listFields:()=>kw,listFiles:()=>kt,listGatewayLogs:()=>wl,listGitHubInstallations:()=>Os,listGitHubRepositories:()=>Ds,listGitHubRepositoryBranches:()=>$s,listGroupMembers:()=>ql,listGroupProjectGrants:()=>zP,listGroups:()=>Ul,listKortixProjectSessions:()=>Nw,listKortixProjects:()=>Uw,listKortixPty:()=>qp,listLinkableGitHubInstallations:()=>js,listManagedGitRepositories:()=>qs,listMarketplaceCatalogItems:()=>Hu,listMarketplaceSources:()=>Xu,listMarketplaces:()=>Vu,listMemberGroups:()=>YP,listMemberProjectAccess:()=>QP,listMilestoneEvents:()=>Ww,listMilestones:()=>Gw,listMyAccountInvites:()=>ps,listOAuthClients:()=>nu,listOAuthGrants:()=>Eu,listPendingApprovals:()=>ii,listPendingProjectInvites:()=>Qs,listPermissions:()=>pu,listPipedreamApps:()=>aa,listPipedreamSections:()=>ca,listPolicies:()=>JP,listProjectAccess:()=>Hs,listProjectAccessRequests:()=>Gs,listProjectAgentIdentities:()=>Vl,listProjectAgents:()=>Ew,listProjectAudit:()=>Lu,listProjectBranches:()=>Ca,listProjectCliTokens:()=>Ou,listProjectCommits:()=>Ea,listProjectFiles:()=>va,listProjectGroupGrants:()=>Zs,listProjectPolicies:()=>ga,listProjectProviderOAuth:()=>gi,listProjectReminders:()=>Ru,listProjectResourceGrants:()=>ri,listProjectSandboxTemplates:()=>fa,listProjectSandboxes:()=>wa,listProjectSecrets:()=>li,listProjectSessions:()=>We,listProjectSessionsPage:()=>za,listProjectSnapshots:()=>ya,listProjectTriggers:()=>Sc,listProjects:()=>Be,listProjectsForAccount:()=>_s,listPublicMarketplaceItems:()=>KC,listPublicMarketplaces:()=>qC,listReferrals:()=>HP,listReviewItems:()=>du,listRoles:()=>Wl,listSandboxProjectMembers:()=>mC,listSandboxShares:()=>Pu,listSandboxes:()=>cC,listScimTokens:()=>ix,listServiceAccountsApi:()=>Ix,listServiceTemplates:()=>sv,listServices:()=>ov,listSessionConnectRequests:()=>N_,listSessionCosts:()=>rl,listSessionPrompts:()=>ac,listSessionProviderSecretPools:()=>Ii,listSessionPublicShares:()=>Ja,listSessionReminders:()=>wu,listSessionsNeedingInput:()=>ai,listSsoGroupMappings:()=>_x,listTaskEvents:()=>aw,listTasks:()=>sw,listTemplates:()=>Iw,listTicketEvents:()=>yw,listTickets:()=>mw,loadHttpSessionHistory:()=>Gh,looksLikeError:()=>wd,looksLikeHtml:()=>kR,looksLikeJsonPayload:()=>PR,mapApiReviewItem:()=>dS,markInstanceError:()=>$C,markSessionFresh:()=>tn,maxWireIdClock:()=>jp,memoryRelPath:()=>JI,mergeBurstSteps:()=>oI,mergeChangeRequest:()=>Ka,messageCreatedAt:()=>cI,messageTime:()=>Vy,migrateAdminSandboxProvider:()=>Yx,mintWireMessageId:()=>Kr,mintWireMessageIdAbove:()=>Dp,mkdir:()=>Ct,modelInDefaultView:()=>bb,modelRefToKey:()=>nb,narrateFailedStep:()=>Cd,narrateStep:()=>Td,narrationToolName:()=>$n,narrowChatEvent:()=>Wm,newestWireIdClock:()=>Om,normalizeActivityToolName:()=>ae,normalizeAppPathname:()=>HT,normalizeExternalInput:()=>_A,normalizeName:()=>W,normalizeToolName:()=>hd,notifyHostSignal:()=>Nh,openChangeRequest:()=>Na,openEventStream:()=>Vr,openStressTestStream:()=>cE,parseBillingError:()=>Kt,parseEmbeddedFailure:()=>wR,parseFlagOverride:()=>US,parseJsonFailure:()=>My,parseLocalhostUrl:()=>Rn,parseMemoryView:()=>ZI,parseOpenCodeErrorPayload:()=>VT,parsePresentationOutput:()=>nT,parseProxyHop:()=>Zp,parseQuestionAnswersFromOutput:()=>rT,parseReadOutput:()=>oT,parseRuntimeErrorPayload:()=>Fd,parseScrapeInputUrls:()=>Dy,parseScrapeOutput:()=>Uy,parseSubdomainUrl:()=>rd,parseTaskRows:()=>zI,parseWebProxyUrl:()=>yA,parseWebSearchOutput:()=>Rd,partOutcome:()=>vd,patchKortixProject:()=>qw,patchVerb:()=>tT,pickerProviderList:()=>gb,pipedreamConnect:()=>ra,pipedreamConnectConnection:()=>Hi,pipedreamFinalize:()=>da,pipedreamFinalizeConnection:()=>Vi,platformConfig:()=>k,pollConnectionOAuth2DeviceAuthorization:()=>$_,pollProjectProviderOAuth:()=>or,previewGatewayRoute:()=>Sl,previewMfaRequired:()=>ux,previewSlackIdentity:()=>DP,previewTeamsIdentity:()=>$P,probeEffectivePermission:()=>eu,probeEffectivePermissions:()=>tu,probePreviewPort:()=>TE,projectCompacting:()=>QE,projectConfigAgentsToOpenCodeAgents:()=>eb,projectConfigAgentsToRuntimeAgents:()=>Zd,projectSessionConnection:()=>OE,projectSessionForRuntimeId:()=>fM,projectSessionStartSeed:()=>mP,projectWorking:()=>WE,provisionProject:()=>As,provisionProjectStream:()=>c_,provisionProjectWithToken:()=>m_,proxyLocalhostUrl:()=>nd,proxyUrlToInternal:()=>dA,purchaseCredits:()=>Xc,putConnectionOAuth2Application:()=>T_,rawErrorText:()=>ld,reactivateSandbox:()=>gC,reactivateSubscription:()=>Vc,readBlob:()=>It,readFile:()=>Rt,readProjectFile:()=>ka,reasoningIsRunning:()=>qy,rebuildProjectSnapshot:()=>ha,reconcileConnection:()=>Ui,reconcileMemberConnection:()=>Li,reconcileServices:()=>cv,recordPlatformLogout:()=>VC,recoverLinkResults:()=>lo,refreshReferralCode:()=>GP,refreshSession:()=>ft,registerAppArtifact:()=>Pr,registerConnectionOAuth2Client:()=>O_,registerService:()=>lv,rejectProjectAccessRequest:()=>Ws,relativizePath:()=>hk,reloadProjectSessionConfig:()=>fc,reloadProjectSessionConfigStream:()=>yc,removeAccountAuditWebhook:()=>Gu,removeAccountBrandingAsset:()=>os,removeAccountMember:()=>fs,removeGroupMember:()=>Bl,removeKortixPty:()=>Wp,removeMarketplaceSource:()=>Zu,removeQueued:()=>Wf,renameConnection:()=>Gi,renameFile:()=>An,renameSandbox:()=>aC,reopenChangeRequest:()=>Ga,reopenMilestone:()=>Yw,reorderQueued:()=>Vf,replaceColumns:()=>Aw,replaceFields:()=>Rw,replaceProjectRepository:()=>Es,replaceTemplates:()=>Tw,requestAccountDeletion:()=>Kx,requestChangesOnChangeRequest:()=>Ba,requestProjectAccess:()=>f_,requestProjectConnector:()=>Wu,requestProjectSecret:()=>Bu,resendAccountInvite:()=>us,resendPendingProjectInvite:()=>Js,resetAccountBranding:()=>ss,resetClient:()=>dv,resetGatewayRoutingPolicy:()=>xl,resetPassword:()=>Mr,resetPublicClient:()=>fv,resetSandboxUpdateStatus:()=>EC,resolveApproval:()=>ci,resolveComposerAgent:()=>Zh,resolveComposerModel:()=>xb,resolveModelDefault:()=>Pb,resolveScrapeResults:()=>RR,resolveWorkingTurn:()=>II,resolvedPlan:()=>vP,restartProjectSession:()=>on,restartSandbox:()=>uC,restoreBackup:()=>SC,retryFailed:()=>Bf,retrySessionPrompt:()=>uc,revealCredential:()=>ev,reviewItemTarget:()=>eS,reviewSegmentForStatus:()=>Zg,reviewVerdictForStatus:()=>nS,revokeAccountSecretResourceGrant:()=>Ai,revokeAccountSession:()=>Ax,revokeAccountToken:()=>Cu,revokeAssignment:()=>uu,revokeConnection:()=>Ni,revokeGatewayKey:()=>Dl,revokeOAuthGrant:()=>Mu,revokePendingProjectInvite:()=>Xs,revokeProjectAccess:()=>zs,revokeProjectCliToken:()=>Du,revokeSandboxProjectAccess:()=>yC,revokeSandboxShare:()=>Su,revokeScimToken:()=>cx,revokeSessionPublicShare:()=>ec,rewriteLocalhostUrl:()=>Fe,rollbackApp:()=>hp,rootRuntimeSession:()=>Fh,rotateAccountSecretResource:()=>Si,rotateOAuthClientSecret:()=>iu,runGatewayPlayground:()=>$l,runProjectProviderOAuthFlow:()=>P_,runtimeSessionsOf:()=>wo,runtimeSupports:()=>af,sanitizePtyChunk:()=>Km,saveGitHubInstallation:()=>Us,savedCopyEmptyRoot:()=>Hh,scheduleDowngrade:()=>zc,searchConnectorTools:()=>Ci,searchProjectFiles:()=>Aa,segmentTurn:()=>fI,selectableProjectAgents:()=>FS,sendMagicLink:()=>Ir,sendReferralEmails:()=>VP,serverCompactionRevalidateAtMs:()=>JE,serviceAction:()=>av,sessionConnectionLabel:()=>pM,sessionListStatus:()=>uM,sessionModelPin:()=>Pc,sessionParentId:()=>iP,sessionStartKey:()=>hP,setAccountSecretResourceAccess:()=>ki,setActiveInstanceCookie:()=>BT,setAdminBypass:()=>wg,setAdminProviderDistribution:()=>Vx,setAdminProviderFallback:()=>Xx,setAgentScope:()=>Mc,setBootstrapAuthToken:()=>S_,setCachedAuthToken:()=>x_,setConnectionPolicies:()=>F_,setConnectorAuthorizationStrategy:()=>Xi,setConnectorCredential:()=>pa,setConnectorCredentialMode:()=>Qi,setConnectorName:()=>na,setConnectorPolicies:()=>ea,setConnectorSecretBinding:()=>W_,setConnectorSensitive:()=>Ji,setDefaultConnection:()=>qi,setEnterpriseDemo:()=>Lx,setEnv:()=>Fp,setGatewayBudget:()=>El,setGatewayRoutingPolicy:()=>Pl,setGitHubAppFromExisting:()=>gE,setGitHubAppPat:()=>mE,setImpersonationSession:()=>qb,setMaintenanceConfig:()=>oE,setMemberSuperAdmin:()=>sx,setMfaRequired:()=>px,setModelDefault:()=>Cc,setPersonalProjectSecret:()=>hi,setProjectModelAccess:()=>un,setProjectModelEnablement:()=>bP,setProjectOnboardingComplete:()=>Ts,setProjectOnboardingProfile:()=>d_,setProjectPolicies:()=>ma,setProjectSecretStrategy:()=>pi,setProjectSessionModel:()=>_c,setProjectSessionScope:()=>bc,setProjectSessionSharing:()=>Ya,setProjectTriggersActivation:()=>kc,setSavedCopyStore:()=>OM,setSessionOversight:()=>gx,setSessionProviderSecretPool:()=>Ti,settleSessionConnection:()=>UE,setupSSH:()=>vC,shareConnection:()=>Wi,shellActivityGroupLabel:()=>AS,shellExitCode:()=>Ud,shouldAttachImpersonation:()=>xg,shouldHideResponsePart:()=>MI,shouldShowToolPart:()=>by,shouldSuppressWorkingTurnBusy:()=>SI,showGroupItems:()=>PI,showTurnBusyIndicator:()=>Md,signInWithPassword:()=>Rr,signInWithProvider:()=>Cr,signInWithSso:()=>$r,signOut:()=>Lr,signUp:()=>kr,skillDocumentPath:()=>pT,skillInputDir:()=>cT,sortSessions:()=>sR,splitUserParts:()=>ak,startApp:()=>mp,startConnectionOAuth2Authorization:()=>j_,startConnectionOAuth2DeviceAuthorization:()=>D_,startConnectorSetupLink:()=>XC,startGitHubAppManifest:()=>dE,startProjectProviderOAuth:()=>rr,startProjectSession:()=>Oe,startSessionWithToken:()=>nE,startTask:()=>pw,stepLabel:()=>Ad,stopApp:()=>fp,stopProjectSession:()=>sn,stopSandbox:()=>pC,storeGitHubUserToken:()=>Fs,stripAnsi:()=>Sk,stripInstancePrefix:()=>qT,stripTrailingSlashes:()=>ce,submitAccessRequest:()=>HC,submitDemoRequest:()=>iE,submitOAuthConsent:()=>YC,submitReviewItem:()=>mu,submitSecretSetupLink:()=>eE,subscribeToImpersonation:()=>Gb,supabaseClient:()=>t_,syncConnectors:()=>Yi,syncSubscription:()=>TP,systemReload:()=>hv,toDaemonPath:()=>Ze,toInstanceAwarePath:()=>WT,toInternalUrl:()=>Pf,toSandboxAbsolutePath:()=>At,toToolView:()=>jk,toWorkspaceRelative:()=>Qp,toolInfo:()=>oo,toolKind:()=>ne,toolViewModel:()=>ch,triggerSandboxUpdate:()=>CC,triggersRequest:()=>Lm,turnEndCause:()=>$h,turnEndNotice:()=>zE,turnHasSteps:()=>nR,turnIsConfirmedActive:()=>AI,turnRetryLabel:()=>gM,unassignTicket:()=>xw,unwrapError:()=>le,updateAccountAuditWebhook:()=>qu,updateAccountBranding:()=>ns,updateAccountMemberRole:()=>ys,updateAccountName:()=>es,updateAgentConfig:()=>xP,updateApp:()=>rp,updateAppAccess:()=>ap,updateAuditWebhook:()=>jx,updateChannelBinding:()=>NP,updateConnectionCredential:()=>Fi,updateEmailPolicy:()=>bl,updateExperimentalFeature:()=>Rs,updateFeatureFlag:()=>ks,updateGroup:()=>Nl,updateKortixPty:()=>Bp,updateMilestone:()=>Vw,updateOAuthClient:()=>su,updatePassword:()=>Or,updatePatPolicy:()=>Rx,updatePolicy:()=>ex,updateProject:()=>Vt,updateProjectAccess:()=>Vs,updateProjectAgent:()=>Ow,updateProjectDefaultAgent:()=>jc,updateProjectGroupGrant:()=>ti,updateProjectSandboxProvider:()=>Is,updateProjectSession:()=>dc,updateProjectTrigger:()=>vc,updateRole:()=>Xl,updateRolePermissions:()=>Jl,updateSandboxTemplate:()=>Pa,updateSessionPolicy:()=>wx,updateSessionReminder:()=>Au,updateTask:()=>uw,updateTemplateWarmPool:()=>p_,updateTicket:()=>bw,updateTicketStatus:()=>_w,updateUserMetadata:()=>Dr,uploadAccountBrandingAsset:()=>rs,uploadAppArtifactArchive:()=>lp,uploadConnectorAttachment:()=>ji,uploadFile:()=>Tt,uploadPromptAttachment:()=>en,uploadSessionAttachment:()=>Ap,uploadSlackChannelFile:()=>dl,uploadTimeoutMsForBytes:()=>St,upsertCredential:()=>Zw,upsertProjectGitCredential:()=>fi,upsertProjectSecret:()=>ui,upsertSsoProvider:()=>fx,validateProjectManifest:()=>xs,validateReferralCode:()=>BP,validateToken:()=>bs,verifyGatewayProvider:()=>KP,verifyOtp:()=>Tr,verifySsoDomain:()=>hx,wakeEscalationAttemptSummary:()=>cM,wakeEscalationNote:()=>iM,wakeProgressFingerprint:()=>nM,wireIdClock:()=>Xe,wireIdClockAt:()=>_t,wireIdClockDelta:()=>Je,workingExpiryAtMs:()=>HE,workingTurnDrawsBusyRow:()=>kI,writeActivityGroupLabel:()=>kS,writeFile:()=>vn,wsDomain:()=>po,wsFavicon:()=>AR,wsRootDomain:()=>vR});var Tb={backendUrl:"",getToken:async()=>null},Eo=null,Wn=null;function Cb(e){Wn=e}function Eb(){return Wn}function Hn(e,t){t?.global!==!1&&(Eo=e)}function k(){return Wn?.()??Eo??Tb}function Vn(){return Eo!==null||Wn?.()!==void 0}function Mb(e){return new Promise(t=>setTimeout(t,e))}async function zn(e,t,n){let r=Math.max(1,t?.attempts??1),o=t?.baseDelayMs??0,s=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(s&&n?.(),o>0&&await Mb(o)),i=await e(),i)return i;return i}var Mo=12e4;function Ob(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function dg(e,t,n=Mo){let r=e instanceof Request?e.signal:t?.signal;if(Ob(e))return r??void 0;let o=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,o]):r:o}function Yn(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var b=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:o,...s}=n;Object.assign(this,s),r&&(this.name=r),o&&(this.stack=o);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)}},X=class extends b{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},Ee=class extends b{constructor(t,n,r,o={}){super(r||n.message||`Billing Error: ${t}`,{...o,status:t,detail:n}),this.name="BillingError"}},qe=class extends b{constructor(t=431,n,r){let o="Request headers are too large";super(r||n?.message||o,{status:t,detail:{message:n?.message||o,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},jb="ENDPOINT_RETIRED";function q(e,t){let n=t?` ${t}`:"";return new b(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:jb})}var Qn="feature_disabled";function gg(e){if(!(e instanceof b)||e.status!==403||e.code!==Qn)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Oo(e){let t=gg(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function jo(e){let t=gg(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function Kt(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 Ee(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 Do(e){return e instanceof Ee}function $o(e){if(!(e instanceof Ee))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 pe(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function de(e,t){return new Promise((n,r)=>{let o=()=>{t.removeEventListener("abort",o),r(pe())};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o)),t.aborted&&o()})}function Xn(e,t){return new Promise((n,r)=>{let o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),r(pe())},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.aborted?o():t?.addEventListener("abort",o,{once:!0})})}var mg="request_deadline",Db=/^Request exceeded the \d+s server processing deadline$/,fg=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===mg||Db.test(n),$b="git_mirror_unavailable",Ub=/^git mirror is temporarily unavailable$/,Lb=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===$b||Ub.test(n);async function Fb(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await de(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 pe();return{message:n,data:r}}function Nb(e,t,n){return fg(e,t,n)||Lb(e,t,n)||e===501&&t?.code===Uo||e===409&&(t?.code===Lo||t?.code===Fo)||e===503&&(t?.code===No||t?.code===Ko)}async function yg(e,t,n,r){let{message:o,data:s}=await Fb(e,t),i=new b(o,{status:e.status,response:e,details:s||void 0,data:s,detail:s?.detail,code:fg(e.status,s,o)?mg:s?.code||s?.error_code||s?.detail?.error_code||e.status.toString()});if(e.status===402&&(i=Kt(i)),e.status===403&&s?.code==="account_mfa_required"&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent("kortix:mfa-required"))}catch{}return e.status===431&&(i=new qe(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&&!Nb(e.status,s,o)&&k().onError?.(i,r),{error:i,success:!1}}var hg="X-Kortix-Impersonate",Go="kortix.impersonation",Ge=null,Jn=!1,qo=new Set;function Bo(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function bg(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 Kb(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 _g(){for(let e of qo)try{e()}catch{}}function Pg(){return Jn||(Jn=!0,Ge=Kb(Bo()?.getItem(Go)??null)),Ge&&!bg(Ge)?(Wo(),null):Ge}function qb(e){if(Jn=!0,!e){Wo();return}Ge=e;try{Bo()?.setItem(Go,JSON.stringify(e))}catch{}_g()}function Wo(){Jn=!0;let e=Ge!==null;Ge=null;try{Bo()?.removeItem(Go)}catch{}e&&_g()}function Gb(e){return qo.add(e),()=>{qo.delete(e)}}var Bb=/(^|\/)admin\/(api|analytics)(\/|$)/;function xg(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Bb.test(t)}function Ho(e){if(e!==void 0&&!xg(e))return{};let t=Pg();return t?{[hg]:t.grantId}:{}}var Yo=!1;function wg(e){Yo=e}function vg(){return Yo}function Wb(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function Vo(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function qt(e,t,n){let r=t.toLowerCase();for(let o of Object.keys(e))o.toLowerCase()===r&&delete e[o];e[t]=n}function er(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[o,s]of r.flatMap(Wb))qt(n,o,s);return n}function zo(e,t,n){let r={...t},o=k().clientVersion?.trim();o&&!Vo(r,"x-kortix-client-version")&&qt(r,"X-Kortix-Client-Version",o),Yo&&qt(r,"x-kortix-admin-bypass","1");for(let[s,i]of Object.entries(Ho(e)))qt(r,s,i);return Vo(r,"authorization")||qt(r,"Authorization",`Bearer ${n}`),r}async function Ag(e,t){let n=await Zn();if(!n)throw new X;return{headers:new Headers(zo(e,er(e,{headers:t}),n)),rejected:()=>k().getToken.invalidate?.(n)}}function Hb(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function Sg(e,t,n,r,o){if(t instanceof Request){let a=new Headers(zo(t.url,er(t,n),r));return e(new Request(t,{headers:a,...o?{signal:o}:{}}))}let s=String(t),i=zo(s,er(t,n),r);return e(s,{...n,headers:i,...o?{signal:o}:{}})}async function Zn(e){return zn(()=>k().getToken(),e)}async function it(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:o=Mo}=n,s=n.fetch??k().fetch??fetch,i=o===null?(e instanceof Request?e.signal:t.signal)??void 0:dg(e,t,o);if(i?.aborted)throw pe();let a=await(i?de(Zn(),i):Zn());if(!a)throw new X;let l=r&&!Hb(t)&&!Vo(er(e,t),"authorization"),p=l&&e instanceof Request?e.clone():e,d=await Sg(s,e,t,a,i);if(d.status!==401||!l)return d;k().getToken.invalidate?.(a);let g=await Zn({attempts:2,baseDelayMs:200});return!g||g===a?d:Sg(s,p,t,g,i)}var kg=()=>k().backendUrl||"",Vb=new Set([502,503,504]),zb=e=>Vb.has(e),Rg=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Yb=e=>Rg(e)||(e??"GET").toUpperCase()==="DELETE",Qb=2,tr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function xe(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:o=3e4,deadlineCoversBody:s=!1,...i}=t,a=new AbortController,l={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>l.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await Xb(e,i,n,r,o,s,a,l)}finally{i.signal?.removeEventListener("abort",p)}}async function Xb(e,t,n,r,o,s,i,a){try{if(t.signal?.aborted)throw pe();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},o);let l={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Zb(e,t,l,o,s,i,a);if(p instanceof X)return{error:p,success:!1};if(!p.ok)return await yg(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await de(p.json(),a.activeController.signal):g?.includes("text/")?d=await de(p.text(),a.activeController.signal):d=await de(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(l){return e_(l,e,t.method,n,r,o,a)}finally{nr(a)}}function nr(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Jb(e,t,n){try{await de(e.arrayBuffer(),t)}catch(r){if(tr(r))throw r}finally{nr(n)}}async function Zb(e,t,n,r,o,s,i){let a=Rg(t.method),l=Yb(t.method),p=l?Qb+1:1,d;for(let g=0;g<p;g++){g>0&&await Xn(250*2**(g-1),t.signal??void 0);let m=g===0?s:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await de(it(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 X)return new X;if(i.didTimeout&&tr(f)&&!t.signal?.aborted&&l&&g<p-1){i.didTimeout=!1;continue}if(tr(f)||g===p-1)throw f;continue}if(!a||!zb(d.status)||g===p-1)return o||nr(i),d;await Jb(d,m.signal,i)}return d}function e_(e,t,n,r,o,s,i){nr(i);let a=tr(e);a&&(i.isAborted=!0);let l;if(a){if(!i.didTimeout)return{error:new b("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(kg(),"")||t;l=new b(`Request timed out after ${Math.round(s/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:s})}else e instanceof Error?(l=new b(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(kg(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&k().onError?.(l,o)):(l=new b(String(e)),r&&k().onError?.(l,o));return{error:l,success:!1}}var Se=()=>k().backendUrl||"",Uo="feature_not_supported",Lo="model_not_servable",Fo="provision_in_flight",No="analytics_unavailable",Ko="accounts_list_unavailable",t_={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let o=new b(r.message||"Database error",{code:r.code,details:r});return k().onError?.(o,t),{error:o,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new b(n.message,{name:n.name||"ApiError",stack:n.stack}):new b(String(n));return k().onError?.(r,t),{error:r,success:!1}}}};async function n_(e,t,n={}){let{timeout:r=3e4,fetch:o}=n,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await it(`${Se()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:s.signal,credentials:"omit"},{timeoutMs:null,fetch:o})}catch(a){if(a instanceof X)return Yn();throw a}finally{clearTimeout(i)}}var c={putRaw:(e,t,n)=>xe(`${Se()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>xe(`${Se()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>xe(`${Se()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>xe(`${Se()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>xe(`${Se()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>xe(`${Se()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],xe(`${Se()}${e}`,{...o,method:"POST",body:t,headers:s})},uploadPut:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],xe(`${Se()}${e}`,{...o,method:"PUT",body:t,headers:s})},postStream:n_};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function Qo(e){return e.replace(/\/v1\/?$/,"")}async function at(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=Qo(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 Xo(){return u(await c.get("/accounts"))}async function Jo(e){return u(await c.post("/accounts",e))}async function Zo(e){return u(await c.get(`/accounts/${e}`))}async function es(e,t){return u(await c.patch(`/accounts/${e}`,{name:t}))}async function ts(e){return u(await c.get(`/accounts/${e}/branding`))}async function ns(e,t){return u(await c.put(`/accounts/${e}/branding`,t))}async function rs(e,t,n,r){let o=new FormData;return o.append("file",n,r??(n instanceof File?n.name:t)),u(await c.upload(`/accounts/${e}/branding/assets/${t}`,o))}async function os(e,t){return u(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function ss(e){return u(await c.delete(`/accounts/${e}/branding`))}async function is(e){return u(await c.get(`/accounts/${e}/members`))}async function as(e,t){return u(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function cs(e){return u(await c.get(`/accounts/${e}/invites`))}async function ls(e,t){return u(await c.delete(`/accounts/${e}/invites/${t}`))}async function us(e,t){return u(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function ps(){return u(await c.get("/account-invites",{showErrors:!1})).invites}async function ds(e){return u(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function gs(e){return u(await c.post(`/account-invites/${e}/accept`,{}))}async function ms(e){return u(await c.post(`/account-invites/${e}/decline`,{}))}async function fs(e,t){return u(await c.delete(`/accounts/${e}/members/${t}`))}async function ys(e,t,n){return u(await c.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function hs(e){return u(await c.post(`/accounts/${e}/leave`,{}))}async function r_(e){return at(e,"/v1/accounts")}async function bs(){let e=await c.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var o_=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","apps","monitors","reminders","warm_sessions","secrets_egress","pi_worker","pooled_provider_secrets","pi_harness","config_releases","agent_principal","us_region"];async function Be(){return u(await c.get("/projects"))}async function _s(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/projects${t}`))}async function Gt(e,t){return u(await c.get(`/projects/${e}`,t))}async function Ps(e,t,n="write"){return u(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function xs(e,t){return u(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Ss(e){return u(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function s_(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function Bt(e,t){let n=u(await c.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function Wt(e,t){return u(await c.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Ht(e,t){return u(await c.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function i_(e,t){return u(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function ws(e){return u(await c.post("/projects",e))}async function vs(e){return u(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function As(e,t={}){return u(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Ig=200;function a_(e){let t=e.split(`
1
+ "use strict";var Kortix=(()=>{var Io=Object.defineProperty;var Sb=Object.getOwnPropertyDescriptor;var wb=Object.getOwnPropertyNames;var vb=Object.prototype.hasOwnProperty;var Ab=(e,t)=>{for(var n in t)Io(e,n,{get:t[n],enumerable:!0})},kb=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of wb(t))!vb.call(e,o)&&o!==n&&Io(e,o,{get:()=>t[o],enumerable:!(r=Sb(t,o))||r.enumerable});return e};var Rb=e=>kb(Io({},"__esModule",{value:!0}),e);var mO={};Ab(mO,{ABORT_REASONS:()=>sh,ABORT_REASONS_NOT_YET_EMITTED:()=>FT,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>Fo,ACTIVE_INSTANCE_COOKIE:()=>Ln,ANALYTICS_UNAVAILABLE_CODE:()=>Lo,ATTACHMENT_PART_REF_PREFIX:()=>kh,ApiError:()=>b,AuthError:()=>X,BillingError:()=>Te,CONNECTION_FAULT_GRACE_MS:()=>jh,CONNECTOR_POLL_FIRST_DELAY_MS:()=>xh,CONNECTOR_POLL_INTERVAL_MS:()=>Sh,CONNECTOR_POLL_WINDOW_MS:()=>wh,CONTEXT_TOOLS:()=>py,COST_MARKUP:()=>Md,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>dy,DEFAULT_TRANSCRIPT_OPTIONS:()=>od,DESTRUCTIVE_PHASES:()=>fh,FEATURE_DISABLED_CODE:()=>Qn,FEATURE_FLAG_KEYS:()=>r_,FEATURE_NOT_SUPPORTED_CODE:()=>Do,FILE_VERBS:()=>Fe,FileExistsError:()=>xt,HeadlessAuthError:()=>dt,HostBoundaryError:()=>Kn,IMPERSONATION_HEADER:()=>mg,INBOX_OBSERVATION_MAX_MS:()=>_o,INITIAL_SETTLED_CONNECTION:()=>qE,INSTANCE_SCOPED_ROUTES:()=>ih,KORTIX_TRANSCRIPT_SCHEMA:()=>ZS,MAX_PROMPT_ATTACHMENTS_BYTES:()=>W_,MAX_PROMPT_ATTACHMENT_BYTES:()=>ka,MAX_PROMPT_ATTACHMENT_FILES:()=>Tg,MEMORY_VERBS:()=>XI,MODEL_NOT_SERVABLE_CODE:()=>$o,NO_GROUP_ACTIVITY_TOOLS:()=>em,OPTIMISTIC_ABORT_MAX_MS:()=>Po,OPTIMISTIC_COMPACTION_MAX_MS:()=>tM,OPTIMISTIC_RECEIPT_MAX_MS:()=>ho,PERSISTED_QUERY_CACHE_VERSION:()=>QK,PLUMBING_TOOLS:()=>Iy,PREVIEW_PROBE_TIMEOUT_MS:()=>OE,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>aP,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>iP,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>Dg,PROVISION_IN_FLIGHT_CODE:()=>Uo,PublicSessionShareError:()=>_r,RUNTIME_NOT_READY_MARKERS:()=>XT,RUNTIME_PERMISSION_CAPABILITIES:()=>nw,RUNTIME_PERMISSION_REPLIES:()=>tw,RequestTooLargeError:()=>Ke,RuntimeNotReadyError:()=>_t,SANDBOX_FS_ROOTS:()=>Qr,SANDBOX_PORTS:()=>we,SERVER_COMPACTION_REVALIDATE_MS:()=>Lh,SERVER_OBSERVATION_MAX_MS:()=>bo,SESSION_LIST_STATUS:()=>fM,SESSION_NOTICE:()=>bM,STANDALONE_TOOLS:()=>tm,STREAM_OBSERVATION_MAX_MS:()=>jt,SandboxNotReadyError:()=>Fn,SessionNotReadyError:()=>Ve,SessionStartError:()=>mr,TURN_END_LEDGER_LAG_MS:()=>zE,TURN_ERROR_CODES:()=>Em,WAKE_ESCALATION_COOLDOWN_MS:()=>aM,WAKE_MAX_RESTARTS:()=>iM,WAKE_NO_PROGRESS_MS:()=>sM,WIRE_ID_BACKDATE_MS:()=>Nr,WIRE_ID_CLOCK_TOLERANCE:()=>je,WIRE_ID_TIME_MASK:()=>ve,WIRE_ID_TIME_SCALE:()=>yt,WIRE_MESSAGE_ID:()=>Am,__getConfigResolver:()=>Cb,__setConfigResolver:()=>Tb,abortErrorReason:()=>NT,acceptAccountInvite:()=>ps,acceptInvite:()=>bC,actReviewItem:()=>gu,activateConnection:()=>Fi,addComputerToProject:()=>qi,addGroupMembers:()=>Kl,addMarketplaceSource:()=>Qu,advanceWakeEscalation:()=>uM,allDescendantIds:()=>vy,appendPreviewToken:()=>Gd,approveProjectAccessRequest:()=>qs,approveTask:()=>dw,archiveProject:()=>Ht,assignTicket:()=>Pw,attachGroupToProject:()=>Js,authMfa:()=>Ur,authUser:()=>jr,authenticatedFetch:()=>j,authorizePreviewUrl:()=>ME,backendApi:()=>l,bindSlackIdentity:()=>OP,bindTeamsIdentity:()=>jP,brokerProjectSecretRequest:()=>ui,browserKeyValueStorage:()=>vE,buildInstancePath:()=>ch,buildPresentationTemplateImageUrl:()=>UE,buildPresentationTemplatePdfUrl:()=>$E,buildPreviewAuthEndpoint:()=>qd,buildPublicTemplateUrl:()=>lE,buildRuntimePresentationConversionUrl:()=>Oh,buildSandboxTemplate:()=>Pa,buildScrapeFailureResults:()=>Ey,buildStaticFileHealthPreviewUrl:()=>uA,buildStaticFileLocalUrl:()=>lA,buildStaticFilePreviewUrl:()=>cA,buildStaticFileServicePath:()=>df,buildTunnelEventStreamUrl:()=>KM,buildWebProxyUrl:()=>fA,bulkActReviewItems:()=>mu,bulkDeletePolicies:()=>nx,bulkImportPolicies:()=>rx,burstSummary:()=>hR,burstSummaryLabel:()=>bR,callConnector:()=>Ci,cancelAccountDeletion:()=>qx,cancelAccountInvite:()=>as,cancelSandbox:()=>dC,cancelSandboxUpdate:()=>MC,cancelScheduledChange:()=>Vc,cancelSubscription:()=>Bc,checkAccessEmail:()=>WC,childMapByParent:()=>oR,claimComputer:()=>UC,claimNext:()=>$f,claimPerSeatBilling:()=>IP,claimWarmProjectSession:()=>ec,classifyPart:()=>bd,classifyPreviewProbeStatus:()=>Mh,classifyPtyClose:()=>jm,classifyTurn:()=>by,cleanErrorMessage:()=>dR,cleanResultSnippet:()=>SR,cleanWorkerOutput:()=>WI,clearImpersonationSession:()=>Go,clearKortixAppViewerCache:()=>Qh,clearModelDefault:()=>Tc,clearSessionFresh:()=>oP,closeChangeRequest:()=>Na,closeMilestone:()=>zw,collectTurnParts:()=>eR,commentTicket:()=>Sw,commitSessionChanges:()=>Ga,compactionExpiryAtMs:()=>rM,compactionTurnInfo:()=>_R,compareMessagesForDisplay:()=>Yk,completeInFlight:()=>Uf,completeSlackInstall:()=>sl,completeTeamsInstall:()=>il,composerSelectableAgents:()=>Xd,computeStatusFromPart:()=>Ed,configureAutoTopup:()=>Xc,configureKortix:()=>Hn,confirmCheckoutSession:()=>qc,connectEmail:()=>ml,connectSlack:()=>rl,connectionFromHealth:()=>KE,connectionIsFaulted:()=>NE,connectionSharedWithEveryone:()=>k_,connectorConnect:()=>Rg,connectorFinalize:()=>Ig,connectorHeadline:()=>fE,contextLabelForTool:()=>ER,contextToolSummary:()=>JA,contextToolTrigger:()=>ZA,convertPresentationToGoogleSlides:()=>Zx,convertRuntimePresentation:()=>LE,copyFile:()=>Sn,costExportUrl:()=>Zc,countLiveInboxPrompts:()=>QE,countReviewItemsBySegment:()=>tS,createAccount:()=>Qo,createAccountAuditWebhook:()=>Fu,createAccountSecretResource:()=>_i,createAccountToken:()=>Ru,createApp:()=>Zu,createAppAccessSession:()=>ip,createAppDeployment:()=>cp,createArtifactKind:()=>ZR,createAssignment:()=>au,createAuditWebhook:()=>Ox,createBackup:()=>xC,createCheckoutSession:()=>Kc,createConnector:()=>na,createConnectorLinkInfoCache:()=>dE,createFile:()=>xn,createGatewayKey:()=>Ml,createGroup:()=>Ul,createHttpSessionSyncController:()=>Wh,createInstance:()=>jC,createKortix:()=>Mf,createKortixPty:()=>Kp,createKortixSession:()=>Fr,createMarketplaceInstallSession:()=>yS,createMilestone:()=>Hw,createModelVisibility:()=>yb,createOAuthClient:()=>nu,createPerSeatCheckout:()=>RP,createPersistedQueryCache:()=>wE,createPolicy:()=>ZP,createPortalSession:()=>Gc,createProject:()=>xs,createProjectAgent:()=>Mw,createProjectCliToken:()=>Mu,createProjectRepo:()=>Ss,createProjectResourceGrant:()=>ni,createProjectSession:()=>We,createProjectTrigger:()=>xc,createPromptAttachmentController:()=>rd,createRole:()=>zl,createSSEStream:()=>qM,createSandbox:()=>sC,createSandboxShare:()=>_u,createSandboxTemplate:()=>ha,createSavedCopyStore:()=>LM,createScimToken:()=>ax,createServiceAccountApi:()=>Tx,createSessionPrompt:()=>tn,createSessionPublicShare:()=>Xa,createSessionQueue:()=>jf,createSessionReminder:()=>Su,createSsoGroupMapping:()=>Px,createTask:()=>lw,createTicket:()=>hw,createTunnelEventStream:()=>GM,currentSavedCopyStore:()=>NM,declineAccountInvite:()=>ds,declineInvite:()=>_C,deleteAccountImmediately:()=>Gx,deleteAccountSecretResource:()=>xi,deleteApp:()=>np,deleteAppDeployment:()=>mp,deleteAuditWebhook:()=>Dx,deleteBackup:()=>wC,deleteConnector:()=>oa,deleteCredential:()=>tv,deleteEnv:()=>Lp,deleteFile:()=>Je,deleteGatewayBudget:()=>Cl,deleteGitHubInstallation:()=>Ls,deleteGroup:()=>Fl,deleteInstance:()=>DC,deleteKortixProject:()=>Kw,deleteMilestone:()=>Qw,deleteOAuthClient:()=>su,deletePersonalProjectSecret:()=>yi,deletePolicy:()=>tx,deleteProjectAgent:()=>jw,deleteProjectProviderOAuth:()=>di,deleteProjectResourceGrant:()=>ri,deleteProjectSecret:()=>mi,deleteProjectSession:()=>pc,deleteProjectTrigger:()=>wc,deletePromptAttachment:()=>ct,deleteRole:()=>Xl,deleteSandboxTemplate:()=>_a,deleteServiceAccountApi:()=>Ex,deleteSessionPrompt:()=>ic,deleteSessionReminder:()=>vu,deleteSsoGroupMapping:()=>xx,deleteSsoProvider:()=>bx,deleteTask:()=>gw,deleteTicket:()=>ww,describeAccountInvite:()=>us,describeConnectorTool:()=>Ti,detachGroupFromProject:()=>ei,detectLocalhostUrls:()=>cf,directSubsessions:()=>PM,disableServiceAccountApi:()=>Cx,disconnectEmail:()=>fl,disconnectGitHubApp:()=>PE,disconnectSlack:()=>cl,discoverConnectionOAuth2:()=>C_,discoverConnectionOAuth2Resource:()=>E_,discoverConnectorAuth:()=>ra,discoverLocalSandbox:()=>lC,downloadAccountAudit:()=>aE,dropClientForUrl:()=>pv,dropPublicClientForUrl:()=>mv,editQueued:()=>Kf,editSessionPrompt:()=>ac,enqueue:()=>Df,ensurePmSession:()=>Cw,ensurePreviewSessionCookie:()=>Eh,ensureProjectConnectorConnection:()=>R_,ensureSandbox:()=>mh,ensureWarmProjectSession:()=>Za,env:()=>Mm,exchangeCode:()=>Er,exportAccountAudit:()=>Uu,extractGatewayErrorDetails:()=>ue,extractInstanceRoute:()=>Mt,extractSkillBaseDir:()=>Zy,extractSkillContent:()=>sT,extractSkillFiles:()=>Jy,extractWorkerPreview:()=>VI,failInFlight:()=>Lf,fallbackBusyRowAfterTurnId:()=>vI,familyForTool:()=>go,featureDisabledKey:()=>Mo,featureFlags:()=>kp,fetchAccountStateWithToken:()=>AP,fetchAccountsWithToken:()=>n_,fetchAttachmentPart:()=>AE,fetchCostExportCsv:()=>MP,fetchKortixAppViewer:()=>Yd,fetchProjectArchive:()=>Aa,fetchProjectsForAccountWithToken:()=>d_,fetchSessionAttachment:()=>vp,filePhase:()=>QI,fileVerb:()=>YI,files:()=>Xm,finalizeAppArtifact:()=>xr,finalizeConnectorSetupLink:()=>JC,findActiveTranscriptShare:()=>lP,findFiles:()=>_n,findLastTextPart:()=>tR,findSessionAttachments:()=>DS,findText:()=>Pn,fireProjectTrigger:()=>Ac,fixSandboxWithAgent:()=>ya,flattenModels:()=>gb,flattenThought:()=>aI,formatBillingErrorForUI:()=>jo,formatCost:()=>NI,formatDuration:()=>UI,formatJsonFailureOutput:()=>gR,formatMessageDay:()=>gI,formatMessageExact:()=>mI,formatOpenCodeRuntimeError:()=>tC,formatRawOutput:()=>xR,formatRuntimeError:()=>gh,formatTokens:()=>KI,formatTranscript:()=>Gf,freshSendHint:()=>RI,generateSessionId:()=>Of,getAccount:()=>Xo,getAccountBranding:()=>Zo,getAccountDeletionStatus:()=>Nx,getAccountState:()=>jc,getAccountStateMinimal:()=>Dc,getActiveInstanceIdFromCookie:()=>uh,getAdminProviderAnalytics:()=>zx,getAdminProviderDistribution:()=>Wx,getAdminProviderFallback:()=>Qx,getAdminRole:()=>Bx,getAgentCardLabel:()=>yy,getAgentConfig:()=>PP,getAgentPersona:()=>Dw,getAllVersions:()=>TC,getAnsweredQuestionParts:()=>rR,getApp:()=>ep,getAppAccess:()=>rp,getAppDeployment:()=>up,getAppDeploymentLogs:()=>pp,getApprovalLink:()=>fS,getAuthToken:()=>at,getAuthTokenWithRetry:()=>S_,getAutoTopupSettings:()=>Qc,getAutoTopupSetupStatus:()=>kP,getBillingCreditBreakdown:()=>Lc,getBillingTierConfigurations:()=>Nc,getBillingTransactionsSummary:()=>Uc,getBillingUsageHistory:()=>Fc,getChangeRequest:()=>Da,getChangeRequestDiff:()=>$a,getChangeRequestMergePreview:()=>Ua,getChildSessionError:()=>gk,getChildSessionId:()=>md,getChildSessionToolParts:()=>mk,getClient:()=>$e,getClientForUrl:()=>me,getConnectStatus:()=>ca,getConnectionOAuth2Application:()=>T_,getConnectionOAuth2Status:()=>$_,getConnectionPolicies:()=>U_,getConnectorCatalog:()=>zt,getConnectorConfig:()=>Zi,getConnectorPolicies:()=>Xi,getConnectorSetupLink:()=>QC,getCostSummary:()=>EP,getCurrentInstanceIdFromPathname:()=>lh,getCurrentInstanceIdFromWindow:()=>GT,getCurrentProject:()=>Yp,getDefaultAccountState:()=>Oc,getDiagnostics:()=>bk,getDirectory:()=>fy,getDiscoverConnector:()=>ur,getDiscoverIntegration:()=>G_,getEmailInstallation:()=>dl,getEmailMode:()=>gl,getEnterpriseDemo:()=>Ux,getFileStatus:()=>bn,getFileWithDir:()=>dd,getFilename:()=>my,getFullChangelog:()=>yh,getGatewayBreakdown:()=>Al,getGatewayBudgets:()=>Il,getGatewayErrors:()=>Rl,getGatewayKeys:()=>El,getGatewayLog:()=>Sl,getGatewayOverview:()=>wl,getGatewayRoutingPolicy:()=>hl,getGatewaySeries:()=>vl,getGatewaySessions:()=>kl,getGitHubAppStatus:()=>yE,getGitHubInstallation:()=>Cs,getGoogleAuthUrl:()=>Jx,getGroup:()=>$l,getHiddenToolParts:()=>ck,getImpersonationSession:()=>hg,getInvite:()=>hC,getJustavpsServerTypes:()=>OC,getKortixProject:()=>Lw,getKortixProjectBySession:()=>Fw,getKortixPtyWebSocketUrl:()=>Bp,getLatestSandboxVersion:()=>IC,getMaintenanceConfig:()=>rE,getManagedGitBackend:()=>Fs,getManagedGitStatus:()=>c_,getMarketplaceCatalogItem:()=>Vu,getMarketplaceCatalogItemFile:()=>zu,getMfaRequired:()=>lx,getMilestone:()=>Bw,getModelDefaults:()=>Rc,getOAuthClient:()=>tu,getOAuthConsentRequest:()=>zC,getOpenCodeConfigInvalidError:()=>zT,getPartText:()=>sk,getPatPolicy:()=>kx,getPermissionForTool:()=>_k,getProject:()=>Kt,getProjectActivity:()=>$w,getProjectCommit:()=>Ca,getProjectCommitDiff:()=>Ea,getProjectDetail:()=>qt,getProjectFileHistory:()=>Ma,getProjectGitToken:()=>Ps,getProjectLlmCatalog:()=>Gt,getProjectLlmCatalogProviders:()=>s_,getProjectModelAccess:()=>an,getProjectModelPicker:()=>Bt,getProjectSandboxHealth:()=>Yt,getProjectSandboxProviderTransition:()=>l_,getProjectSession:()=>en,getProjectSessionConfigState:()=>dc,getProjectSessionScope:()=>fc,getProrationPreview:()=>zc,getProviders:()=>rC,getProxyBaseUrl:()=>pA,getPublicClientForUrl:()=>gv,getPublicMarketplaceItem:()=>GC,getPublicMarketplaceItemFile:()=>BC,getPublicSessionShare:()=>gS,getPublicSessionShareMessages:()=>mS,getPublicShareByToken:()=>tE,getPublicTemplate:()=>uE,getQuestionForTool:()=>Pk,getReferralCode:()=>qP,getReferralStats:()=>WP,getRetryInfo:()=>qI,getRetryMessage:()=>GI,getReviewItem:()=>pu,getRolePermissions:()=>Hl,getRoleUsage:()=>Vl,getRuntimeConfigInvalidError:()=>yo,getSSHConnection:()=>AC,getSandbox:()=>oC,getSandboxById:()=>iC,getSandboxPortUrl:()=>nC,getSandboxProvisionStatus:()=>LC,getSandboxProvisionStreamUrl:()=>FC,getSandboxUpdateStatus:()=>RC,getSandboxUrl:()=>Ld,getSecretSetupLink:()=>ZC,getServerHealth:()=>Xr,getServiceLogs:()=>iv,getSessionAudit:()=>tc,getSessionCost:()=>FI,getSessionCostRecord:()=>sn,getSessionHealth:()=>Zp,getSessionMessageAuthors:()=>_c,getSessionOpenBundle:()=>uP,getSessionOversight:()=>dx,getSessionParticipants:()=>za,getSessionPolicy:()=>Sx,getSessionPreviewCandidates:()=>Ya,getSessionProviderSecretPool:()=>Ai,getSessionTranscript:()=>nc,getSessionTranscriptSync:()=>rc,getSessionTurn:()=>oc,getShellModePart:()=>TI,getSlackChannelFile:()=>ll,getSlackInstallation:()=>nl,getSlackManifest:()=>al,getSlackMode:()=>ol,getSsoProvider:()=>mx,getStaticFileHealthPath:()=>gf,getSupabaseAccessToken:()=>sr,getSupabaseAccessTokenWithRetry:()=>it,getTask:()=>iw,getTaskStatus:()=>cw,getTemplate:()=>hS,getTicket:()=>fw,getToolInfo:()=>fk,getToolPrimaryArg:()=>ro,getTranscriptFilename:()=>Bf,getTurnCost:()=>LI,getTurnError:()=>OI,getTurnErrorDetails:()=>DI,getTurnErrorRawText:()=>jI,getTurnStatus:()=>$I,getUsageRollup:()=>Jc,getUserRolesWithToken:()=>sE,getVersionDiff:()=>Oa,getWorkingState:()=>EI,grantAccountSecretResource:()=>Si,grantSandboxProjectAccess:()=>fC,grantSecretToAgent:()=>SP,groupMessagesIntoTurns:()=>Xk,groupShowSegments:()=>hI,groupSteps:()=>Td,hasDiffs:()=>BI,hasLocalhostUrls:()=>sA,hasPreviewTarget:()=>pf,hasRetryingAssistantTurn:()=>iR,heartbeatGapEvent:()=>Fm,holdSessionPrompts:()=>lc,humanizeReviewActionPath:()=>hu,humanizeSearchQuery:()=>Rn,humanizeToolName:()=>yd,impersonationHeaders:()=>Bo,importSsoProviderFromMetadata:()=>yx,inboxObservationSupersedes:()=>YE,initialWakeEscalationState:()=>Wd,inputPath:()=>ke,installTemplate:()=>bS,invalidateTokenCache:()=>ir,inviteAccountMember:()=>ss,inviteProjectMember:()=>Vs,inviteRepoCollaborator:()=>bs,isAbortError:()=>Un,isAdminBypassEnabled:()=>xg,isAgentPart:()=>ek,isAppRouteUrl:()=>af,isAttachment:()=>ik,isAttachmentPartRef:()=>Rh,isBillingError:()=>Oo,isCompactionPart:()=>tk,isConfigured:()=>Vn,isContextTool:()=>XA,isDestructivePhase:()=>kC,isEmptyConversation:()=>zh,isEmptyShowPart:()=>Sr,isErrorOutput:()=>aR,isExternalUrl:()=>bA,isFeatureDisabledError:()=>Eo,isFilePart:()=>gd,isImpersonationSessionLive:()=>fg,isInstanceDetailPath:()=>KT,isInstanceScopedAppPath:()=>ah,isInternalLocalhostUrl:()=>mA,isInvisibleActivityPart:()=>bp,isInviteSent:()=>f_,isLastUserMessage:()=>CI,isLegacyMigratedSession:()=>Fh,isManagedGithubProject:()=>o_,isNoGroupActivityTool:()=>hp,isOfferedModel:()=>ko,isOpenCodeConfigInvalidError:()=>YT,isPaintableSavedCopy:()=>Vd,isPatchPart:()=>rk,isPersistableQueryKey:()=>SE,isPreviewUrl:()=>gA,isProxiableLocalhostUrl:()=>mf,isQuestionTool:()=>vS,isReasoningPart:()=>ye,isRetryableTurnError:()=>Ay,isRuntimeConfigInvalidError:()=>ph,isRuntimeNotReadyResponse:()=>dh,isRuntimeReady:()=>Jp,isRuntimeStartingError:()=>eC,isSandboxNotReadyError:()=>Ot,isSelectableAgent:()=>Ar,isServerReachable:()=>Qp,isSessionAttachmentRef:()=>TS,isSessionFresh:()=>Wa,isSessionStartError:()=>fP,isShellActivityTool:()=>wS,isShellMode:()=>Wy,isShortOutput:()=>HI,isShowContentUnavailable:()=>xS,isShowPayloadEmpty:()=>ln,isSnapshotPart:()=>nk,isStandaloneActivityTool:()=>_p,isStepPart:()=>ok,isSubdomainPreviewUrl:()=>qn,isTextPart:()=>fe,isToolPart:()=>Y,isToolPartHidden:()=>lk,isTurnErrorCode:()=>ew,isUnderSandboxRoot:()=>Vp,isWebProxyUrl:()=>hA,isWireIdAheadOf:()=>Rm,kortixAppViewerToken:()=>Xh,kortixPty:()=>Um,leaveAccount:()=>fs,linkGitHubInstallation:()=>$s,linkRepository:()=>Is,listAccountAudit:()=>Du,listAccountAuditWebhooks:()=>Lu,listAccountInvites:()=>is,listAccountMembers:()=>os,listAccountResourceGrants:()=>XP,listAccountSecretResources:()=>bi,listAccountSessions:()=>vx,listAccountTokens:()=>ku,listAccounts:()=>Yo,listActions:()=>ox,listAdminSandboxes:()=>Hx,listAgentIdentities:()=>Bl,listAllConnections:()=>ji,listAppAgents:()=>op,listAppDeployments:()=>lp,listApps:()=>Ju,listAssignments:()=>iu,listAuditEvents:()=>$x,listAuditWebhooks:()=>Mx,listBackups:()=>PC,listBillingTransactions:()=>$c,listChangeRequests:()=>ja,listChannelBindings:()=>FP,listColumns:()=>vw,listConnectSections:()=>K_,listConnectToolkits:()=>N_,listConnections:()=>Oi,listConnectorAccounts:()=>Ei,listConnectorTools:()=>cr,listConnectors:()=>Hi,listCostByProject:()=>CP,listCredentialEvents:()=>Jw,listCredentials:()=>Xw,listDiscoverConnectors:()=>lr,listDiscoverIntegrations:()=>q_,listDiscoverSections:()=>aa,listEnv:()=>$p,listFeaturedMarketplaces:()=>Hu,listFields:()=>kw,listFiles:()=>vt,listGatewayLogs:()=>xl,listGitHubInstallations:()=>Es,listGitHubRepositories:()=>Os,listGitHubRepositoryBranches:()=>js,listGroupMembers:()=>Nl,listGroupProjectGrants:()=>zP,listGroups:()=>Dl,listKortixProjectSessions:()=>Nw,listKortixProjects:()=>Uw,listKortixPty:()=>Np,listLinkableGitHubInstallations:()=>Ms,listManagedGitRepositories:()=>Ns,listMarketplaceCatalogItems:()=>Bu,listMarketplaceSources:()=>Yu,listMarketplaces:()=>Wu,listMemberGroups:()=>YP,listMemberProjectAccess:()=>QP,listMilestoneEvents:()=>Ww,listMilestones:()=>Gw,listMyAccountInvites:()=>ls,listOAuthClients:()=>eu,listOAuthGrants:()=>Tu,listPendingApprovals:()=>oi,listPendingProjectInvites:()=>zs,listPermissions:()=>lu,listPipedreamApps:()=>sa,listPipedreamSections:()=>ia,listPolicies:()=>JP,listProjectAccess:()=>Bs,listProjectAccessRequests:()=>Ks,listProjectAgentIdentities:()=>Wl,listProjectAgents:()=>Ew,listProjectAudit:()=>$u,listProjectBranches:()=>Ia,listProjectCliTokens:()=>Eu,listProjectCommits:()=>Ta,listProjectFiles:()=>Sa,listProjectGroupGrants:()=>Xs,listProjectPolicies:()=>pa,listProjectProviderOAuth:()=>pi,listProjectReminders:()=>Au,listProjectResourceGrants:()=>ti,listProjectSandboxTemplates:()=>ga,listProjectSandboxes:()=>xa,listProjectSecrets:()=>ai,listProjectSessions:()=>Be,listProjectSessionsPage:()=>Ha,listProjectSnapshots:()=>ma,listProjectTriggers:()=>Pc,listProjects:()=>Ge,listProjectsForAccount:()=>hs,listPublicMarketplaceItems:()=>KC,listPublicMarketplaces:()=>qC,listReferrals:()=>HP,listReviewItems:()=>uu,listRoles:()=>Gl,listSandboxProjectMembers:()=>mC,listSandboxShares:()=>bu,listSandboxes:()=>cC,listScimTokens:()=>ix,listServiceAccountsApi:()=>Ix,listServiceTemplates:()=>sv,listServices:()=>ov,listSessionConnectRequests:()=>F_,listSessionCosts:()=>tl,listSessionPrompts:()=>sc,listSessionProviderSecretPools:()=>ki,listSessionPublicShares:()=>Qa,listSessionReminders:()=>xu,listSessionsNeedingInput:()=>si,listSsoGroupMappings:()=>_x,listTaskEvents:()=>aw,listTasks:()=>sw,listTemplates:()=>Iw,listTicketEvents:()=>yw,listTickets:()=>mw,loadHttpSessionHistory:()=>Bh,looksLikeError:()=>xd,looksLikeHtml:()=>kR,looksLikeJsonPayload:()=>PR,mapApiReviewItem:()=>dS,markInstanceError:()=>$C,markSessionFresh:()=>Zt,maxWireIdClock:()=>Mp,memoryRelPath:()=>JI,mergeBurstSteps:()=>oI,mergeChangeRequest:()=>Fa,messageCreatedAt:()=>cI,messageTime:()=>qy,migrateAdminSandboxProvider:()=>Yx,mintWireMessageId:()=>Kr,mintWireMessageIdAbove:()=>Op,mkdir:()=>It,modelInDefaultView:()=>hb,modelRefToKey:()=>tb,narrateFailedStep:()=>Id,narrateStep:()=>Rd,narrationToolName:()=>Dn,narrowChatEvent:()=>Nm,newestWireIdClock:()=>Im,nextConnectorPollDelay:()=>mE,normalizeActivityToolName:()=>ae,normalizeAppPathname:()=>HT,normalizeExternalInput:()=>_A,normalizeName:()=>W,normalizeToolName:()=>fd,notifyHostSignal:()=>Kh,openChangeRequest:()=>La,openEventStream:()=>Vr,openStressTestStream:()=>cE,parseBillingError:()=>Ft,parseEmbeddedFailure:()=>wR,parseFlagOverride:()=>US,parseJsonFailure:()=>Ry,parseLocalhostUrl:()=>kn,parseMemoryView:()=>ZI,parseOpenCodeErrorPayload:()=>VT,parsePresentationOutput:()=>nT,parseProxyHop:()=>Xp,parseQuestionAnswersFromOutput:()=>rT,parseReadOutput:()=>oT,parseRuntimeErrorPayload:()=>Ud,parseScrapeInputUrls:()=>Cy,parseScrapeOutput:()=>My,parseSubdomainUrl:()=>td,parseTaskRows:()=>zI,parseWebProxyUrl:()=>yA,parseWebSearchOutput:()=>Ad,partOutcome:()=>Sd,patchKortixProject:()=>qw,patchVerb:()=>tT,pickerProviderList:()=>db,pipedreamConnect:()=>ta,pipedreamConnectConnection:()=>Bi,pipedreamFinalize:()=>ua,pipedreamFinalizeConnection:()=>Wi,platformConfig:()=>k,pollConnectionOAuth2DeviceAuthorization:()=>D_,pollProjectProviderOAuth:()=>or,previewGatewayRoute:()=>Pl,previewMfaRequired:()=>ux,previewSlackIdentity:()=>DP,previewTeamsIdentity:()=>$P,probeEffectivePermission:()=>Jl,probeEffectivePermissions:()=>Zl,probePreviewPort:()=>jE,projectCompacting:()=>nM,projectConfigAgentsToOpenCodeAgents:()=>Zh,projectConfigAgentsToRuntimeAgents:()=>Qd,projectSessionConnection:()=>FE,projectSessionForRuntimeId:()=>xM,projectSessionStartSeed:()=>mP,projectWorking:()=>XE,provisionProject:()=>ws,provisionProjectStream:()=>a_,provisionProjectWithToken:()=>g_,proxyLocalhostUrl:()=>ed,proxyUrlToInternal:()=>dA,purchaseCredits:()=>Yc,putConnectionOAuth2Application:()=>I_,rawErrorText:()=>ad,reactivateSandbox:()=>gC,reactivateSubscription:()=>Wc,readBlob:()=>kt,readFile:()=>At,readProjectFile:()=>va,reasoningIsRunning:()=>Uy,rebuildProjectSnapshot:()=>fa,reconcileConnection:()=>Di,reconcileMemberConnection:()=>$i,reconcileServices:()=>cv,recordPlatformLogout:()=>VC,recoverLinkResults:()=>lo,refreshReferralCode:()=>GP,refreshSession:()=>gt,registerAppArtifact:()=>Pr,registerConnectionOAuth2Client:()=>M_,registerService:()=>lv,rejectProjectAccessRequest:()=>Gs,relativizePath:()=>hk,reloadProjectSessionConfig:()=>gc,reloadProjectSessionConfigStream:()=>mc,removeAccountAuditWebhook:()=>Ku,removeAccountBrandingAsset:()=>ns,removeAccountMember:()=>gs,removeGroupMember:()=>ql,removeKortixPty:()=>Gp,removeMarketplaceSource:()=>Xu,removeQueued:()=>Nf,renameConnection:()=>Ki,renameFile:()=>vn,renameSandbox:()=>aC,reopenChangeRequest:()=>Ka,reopenMilestone:()=>Yw,reorderQueued:()=>qf,replaceColumns:()=>Aw,replaceFields:()=>Rw,replaceProjectRepository:()=>Ts,replaceTemplates:()=>Tw,requestAccountDeletion:()=>Kx,requestChangesOnChangeRequest:()=>qa,requestProjectAccess:()=>m_,requestProjectConnector:()=>Gu,requestProjectSecret:()=>qu,resendAccountInvite:()=>cs,resendPendingProjectInvite:()=>Qs,resetAccountBranding:()=>rs,resetClient:()=>dv,resetGatewayRoutingPolicy:()=>_l,resetPassword:()=>Mr,resetPublicClient:()=>fv,resetSandboxUpdateStatus:()=>EC,resolveApproval:()=>ii,resolveComposerAgent:()=>Jh,resolveComposerModel:()=>Pb,resolveConnectorStart:()=>gE,resolveModelDefault:()=>_b,resolvePublicShareUrl:()=>cP,resolveScrapeResults:()=>RR,resolveWorkingTurn:()=>II,resolvedPlan:()=>vP,restartProjectSession:()=>nn,restartSandbox:()=>uC,restoreBackup:()=>SC,retryFailed:()=>Ff,retrySessionPrompt:()=>cc,revealCredential:()=>ev,reviewItemTarget:()=>eS,reviewSegmentForStatus:()=>Qg,reviewVerdictForStatus:()=>nS,revokeAccountSecretResourceGrant:()=>wi,revokeAccountSession:()=>Ax,revokeAccountToken:()=>Iu,revokeAssignment:()=>cu,revokeConnection:()=>Li,revokeGatewayKey:()=>Ol,revokeOAuthGrant:()=>Cu,revokePendingProjectInvite:()=>Ys,revokeProjectAccess:()=>Hs,revokeProjectCliToken:()=>Ou,revokeSandboxProjectAccess:()=>yC,revokeSandboxShare:()=>Pu,revokeScimToken:()=>cx,revokeSessionPublicShare:()=>Ja,rewriteLocalhostUrl:()=>Le,rollbackApp:()=>fp,rootRuntimeSession:()=>Nh,rotateAccountSecretResource:()=>Pi,rotateOAuthClientSecret:()=>ou,runGatewayPlayground:()=>jl,runProjectProviderOAuthFlow:()=>__,runtimeSessionsOf:()=>xo,runtimeSupports:()=>tf,sanitizePtyChunk:()=>$m,saveGitHubInstallation:()=>Ds,savedCopyEmptyRoot:()=>Vh,scheduleDowngrade:()=>Hc,searchConnectorTools:()=>Ii,searchProjectFiles:()=>wa,segmentTurn:()=>fI,selectableProjectAgents:()=>FS,sendMagicLink:()=>Ir,sendReferralEmails:()=>VP,serverCompactionRevalidateAtMs:()=>oM,serviceAction:()=>av,sessionConnectionLabel:()=>hM,sessionListStatus:()=>yM,sessionModelPin:()=>bc,sessionParentId:()=>sP,sessionStartKey:()=>hP,setAccountSecretResourceAccess:()=>vi,setActiveInstanceCookie:()=>BT,setAdminBypass:()=>Pg,setAdminProviderDistribution:()=>Vx,setAdminProviderFallback:()=>Xx,setAgentScope:()=>Cc,setBootstrapAuthToken:()=>x_,setCachedAuthToken:()=>P_,setConnectionPolicies:()=>L_,setConnectorAuthorizationStrategy:()=>Yi,setConnectorCredential:()=>la,setConnectorCredentialMode:()=>zi,setConnectorName:()=>ea,setConnectorPolicies:()=>Ji,setConnectorSecretBinding:()=>B_,setConnectorSensitive:()=>Qi,setDefaultConnection:()=>Ni,setEnterpriseDemo:()=>Lx,setEnv:()=>Up,setGatewayBudget:()=>Tl,setGatewayRoutingPolicy:()=>bl,setGitHubAppFromExisting:()=>bE,setGitHubAppPat:()=>_E,setImpersonationSession:()=>Kb,setMaintenanceConfig:()=>oE,setMemberSuperAdmin:()=>sx,setMfaRequired:()=>px,setModelDefault:()=>Ic,setPersonalProjectSecret:()=>fi,setProjectModelAccess:()=>cn,setProjectModelEnablement:()=>bP,setProjectOnboardingComplete:()=>Rs,setProjectOnboardingProfile:()=>p_,setProjectPolicies:()=>da,setProjectSecretStrategy:()=>li,setProjectSessionModel:()=>hc,setProjectSessionScope:()=>yc,setProjectSessionSharing:()=>Va,setProjectTriggersActivation:()=>vc,setSavedCopyStore:()=>FM,setSessionOversight:()=>gx,setSessionProviderSecretPool:()=>Ri,settleSessionConnection:()=>GE,setupSSH:()=>vC,shareConnection:()=>Gi,shellActivityGroupLabel:()=>AS,shellExitCode:()=>Dd,shouldAttachImpersonation:()=>bg,shouldHideResponsePart:()=>MI,shouldShowToolPart:()=>gy,shouldSuppressWorkingTurnBusy:()=>SI,showGroupItems:()=>PI,showTurnBusyIndicator:()=>Cd,signInWithPassword:()=>Rr,signInWithProvider:()=>Cr,signInWithSso:()=>$r,signOut:()=>Lr,signUp:()=>kr,skillDocumentPath:()=>pT,skillInputDir:()=>cT,sortSessions:()=>sR,splitUserParts:()=>ak,startApp:()=>dp,startConnectionOAuth2Authorization:()=>O_,startConnectionOAuth2DeviceAuthorization:()=>j_,startConnectorSetupLink:()=>XC,startGitHubAppManifest:()=>hE,startProjectProviderOAuth:()=>rr,startProjectSession:()=>Ee,startSessionWithToken:()=>nE,startTask:()=>pw,stepLabel:()=>wd,stopApp:()=>gp,stopProjectSession:()=>rn,stopSandbox:()=>pC,storeGitHubUserToken:()=>Us,stripAnsi:()=>Sk,stripInstancePrefix:()=>qT,stripTrailingSlashes:()=>le,submitAccessRequest:()=>HC,submitDemoRequest:()=>iE,submitOAuthConsent:()=>YC,submitReviewItem:()=>du,submitSecretSetupLink:()=>eE,subscribeToImpersonation:()=>qb,supabaseClient:()=>e_,syncConnectors:()=>Vi,syncSubscription:()=>TP,systemReload:()=>hv,toDaemonPath:()=>Xe,toInstanceAwarePath:()=>WT,toInternalUrl:()=>ff,toSandboxAbsolutePath:()=>wt,toToolView:()=>jk,toWorkspaceRelative:()=>zp,toolInfo:()=>oo,toolKind:()=>ne,toolViewModel:()=>rh,triggerSandboxUpdate:()=>CC,triggersRequest:()=>Om,turnEndCause:()=>Uh,turnEndNotice:()=>eM,turnHasSteps:()=>nR,turnIsConfirmedActive:()=>AI,turnRetryLabel:()=>_M,unassignTicket:()=>xw,unwrapError:()=>ce,updateAccountAuditWebhook:()=>Nu,updateAccountBranding:()=>es,updateAccountMemberRole:()=>ms,updateAccountName:()=>Jo,updateAgentConfig:()=>xP,updateApp:()=>tp,updateAppAccess:()=>sp,updateAuditWebhook:()=>jx,updateChannelBinding:()=>NP,updateConnectionCredential:()=>Ui,updateEmailPolicy:()=>yl,updateExperimentalFeature:()=>As,updateFeatureFlag:()=>vs,updateGroup:()=>Ll,updateKortixPty:()=>qp,updateMilestone:()=>Vw,updateOAuthClient:()=>ru,updatePassword:()=>Or,updatePatPolicy:()=>Rx,updatePolicy:()=>ex,updateProject:()=>Wt,updateProjectAccess:()=>Ws,updateProjectAgent:()=>Ow,updateProjectDefaultAgent:()=>Mc,updateProjectGroupGrant:()=>Zs,updateProjectSandboxProvider:()=>ks,updateProjectSession:()=>uc,updateProjectTrigger:()=>Sc,updateRole:()=>Yl,updateRolePermissions:()=>Ql,updateSandboxTemplate:()=>ba,updateSessionPolicy:()=>wx,updateSessionReminder:()=>wu,updateTask:()=>uw,updateTemplateWarmPool:()=>u_,updateTicket:()=>bw,updateTicketStatus:()=>_w,updateUserMetadata:()=>Dr,uploadAccountBrandingAsset:()=>ts,uploadAppArtifactArchive:()=>ap,uploadConnectorAttachment:()=>Mi,uploadFile:()=>Rt,uploadPromptAttachment:()=>Jt,uploadSessionAttachment:()=>wp,uploadSlackChannelFile:()=>ul,uploadTimeoutMsForBytes:()=>Pt,upsertCredential:()=>Zw,upsertProjectGitCredential:()=>gi,upsertProjectSecret:()=>ci,upsertSsoProvider:()=>fx,validateProjectManifest:()=>_s,validateReferralCode:()=>BP,validateToken:()=>ys,verifyGatewayProvider:()=>KP,verifyOtp:()=>Tr,verifySsoDomain:()=>hx,wakeEscalationAttemptSummary:()=>mM,wakeEscalationNote:()=>dM,wakeProgressFingerprint:()=>cM,wireIdClock:()=>Ye,wireIdClockAt:()=>ht,wireIdClockDelta:()=>Qe,workingExpiryAtMs:()=>JE,workingTurnDrawsBusyRow:()=>kI,writeActivityGroupLabel:()=>kS,writeFile:()=>wn,wsDomain:()=>po,wsFavicon:()=>AR,wsRootDomain:()=>vR});var Ib={backendUrl:"",getToken:async()=>null},To=null,Wn=null;function Tb(e){Wn=e}function Cb(){return Wn}function Hn(e,t){t?.global!==!1&&(To=e)}function k(){return Wn?.()??To??Ib}function Vn(){return To!==null||Wn?.()!==void 0}function Eb(e){return new Promise(t=>setTimeout(t,e))}async function zn(e,t,n){let r=Math.max(1,t?.attempts??1),o=t?.baseDelayMs??0,s=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(s&&n?.(),o>0&&await Eb(o)),i=await e(),i)return i;return i}var Co=12e4;function Mb(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function lg(e,t,n=Co){let r=e instanceof Request?e.signal:t?.signal;if(Mb(e))return r??void 0;let o=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,o]):r:o}function Yn(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var b=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:o,...s}=n;Object.assign(this,s),r&&(this.name=r),o&&(this.stack=o);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)}},X=class extends b{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},Te=class extends b{constructor(t,n,r,o={}){super(r||n.message||`Billing Error: ${t}`,{...o,status:t,detail:n}),this.name="BillingError"}},Ke=class extends b{constructor(t=431,n,r){let o="Request headers are too large";super(r||n?.message||o,{status:t,detail:{message:n?.message||o,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},Ob="ENDPOINT_RETIRED";function F(e,t){let n=t?` ${t}`:"";return new b(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:Ob})}var Qn="feature_disabled";function ug(e){if(!(e instanceof b)||e.status!==403||e.code!==Qn)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Eo(e){let t=ug(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function Mo(e){let t=ug(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function Ft(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 Te(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 Oo(e){return e instanceof Te}function jo(e){if(!(e instanceof Te))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 pe(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function de(e,t){return new Promise((n,r)=>{let o=()=>{t.removeEventListener("abort",o),r(pe())};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o)),t.aborted&&o()})}function Xn(e,t){return new Promise((n,r)=>{let o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),r(pe())},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.aborted?o():t?.addEventListener("abort",o,{once:!0})})}var pg="request_deadline",jb=/^Request exceeded the \d+s server processing deadline$/,dg=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===pg||jb.test(n),Db="git_mirror_unavailable",$b=/^git mirror is temporarily unavailable$/,Ub=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Db||$b.test(n);async function Lb(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await de(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 pe();return{message:n,data:r}}function Fb(e,t,n){return dg(e,t,n)||Ub(e,t,n)||e===501&&t?.code===Do||e===409&&(t?.code===$o||t?.code===Uo)||e===503&&(t?.code===Lo||t?.code===Fo)}async function gg(e,t,n,r){let{message:o,data:s}=await Lb(e,t),i=new b(o,{status:e.status,response:e,details:s||void 0,data:s,detail:s?.detail,code:dg(e.status,s,o)?pg:s?.code||s?.error_code||s?.detail?.error_code||e.status.toString()});if(e.status===402&&(i=Ft(i)),e.status===403&&s?.code==="account_mfa_required"&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent("kortix:mfa-required"))}catch{}return e.status===431&&(i=new Ke(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&&!Fb(e.status,s,o)&&k().onError?.(i,r),{error:i,success:!1}}var mg="X-Kortix-Impersonate",Ko="kortix.impersonation",qe=null,Jn=!1,No=new Set;function qo(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function fg(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 Nb(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 yg(){for(let e of No)try{e()}catch{}}function hg(){return Jn||(Jn=!0,qe=Nb(qo()?.getItem(Ko)??null)),qe&&!fg(qe)?(Go(),null):qe}function Kb(e){if(Jn=!0,!e){Go();return}qe=e;try{qo()?.setItem(Ko,JSON.stringify(e))}catch{}yg()}function Go(){Jn=!0;let e=qe!==null;qe=null;try{qo()?.removeItem(Ko)}catch{}e&&yg()}function qb(e){return No.add(e),()=>{No.delete(e)}}var Gb=/(^|\/)admin\/(api|analytics)(\/|$)/;function bg(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Gb.test(t)}function Bo(e){if(e!==void 0&&!bg(e))return{};let t=hg();return t?{[mg]:t.grantId}:{}}var Vo=!1;function Pg(e){Vo=e}function xg(){return Vo}function Bb(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function Wo(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Nt(e,t,n){let r=t.toLowerCase();for(let o of Object.keys(e))o.toLowerCase()===r&&delete e[o];e[t]=n}function er(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[o,s]of r.flatMap(Bb))Nt(n,o,s);return n}function Ho(e,t,n){let r={...t},o=k().clientVersion?.trim();o&&!Wo(r,"x-kortix-client-version")&&Nt(r,"X-Kortix-Client-Version",o),Vo&&Nt(r,"x-kortix-admin-bypass","1");for(let[s,i]of Object.entries(Bo(e)))Nt(r,s,i);return Wo(r,"authorization")||Nt(r,"Authorization",`Bearer ${n}`),r}async function Sg(e,t){let n=await Zn();if(!n)throw new X;return{headers:new Headers(Ho(e,er(e,{headers:t}),n)),rejected:()=>k().getToken.invalidate?.(n)}}function Wb(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function _g(e,t,n,r,o){if(t instanceof Request){let a=new Headers(Ho(t.url,er(t,n),r));return e(new Request(t,{headers:a,...o?{signal:o}:{}}))}let s=String(t),i=Ho(s,er(t,n),r);return e(s,{...n,headers:i,...o?{signal:o}:{}})}async function Zn(e){return zn(()=>k().getToken(),e)}async function ot(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:o=Co}=n,s=n.fetch??k().fetch??fetch,i=o===null?(e instanceof Request?e.signal:t.signal)??void 0:lg(e,t,o);if(i?.aborted)throw pe();let a=await(i?de(Zn(),i):Zn());if(!a)throw new X;let c=r&&!Wb(t)&&!Wo(er(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await _g(s,e,t,a,i);if(d.status!==401||!c)return d;k().getToken.invalidate?.(a);let g=await Zn({attempts:2,baseDelayMs:200});return!g||g===a?d:_g(s,p,t,g,i)}var wg=()=>k().backendUrl||"",Hb=new Set([502,503,504]),Vb=e=>Hb.has(e),vg=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},zb=e=>vg(e)||(e??"GET").toUpperCase()==="DELETE",Yb=2,tr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function Pe(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:o=3e4,deadlineCoversBody:s=!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 Qb(e,i,n,r,o,s,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function Qb(e,t,n,r,o,s,i,a){try{if(t.signal?.aborted)throw pe();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},o);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Jb(e,t,c,o,s,i,a);if(p instanceof X)return{error:p,success:!1};if(!p.ok)return await gg(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await de(p.json(),a.activeController.signal):g?.includes("text/")?d=await de(p.text(),a.activeController.signal):d=await de(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return Zb(c,e,t.method,n,r,o,a)}finally{nr(a)}}function nr(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Xb(e,t,n){try{await de(e.arrayBuffer(),t)}catch(r){if(tr(r))throw r}finally{nr(n)}}async function Jb(e,t,n,r,o,s,i){let a=vg(t.method),c=zb(t.method),p=c?Yb+1:1,d;for(let g=0;g<p;g++){g>0&&await Xn(250*2**(g-1),t.signal??void 0);let m=g===0?s:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await de(ot(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 X)return new X;if(i.didTimeout&&tr(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(tr(f)||g===p-1)throw f;continue}if(!a||!Vb(d.status)||g===p-1)return o||nr(i),d;await Xb(d,m.signal,i)}return d}function Zb(e,t,n,r,o,s,i){nr(i);let a=tr(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new b("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(wg(),"")||t;c=new b(`Request timed out after ${Math.round(s/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:s})}else e instanceof Error?(c=new b(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(wg(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&k().onError?.(c,o)):(c=new b(String(e)),r&&k().onError?.(c,o));return{error:c,success:!1}}var xe=()=>k().backendUrl||"",Do="feature_not_supported",$o="model_not_servable",Uo="provision_in_flight",Lo="analytics_unavailable",Fo="accounts_list_unavailable",e_={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let o=new b(r.message||"Database error",{code:r.code,details:r});return k().onError?.(o,t),{error:o,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new b(n.message,{name:n.name||"ApiError",stack:n.stack}):new b(String(n));return k().onError?.(r,t),{error:r,success:!1}}}};async function t_(e,t,n={}){let{timeout:r=3e4,fetch:o}=n,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await ot(`${xe()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:s.signal,credentials:"omit"},{timeoutMs:null,fetch:o})}catch(a){if(a instanceof X)return Yn();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>Pe(`${xe()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>Pe(`${xe()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>Pe(`${xe()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>Pe(`${xe()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>Pe(`${xe()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>Pe(`${xe()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],Pe(`${xe()}${e}`,{...o,method:"POST",body:t,headers:s})},uploadPut:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],Pe(`${xe()}${e}`,{...o,method:"PUT",body:t,headers:s})},postStream:t_};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function zo(e){return e.replace(/\/v1\/?$/,"")}async function st(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=zo(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 Yo(){return u(await l.get("/accounts"))}async function Qo(e){return u(await l.post("/accounts",e))}async function Xo(e){return u(await l.get(`/accounts/${e}`))}async function Jo(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function Zo(e){return u(await l.get(`/accounts/${e}/branding`))}async function es(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function ts(e,t,n,r){let o=new FormData;return o.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,o))}async function ns(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function rs(e){return u(await l.delete(`/accounts/${e}/branding`))}async function os(e){return u(await l.get(`/accounts/${e}/members`))}async function ss(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function is(e){return u(await l.get(`/accounts/${e}/invites`))}async function as(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function cs(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function ls(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function us(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function ps(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}async function ds(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function gs(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function ms(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function fs(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function n_(e){return st(e,"/v1/accounts")}async function ys(){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 r_=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","apps","monitors","reminders","warm_sessions","secrets_egress","pi_worker","pooled_provider_secrets","pi_harness","config_releases","us_region"];async function Ge(){return u(await l.get("/projects"))}async function hs(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 bs(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function _s(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Ps(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function o_(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function qt(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 Gt(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Bt(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function s_(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function xs(e){return u(await l.post("/projects",e))}async function Ss(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function ws(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Ag=200;function i_(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 o=n.length>Ig?`${n.slice(0,Ig)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${o})`,{cause:r})}}async function c_(e,t,n={}){let r=await c.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let l=await r.json().catch(()=>null);throw new b(l?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:l?.code})}let o=r.body?.getReader();if(!o)throw new Error("Provision stream is unavailable on this runtime (no response body)");let s=new TextDecoder,i="",a=null;try{for(;;){let{done:l,value:p}=await o.read();if(l)break;i+=s.decode(p,{stream:!0});let d=i.indexOf(`
3
+ `);try{return JSON.parse(n)}catch(r){let o=n.length>Ag?`${n.slice(0,Ag)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${o})`,{cause:r})}}async function a_(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 b(c?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:c?.code})}let o=r.body?.getReader();if(!o)throw new Error("Provision stream is unavailable on this runtime (no response body)");let s=new TextDecoder,i="",a=null;try{for(;;){let{done:c,value:p}=await o.read();if(c)break;i+=s.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=a_(g);if(m){if(t(m),m.type==="error")throw new b(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{o.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function l_(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Vt(e,t){return u(await c.patch(`/projects/${e}`,t))}async function ks(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Rs(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function Is(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function u_(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function p_(e,t){throw q("updateTemplateWarmPool")}async function Ts(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function d_(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function zt(e){return u(await c.delete(`/projects/${e}`))}async function g_(e,t){return at(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function m_(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Qo(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 o=await r.json().catch(()=>null);return o?.project_id?{ok:!0,project:o}:{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 Cs(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function Es(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Ms(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Os(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function js(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Ds(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let o=n?.search?.trim();return o&&r.set("search",o),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await c.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function $s(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await c.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function Us(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function Ls(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Fs(e){return u(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function Ns(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await c.delete(`/projects/github/installation?${n.toString()}`))}async function Ks(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function qs(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await c.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function f_(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Gs(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function Bs(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Ws(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Hs(e){return u(await c.get(`/projects/${e}/access`))}async function Vs(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function zs(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function y_(e){return"status"in e&&e.status==="invited"}async function Ys(e,t,n,r){return u(await c.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Qs(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function Xs(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Js(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Zs(e){return u(await c.get(`/projects/${e}/group-grants`))}async function ei(e,t,n,r){return u(await c.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function ti(e,t,n,r){return u(await c.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function ni(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function ri(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function oi(e,t){return u(await c.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function si(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function ii(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function ai(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function ci(e,t,n,r={}){let o=r.note?.trim();return u(await c.post(`/projects/${e}/approvals/${t}`,{decision:n,...o?{note:o}:{}}))}async function li(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function ui(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function pi(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function di(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function gi(e){return u(await c.get(`/projects/${e}/oauth`)).items??[]}async function rr(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function or(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function mi(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var h_=2e3,b_=3e3,__=10*6e4;async function P_(e){let{projectId:t,provider:n,input:r,onChallenge:o,isCancelled:s,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,l=()=>s?.()??!1,p=await rr(t,n,r);if(l())return{status:"cancelled"};o?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(h_,p.interval_ms||b_),g=p.expires_at||a()+__;for(;!l()&&a()<g;){if(await i(d),l())return{status:"cancelled"};let m;try{m=await or(t,n,p.flow_id)}catch{continue}if(l())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 l()?{status:"cancelled"}:{status:"expired"}}async function fi(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function yi(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function hi(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function bi(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var _i=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Yt=(e,t)=>`${_i(e)}/${encodeURIComponent(t)}`,Tg=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Pi(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${_i(e)}${n}`))}async function xi(e,t){return u(await c.post(_i(e),t))}async function Si(e,t,n){return u(await c.put(`${Yt(e,t)}/value`,{value:n}))}async function wi(e,t){return u(await c.delete(Yt(e,t)))}async function vi(e,t,n,r){return u(await c.put(`${Yt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function Ai(e,t,n,r){return u(await c.delete(`${Yt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function ki(e,t,n,r){return u(await c.put(`${Yt(e,t)}/access`,{mode:n,user_ids:r}))}async function Ri(e,t,n){return u(await c.get(Tg(e,t,n)))}async function Ii(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function Ti(e,t,n,r){return u(await c.put(Tg(e,t,n),{secret_ids:r}))}async function sr(){return k().getToken()}async function ct(e){return zn(()=>k().getToken(),e,ir)}function ir(){}function x_(e){}function S_(e){}async function lt(){return sr()}async function w_(e){return ct(e)}async function j(e,t,n){try{return await it(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof X)return Yn();throw r}}function ar(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Qt(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`${ar(e,"catalog")}${r}`)).connectors??[]}async function cr(e){let t=[];for(let n of await Qt(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 Ci(e,t="",n={}){let r=t.trim().toLowerCase(),o=r.split(/\s+/).filter(Boolean),s=[],i=[];for(let a of await cr(e)){let l=`${a.tool} ${a.description}`.toLowerCase();!r||l.includes(r)?s.push(a):o.every(p=>l.includes(p))&&i.push(a)}return[...s,...i].slice(0,n.limit??20)}async function Ei(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let o=(await Qt(e,{slug:r,includeSchemas:!0})).find(s=>s.slug===r);if(!o)return null;for(let s of o.actions){let i=`${o.slug}.${s.path}`;if(i===t)return{tool:i,connector:o.slug,action:s.path,risk:s.risk,description:s.description||s.name,inputSchema:s.inputSchema}}return null}function v_(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}}async function Mi(e,t,n={},r={}){let{connector:o,action:s}=v_(t),i=r.account?.trim(),a=r.approvalContext?.trim();return u(await c.post(ar(e,"call"),{connector:o,action:s,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}}))}async function Oi(e,t){let n=await c.get(ar(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function A_(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 k_(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 ji(e,t,n){let r=n.filename.trim(),o=n.contentType.trim();if(!r)throw new Error("filename is required");if(!o)throw new Error("contentType is required");let s={"Content-Type":o,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(s["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(s["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=k_(k().backendUrl),a=ar(e,"attachments"),l=await j(`${i}${a}`,{method:"POST",headers:s,body:t},{timeoutMs:6e4}),p=await l.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!l.ok)throw new b(A_(d,l.status),{status:l.status,code:String(d&&typeof d=="object"?d.code??l.status:l.status),details:d,response:l,endpoint:a});return d}function R_(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 Di(e){return u(await c.get(`/projects/${e}/connections`))}async function $i(e){return u(await c.get(`/projects/${e}/connections/all`))}async function Ui(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function Li(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function Fi(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function we(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function I_(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function T_(e,t,n){return u(await c.put(we(e,t,"application"),n))}async function C_(e,t){return u(await c.get(we(e,t,"application")))}async function E_(e,t,n){return u(await c.post(we(e,t,"discover"),n))}async function M_(e,t,n={}){return u(await c.post(we(e,t,"discover-resource"),n))}async function O_(e,t,n){return u(await c.post(we(e,t,"register"),n))}async function j_(e,t,n){return u(await c.post(we(e,t,"authorize"),n))}async function D_(e,t,n){return u(await c.post(we(e,t,"device"),n))}async function $_(e,t,n){return u(await c.post(we(e,t,`device/${encodeURIComponent(n)}`),{}))}async function U_(e,t){return u(await c.get(we(e,t,"status")))}async function Ni(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Ki(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function qi(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function Gi(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Bi(e,t){return u(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Wi(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Hi(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function Vi(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function zi(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await c.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function Yi(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Qi(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Xi(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Ji(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Zi(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function ea(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function L_(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function F_(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function ta(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function na(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Cg(e,t,n={}){return u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,n.owner?{owner:n.owner}:{}))}var ra=Cg;async function N_(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function oa(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function sa(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function ia(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function aa(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/apps${s?`?${s}`:""}`))}async function ca(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 c.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function K_(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(),o=u(await c.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in o)return o;let s=o.cursor?.trim()||void 0;return{provider:"composio",toolkits:o.items,nextCursor:s,hasMore:!!s}}async function q_(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 c.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function lr(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await c.get(`/connectors/projects/${e}/discover/connectors${s?`?${s}`:""}`))}async function la(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 c.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function ur(e,t){let n=new URLSearchParams({id:t});return u(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var G_=lr,B_=ur;async function ua(){return u(await c.get("/connectors/connect-status"))}async function pa(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function W_(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Eg(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var da=Eg;async function ga(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function ma(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function fa(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function ya(e){return u(await c.get(`/projects/${e}/snapshots`))}async function Xt(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function ha(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function ba(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function _a(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function Pa(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function xa(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Sa(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function wa(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function va(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 c.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function Aa(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 c.get(`/projects/${e}/files/search?${r.toString()}`))}async function ka(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await c.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}async function Ra(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"",s=await ct(),i=`${k().backendUrl||""}/projects/${e}/files/archive${o}`,a=await fetch(i,{method:"GET",headers:s?{Authorization:`Bearer ${s}`}:{}});if(!a.ok){let l=await a.text().catch(()=>"");throw new Error(l||`Failed to download (HTTP ${a.status})`)}return await a.blob()}var Ia=52428800,H_=104857600,Mg=20;var dr=e=>`/projects/${encodeURIComponent(e)}/attachments`,gr={showErrors:!1,deadlineCoversBody:!0},Og=3e4,V_=12e4,z_=6e4,Y_=5*6e4,Q_=6e4,X_=6e4;function pr(){return new b("Request aborted",{name:"AbortError",code:"ABORTED"})}function Jt(e){if(e?.aborted)throw pr()}function J_(e){return!(e instanceof b)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Zt(e,t,n=!1){let r;for(let o=0;;o++){Jt(t);try{return await e()}catch(s){let i=n&&s instanceof b&&s.status===409&&s.code==="attachment_processing";if(t?.aborted||!(J_(s)||i))throw s;r??=Date.now()+(n?Y_:z_);let a=Math.min(8e3,500*2**o)*(.5+Math.random()/2);if(Date.now()+a>=r)throw s;try{await Xn(a,t)}catch{throw Jt(t),s}}}}function Z_(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function Ta(e,t,n){let r=e?.upload,o=e?.received_bytes,s=Number.isSafeInteger(o)&&o>=0&&o<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&Z_(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(o===0||o===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(o===t.size||o%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!s||!i)throw new Error("Invalid attachment upload handle");return e}async function jg(e,t,n,r){return u(await c.post(dr(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...gr,signal:n,timeout:Og}),"Failed to start attachment upload")}async function Dg(e,t,n,r){let o=Ta({...await Zt(()=>jg(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(o),o}function $g(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new b(r,{status:e,details:n,code:String(n?.statusCode??e)})}function eP(e){if(!(e instanceof b))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function tP(e,t,n,r){return new Promise((o,s)=>{let i=new e,a=0,l=!1,p,d=f=>{l||(l=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?s(f):o())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new b("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},Q_)},m=()=>{d(pr()),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($g(i.status,i.responseText))},i.onerror=()=>d(new b("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(pr()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function nP(e,t,n){let r=k().fetch??fetch,o;try{o=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(s){throw n.signal?.aborted||s instanceof Error&&s.name==="AbortError"?pr():new b(s instanceof Error?s.message:String(s),{name:s instanceof Error?s.name:"TypeError"})}if(!o.ok)throw $g(o.status,await o.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function rP(e,t,n){Jt(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?tP(r,e,t,n):nP(e,t,n)}async function oP(e,t,n,r){let o=n,s=!1;for(r.onProgress?.(0,t.size);o.upload.kind==="direct";){let i=o.upload;try{await Zt(()=>rP(i,t,r),r.signal)}catch(a){let l=eP(a);if(l!==409){if(s||!(l===400||l===401||l===403))throw a;s=!0,o=await Dg(e,t,o,r);continue}}return o={...o,received_bytes:t.size},r.onUpload?.(o),o}return Ug(e,t,o,r)}async function Ug(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let o=n.upload.chunk_size,s=`${dr(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Jt(r.signal);let a=i.received_bytes,l=Math.min(a+o,t.size),p=t.slice(a,l),d=await Zt(async()=>u(await c.putRaw(`${s}/chunks/${a/o}`,p,{...gr,signal:r.signal,timeout:Og}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==l)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:l},r.onUpload?.(i),r.onProgress?.(l,t.size)}return i}async function en(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");Jt(n.signal);let r=n.resume?Ta({...n.resume},t):Ta({...await Zt(()=>jg(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()<X_&&(r=await Dg(e,t,r,n)),r=r.upload.kind==="direct"?await oP(e,t,r,n):await Ug(e,t,r,n)),n.onProcessing?.();let o=`${dr(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Zt(async()=>u(await c.post(`${o}/complete`,{},{...gr,signal:n.signal,timeout:V_}),"Failed to complete attachment upload"),n.signal,!0)}catch(s){throw r.upload.kind==="direct"&&s instanceof b&&s.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),s}}async function ut(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${dr(e)}/${encodeURIComponent(t)}`,{...gr,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function Ca(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 c.get(`/projects/${e}/branches${r}`))}async function Ea(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 c.get(`/projects/${e}/commits${r}`))}async function Ma(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Oa(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let o=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${o}`))}async function ja(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 c.get(`/projects/${e}/files/history?${r.toString()}`))}async function Da(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await c.get(`/projects/${e}/version-diff?${n.toString()}`))}async function $a(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 o=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/change-requests${o}`,{showErrors:!1,timeout:15e3}))}async function Ua(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function La(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function Fa(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function Na(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function Ka(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function qa(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Ga(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Ba(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Wa(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}var Ha=new Set;function tn(e){e&&Ha.add(e)}function Va(e){return!!e&&Ha.has(e)}function sP(e){e&&Ha.delete(e)}function iP(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 aP=50,Lg=200,cP=Lg;function Fg(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 za(e,t){let n=await c.get(`/projects/${e}/sessions${Fg(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function We(e,t){return u(await c.get(`/projects/${e}/sessions${Fg(t)}`))}async function Ya(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Qa(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}function lP(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 Xa(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function Ja(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Za(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function ec(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function He(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||tn(n?.session_id),n}async function tc(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await c.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||tn(r.session.session_id),r}async function nc(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return tn(n.session_id),n}async function nn(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function rc(e,t,n,r){let o=new URLSearchParams;n&&o.set("limit",String(n)),r?.cursor&&o.set("cursor",r.cursor),r?.includeEvents!=null&&o.set("include_events",String(r.includeEvents));let s=o.toString();return u(await c.get(`/projects/${e}/sessions/${t}/audit${s?`?${s}`:""}`,{showErrors:r?.showErrors}))}async function oc(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 o=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/transcript${o?`?${o}`:""}`))}async function sc(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 c.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function ic(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/turn`))}async function uP(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let o=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/snapshot${o?`?${o}`:""}`,{signal:n?.signal,showErrors:!1}))}async function rn(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...n.placement?{placement:n.placement}:{},...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 ac(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function cc(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function lc(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function uc(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function pc(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function dc(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function gc(e,t){return u(await c.delete(`/projects/${e}/sessions/${t}`))}async function on(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function sn(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}))}async function mc(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function pP(e){let t=e.split(`
7
+ `);let m=i_(g);if(m){if(t(m),m.type==="error")throw new b(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{o.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function c_(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Wt(e,t){return u(await l.patch(`/projects/${e}`,t))}async function vs(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function As(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function ks(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function l_(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function u_(e,t){throw F("updateTemplateWarmPool")}async function Rs(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function p_(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Ht(e){return u(await l.delete(`/projects/${e}`))}async function d_(e,t){return st(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function g_(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=zo(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 o=await r.json().catch(()=>null);return o?.project_id?{ok:!0,project:o}:{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 Is(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function Ts(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Cs(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Es(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Ms(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Os(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let o=n?.search?.trim();return o&&r.set("search",o),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function js(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 Ds(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function $s(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Us(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function Ls(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 Fs(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function Ns(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await l.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function m_(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Ks(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function qs(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Gs(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Bs(e){return u(await l.get(`/projects/${e}/access`))}async function Ws(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function Hs(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function f_(e){return"status"in e&&e.status==="invited"}async function Vs(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 zs(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function Ys(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Qs(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Xs(e){return u(await l.get(`/projects/${e}/group-grants`))}async function Js(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 Zs(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 ei(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function ti(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function ni(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 ri(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function oi(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function si(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function ii(e,t,n,r={}){let o=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...o?{note:o}:{}}))}async function ai(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function ci(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function li(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function ui(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function pi(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function rr(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 or(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function di(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var y_=2e3,h_=3e3,b_=10*6e4;async function __(e){let{projectId:t,provider:n,input:r,onChallenge:o,isCancelled:s,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,c=()=>s?.()??!1,p=await rr(t,n,r);if(c())return{status:"cancelled"};o?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(y_,p.interval_ms||h_),g=p.expires_at||a()+b_;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await or(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 gi(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function mi(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function fi(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function yi(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var hi=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Vt=(e,t)=>`${hi(e)}/${encodeURIComponent(t)}`,kg=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function bi(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${hi(e)}${n}`))}async function _i(e,t){return u(await l.post(hi(e),t))}async function Pi(e,t,n){return u(await l.put(`${Vt(e,t)}/value`,{value:n}))}async function xi(e,t){return u(await l.delete(Vt(e,t)))}async function Si(e,t,n,r){return u(await l.put(`${Vt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function wi(e,t,n,r){return u(await l.delete(`${Vt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function vi(e,t,n,r){return u(await l.put(`${Vt(e,t)}/access`,{mode:n,user_ids:r}))}async function Ai(e,t,n){return u(await l.get(kg(e,t,n)))}async function ki(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function Ri(e,t,n,r){return u(await l.put(kg(e,t,n),{secret_ids:r}))}async function sr(){return k().getToken()}async function it(e){return zn(()=>k().getToken(),e,ir)}function ir(){}function P_(e){}function x_(e){}async function at(){return sr()}async function S_(e){return it(e)}async function j(e,t,n){try{return await ot(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof X)return Yn();throw r}}function ar(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function zt(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`${ar(e,"catalog")}${r}`)).connectors??[]}async function cr(e){let t=[];for(let n of await zt(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 Ii(e,t="",n={}){let r=t.trim().toLowerCase(),o=r.split(/\s+/).filter(Boolean),s=[],i=[];for(let a of await cr(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?s.push(a):o.every(p=>c.includes(p))&&i.push(a)}return[...s,...i].slice(0,n.limit??20)}async function Ti(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let o=(await zt(e,{slug:r,includeSchemas:!0})).find(s=>s.slug===r);if(!o)return null;for(let s of o.actions){let i=`${o.slug}.${s.path}`;if(i===t)return{tool:i,connector:o.slug,action:s.path,risk:s.risk,description:s.description||s.name,inputSchema:s.inputSchema}}return null}function w_(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}}async function Ci(e,t,n={},r={}){let{connector:o,action:s}=w_(t),i=r.account?.trim(),a=r.approvalContext?.trim();return u(await l.post(ar(e,"call"),{connector:o,action:s,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}}))}async function Ei(e,t){let n=await l.get(ar(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function v_(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 A_(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 Mi(e,t,n){let r=n.filename.trim(),o=n.contentType.trim();if(!r)throw new Error("filename is required");if(!o)throw new Error("contentType is required");let s={"Content-Type":o,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(s["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(s["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=A_(k().backendUrl),a=ar(e,"attachments"),c=await j(`${i}${a}`,{method:"POST",headers:s,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 b(v_(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 k_(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 Oi(e){return u(await l.get(`/projects/${e}/connections`))}async function ji(e){return u(await l.get(`/projects/${e}/connections/all`))}async function Di(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function $i(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function Ui(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function Se(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function R_(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function I_(e,t,n){return u(await l.put(Se(e,t,"application"),n))}async function T_(e,t){return u(await l.get(Se(e,t,"application")))}async function C_(e,t,n){return u(await l.post(Se(e,t,"discover"),n))}async function E_(e,t,n={}){return u(await l.post(Se(e,t,"discover-resource"),n))}async function M_(e,t,n){return u(await l.post(Se(e,t,"register"),n))}async function O_(e,t,n){return u(await l.post(Se(e,t,"authorize"),n))}async function j_(e,t,n){return u(await l.post(Se(e,t,"device"),n))}async function D_(e,t,n){return u(await l.post(Se(e,t,`device/${encodeURIComponent(n)}`),{}))}async function $_(e,t){return u(await l.get(Se(e,t,"status")))}async function Li(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Fi(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Ni(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function Ki(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function qi(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Gi(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Bi(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function Wi(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Hi(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 Vi(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function zi(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Yi(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Qi(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Xi(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Ji(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function U_(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function L_(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Zi(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function ea(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Rg(e,t,n={}){return u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,n.owner?{owner:n.owner}:{}))}var ta=Rg;async function F_(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function na(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function ra(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function oa(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function sa(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/apps${s?`?${s}`:""}`))}async function ia(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}/pipedream/sections${r?`?${r}`:""}`))}async function N_(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(),o=u(await l.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in o)return o;let s=o.cursor?.trim()||void 0;return{provider:"composio",toolkits:o.items,nextCursor:s,hasMore:!!s}}async function K_(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 lr(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await l.get(`/connectors/projects/${e}/discover/connectors${s?`?${s}`:""}`))}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}/discover/sections${r?`?${r}`:""}`))}async function ur(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var q_=lr,G_=ur;async function ca(){return u(await l.get("/connectors/connect-status"))}async function la(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 B_(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Ig(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 ua=Ig;async function pa(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function da(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function ga(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function ma(e){return u(await l.get(`/projects/${e}/snapshots`))}async function Yt(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function fa(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function ya(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function ha(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function ba(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function _a(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Pa(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function xa(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Sa(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 wa(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 va(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}))}async function Aa(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"",s=await it(),i=`${k().backendUrl||""}/projects/${e}/files/archive${o}`,a=await fetch(i,{method:"GET",headers:s?{Authorization:`Bearer ${s}`}:{}});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(c||`Failed to download (HTTP ${a.status})`)}return await a.blob()}var ka=52428800,W_=104857600,Tg=20;var dr=e=>`/projects/${encodeURIComponent(e)}/attachments`,gr={showErrors:!1,deadlineCoversBody:!0},Cg=3e4,H_=12e4,V_=6e4,z_=5*6e4,Y_=6e4,Q_=6e4;function pr(){return new b("Request aborted",{name:"AbortError",code:"ABORTED"})}function Qt(e){if(e?.aborted)throw pr()}function X_(e){return!(e instanceof b)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Xt(e,t,n=!1){let r;for(let o=0;;o++){Qt(t);try{return await e()}catch(s){let i=n&&s instanceof b&&s.status===409&&s.code==="attachment_processing";if(t?.aborted||!(X_(s)||i))throw s;r??=Date.now()+(n?z_:V_);let a=Math.min(8e3,500*2**o)*(.5+Math.random()/2);if(Date.now()+a>=r)throw s;try{await Xn(a,t)}catch{throw Qt(t),s}}}}function J_(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function Ra(e,t,n){let r=e?.upload,o=e?.received_bytes,s=Number.isSafeInteger(o)&&o>=0&&o<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&J_(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(o===0||o===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(o===t.size||o%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!s||!i)throw new Error("Invalid attachment upload handle");return e}async function Eg(e,t,n,r){return u(await l.post(dr(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...gr,signal:n,timeout:Cg}),"Failed to start attachment upload")}async function Mg(e,t,n,r){let o=Ra({...await Xt(()=>Eg(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(o),o}function Og(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new b(r,{status:e,details:n,code:String(n?.statusCode??e)})}function Z_(e){if(!(e instanceof b))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function eP(e,t,n,r){return new Promise((o,s)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?s(f):o())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new b("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},Y_)},m=()=>{d(pr()),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(Og(i.status,i.responseText))},i.onerror=()=>d(new b("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(pr()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function tP(e,t,n){let r=k().fetch??fetch,o;try{o=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(s){throw n.signal?.aborted||s instanceof Error&&s.name==="AbortError"?pr():new b(s instanceof Error?s.message:String(s),{name:s instanceof Error?s.name:"TypeError"})}if(!o.ok)throw Og(o.status,await o.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function nP(e,t,n){Qt(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?eP(r,e,t,n):tP(e,t,n)}async function rP(e,t,n,r){let o=n,s=!1;for(r.onProgress?.(0,t.size);o.upload.kind==="direct";){let i=o.upload;try{await Xt(()=>nP(i,t,r),r.signal)}catch(a){let c=Z_(a);if(c!==409){if(s||!(c===400||c===401||c===403))throw a;s=!0,o=await Mg(e,t,o,r);continue}}return o={...o,received_bytes:t.size},r.onUpload?.(o),o}return jg(e,t,o,r)}async function jg(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let o=n.upload.chunk_size,s=`${dr(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Qt(r.signal);let a=i.received_bytes,c=Math.min(a+o,t.size),p=t.slice(a,c),d=await Xt(async()=>u(await l.putRaw(`${s}/chunks/${a/o}`,p,{...gr,signal:r.signal,timeout:Cg}),"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 Jt(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");Qt(n.signal);let r=n.resume?Ra({...n.resume},t):Ra({...await Xt(()=>Eg(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()<Q_&&(r=await Mg(e,t,r,n)),r=r.upload.kind==="direct"?await rP(e,t,r,n):await jg(e,t,r,n)),n.onProcessing?.();let o=`${dr(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Xt(async()=>u(await l.post(`${o}/complete`,{},{...gr,signal:n.signal,timeout:H_}),"Failed to complete attachment upload"),n.signal,!0)}catch(s){throw r.upload.kind==="direct"&&s instanceof b&&s.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),s}}async function ct(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${dr(e)}/${encodeURIComponent(t)}`,{...gr,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function Ia(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 Ta(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 Ca(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Ea(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${o}`))}async function Ma(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 Oa(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 ja(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 o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${o}`,{showErrors:!1,timeout:15e3}))}async function Da(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function $a(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function Ua(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function La(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function Fa(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Na(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Ka(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function qa(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Ga(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}var Ba=new Set;function Zt(e){e&&Ba.add(e)}function Wa(e){return!!e&&Ba.has(e)}function oP(e){e&&Ba.delete(e)}function sP(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 iP=50,Dg=200,aP=Dg;function $g(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 Ha(e,t){let n=await l.get(`/projects/${e}/sessions${$g(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Be(e,t){return u(await l.get(`/projects/${e}/sessions${$g(t)}`))}async function Va(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function za(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}function cP(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 lP(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 Ya(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function Qa(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Xa(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Ja(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function We(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||Zt(n?.session_id),n}async function Za(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||Zt(r.session.session_id),r}async function ec(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Zt(n.session_id),n}async function en(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function tc(e,t,n,r){let o=new URLSearchParams;n&&o.set("limit",String(n)),r?.cursor&&o.set("cursor",r.cursor),r?.includeEvents!=null&&o.set("include_events",String(r.includeEvents));let s=o.toString();return u(await l.get(`/projects/${e}/sessions/${t}/audit${s?`?${s}`:""}`,{showErrors:r?.showErrors}))}async function nc(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let o=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/transcript${o?`?${o}`:""}`))}async function rc(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 oc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/turn`))}async function uP(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let o=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${o?`?${o}`:""}`,{signal:n?.signal,showErrors:!1}))}async function tn(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...n.placement?{placement:n.placement}:{},...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 sc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function ic(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function ac(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function cc(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function lc(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function uc(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function pc(e,t){return u(await l.delete(`/projects/${e}/sessions/${t}`))}async function nn(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function rn(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}))}async function dc(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function pP(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 fc(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function yc(e,t,n,r,o={}){let s=await c.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,o);if(!s.ok){let d=await s.json().catch(()=>null);throw new b(d?.error||`Reload failed: HTTP ${s.status}`,{status:s.status,code:d?.code,data:d})}let i=s.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,l="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;l+=a.decode(g,{stream:!0});let m=l.indexOf(`
9
+ `))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function gc(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function mc(e,t,n,r,o={}){let s=await l.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,o);if(!s.ok){let d=await s.json().catch(()=>null);throw new b(d?.error||`Reload failed: HTTP ${s.status}`,{status:s.status,code:d?.code,data:d})}let i=s.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,c="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;c+=a.decode(g,{stream:!0});let m=c.indexOf(`
10
10
 
11
- `);for(;m!==-1;){let f=l.slice(0,m);l=l.slice(m+2),m=l.indexOf(`
11
+ `);for(;m!==-1;){let f=c.slice(0,m);c=c.slice(m+2),m=c.indexOf(`
12
12
 
13
- `);let h=pP(f);if(h){if(r(h),h.type==="error")throw new b(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function hc(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function bc(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function _c(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Pc(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function xc(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function Sc(e){return u(await c.get(`/projects/${e}/triggers`))}async function wc(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function vc(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function Ac(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function kc(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function Rc(e,t){return u(await c.post(`/projects/${e}/triggers/${t}/fire`,{}))}var Me=new Map;function Ic(e,t){return`${e}::${t}`}function Ng(e,t){Me.delete(e),Me.set(e,t)}function Kg(e,t){let n=Ic(e,t),r=Me.get(n);return r&&Ng(n,r),r}function qg(e,t,n){let r=Ic(e,t);if(!Me.has(r)&&Me.size>=512){let o=Me.keys().next().value;o!==void 0&&Me.delete(o)}Ng(r,n)}function Gg(e,t){Me.delete(Ic(e,t))}function dP(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function an(){return dP(k().backendUrl||"http://localhost:8008/v1")}function Bg(){let e=k().sandboxId;return e?`${an()}/p/${e}/8000`:""}function gP(e,t=8e3){return`${an()}/p/${e}/${t}`}function pt(e,t=8e3){return gP(e,t)}function mP(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 mr=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 fP(e){return e instanceof Error&&e.name==="SessionStartError"}function yP(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,o=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new mr(o,{status:n,code:r,terminal:!0}):null}async function Oe(e,t,n){let r=typeof n=="number"?n:n?.waitMs,o=typeof n=="number"?void 0:n?.repositoryMode,s=new URLSearchParams;r&&r>0&&s.set("wait_ms",String(Math.floor(r))),o&&s.set("repository_mode",o);let i=s.size>0?`?${s.toString()}`:"",a=await c.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1});if(!a.success||!a.data){let g=yP(a.error);if(g&&!(g.status===404&&Va(t)))throw g;return null}let l=a.data,p=l.sandbox?.external_id,d=l.runtime_session_id??l.opencode_session_id;return l.stage==="ready"&&p&&d&&qg(e,t,{runtimeSessionId:d,opencodeSessionId:d,runtimeUrl:pt(p),sandboxId:p}),l}function hP(e,t){return["session-start",e,t]}async function Tc(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function Cc(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function Ec(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await c.delete(`/projects/${e}/model-defaults?${n}`))}async function bP(e,t){return u(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Wg(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function _P(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function fr(e){let t=e.connectors_required?Wg(e.connectors_required):void 0,n=e.connectors_personal?Wg(e.connectors_personal):void 0;if(t&&n&&!_P(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 Mc(e,t,n){let r=fr(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function PP(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Oc(n.block):null}}async function xP(e,t,n){let r=Oc(n,!0),o=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...o,block:o.block?Oc(o.block):null}}function Oc(e,t=!1){let n=fr(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 SP(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function jc(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}function Dc(){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 wP(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function vP(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??Dc(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),o=(n.tier?.display_name||"").trim()||r;return{family:wP(r),label:o,sublabel:null,isGrandfathered:!1}}async function Hg(e){let t=await c.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?Dc():t.data}function Vg(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 $c(e){return Hg(`/billing/account-state${Vg(e)}`)}async function Uc(e){return Hg(`/billing/account-state/minimal${Vg(e)}`)}async function Lc(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 c.get(`/billing/transactions${n?`?${n}`:""}`))}async function Fc(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 c.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Nc(){return u(await c.get("/billing/credit-breakdown"))}async function Kc(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function qc(){return u(await c.get("/billing/tier-configurations"))}async function AP(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return at(e,`/v1/billing/account-state${t}`)}async function Gc(e){return u(await c.post("/billing/create-checkout-session",{account_id:e.accountId,tier_key:e.tierKey,success_url:e.successUrl,cancel_url:e.cancelUrl,commitment_type:e.commitmentType,locale:e.locale,server_type:e.serverType,location:e.location}),"Failed to create checkout session")}async function Bc(e,t){return u(await c.post("/billing/confirm-checkout-session",{account_id:t,session_id:e}),"Failed to confirm checkout session")}async function Wc(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Hc(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Vc(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function zc(e,t,n){return u(await c.post("/billing/schedule-downgrade",{account_id:n,target_tier_key:e,commitment_type:t}),"Failed to schedule downgrade")}async function Yc(e){return u(await c.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function Qc(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),u(await c.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function Xc(e){return u(await c.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Jc(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function Zc(e){return u(await c.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function kP(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function RP(e){return u(await c.post("/billing/create-per-seat-checkout",{account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale}),"Failed to create per-seat checkout")}async function IP(e){return u(await c.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function TP(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function el(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 c.get(`/usage${n?`?${n}`:""}`))}function nl(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function yr(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function hr(e){return e.size>0?`?${e}`:""}async function rl(e={}){let t=new URLSearchParams;return nl(t,e),e.ownerId&&t.set("owner_id",e.ownerId),yr(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 c.get(`/usage/session-costs${hr(t)}`))}async function cn(e,t={}){let n=new URLSearchParams;return nl(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${hr(n)}`))}async function CP(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),yr(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 c.get(`/usage/cost-by-project${hr(t)}`))}async function EP(e={}){let t=new URLSearchParams;return nl(t,e),e.sessionId&&t.set("session_id",e.sessionId),yr(t,e),u(await c.get(`/usage/cost-summary${hr(t)}`))}function tl(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 o=t;o.ownerId&&n.set("owner_id",o.ownerId)}yr(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 MP(e,t={}){let n=tl(e==="projects"?"projects":"sessions",t),r=await ct(),o=await fetch(n,{method:"GET",headers:r?{Authorization:`Bearer ${r}`}:{}});if(!o.ok){let l=await o.text().catch(()=>"");throw new Error(l||`Failed to export CSV (HTTP ${o.status})`)}let s=o.headers.get("x-kortix-row-cap"),i=s!=null?Number(s):NaN;return{blob:await o.blob(),rowCap:Number.isFinite(i)?i:null}}async function zg(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function OP(e){return zg("slack",e)}function jP(e){return zg("teams",e)}async function Yg(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function DP(e){return Yg("slack",e)}function $P(e){return Yg("teams",e)}async function ol(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function sl(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var UP={oauth_available:!1,install_url:null};async function il(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?UP:t.data}async function Qg(e,t,n){return u(await c.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function al(e,t){return Qg("slack",e,t)}function cl(e,t){return Qg("teams",e,t)}async function ll(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function ul(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function pl(e,t){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function dl(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function gl(e){let t=e.connectionId??e.connection_id??null,n=e.connectorSlug??e.connector_slug??e.connectionSlug??e.connection_slug??"kortix_email";return{...e,connectionId:t,connectorSlug:n}}var LP={provider:"agentmail",managed_available:!1};async function ml(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?gl(r.data):null}async function fl(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?LP:t.data}async function yl(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return gl(n)}async function hl(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function bl(e,t,n){let r=u(await c.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return gl(r)}async function FP(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function NP(e,t,n){return u(await c.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function _l(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Pl(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function xl(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Sl(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function wl(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 c.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function vl(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Al(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function kl(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Rl(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Il(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Tl(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Cl(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function El(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Ml(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Ol(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function jl(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Dl(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function $l(e,t,n,r,o){return u(await c.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...o&&Object.keys(o).length?{generationConfig:o}:{}}),"Gateway request failed")}async function KP(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function qP(){throw q("getReferralCode")}async function GP(){throw q("refreshReferralCode")}async function BP(e){throw q("validateReferralCode")}async function WP(){throw q("getReferralStats")}async function HP(e={}){throw q("listReferrals")}async function VP(e){throw q("sendReferralEmails")}function M(e){return c.get(e,{showErrors:!1})}function S(e){return u(e,"Unexpected empty response")}async function Ul(e){return S(await M(`/accounts/${e}/iam/groups`)).groups}async function Ll(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}`))}async function Fl(e,t){return S(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Nl(e,t,n){return S(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Kl(e,t){return S(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function ql(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Gl(e,t,n){return S(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function zP(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Bl(e,t,n){return S(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function YP(e,t){return S(await M(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function QP(e,t){let n=S(await M(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function je(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}async function XP(e,t={}){let n=je({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return S(await M(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function JP(e,t={}){let n=je({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return S(await M(`/accounts/${e}/iam/policies${n}`)).policies}async function ZP(e,t){return S(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function ex(e,t,n){return S(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function tx(e,t){return S(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function nx(e,t){return S(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function rx(e,t){return S(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Wl(e){return S(await M(`/accounts/${e}/iam/roles`)).roles}async function Hl(e){return S(await M(`/accounts/${e}/iam/agent-identities`)).agents}async function Vl(e){return S(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function zl(e,t){return S(await M(`/accounts/${e}/iam/roles/${t}/permissions`))}async function ox(e){return S(await M(`/accounts/${e}/iam/actions`)).actions}async function Yl(e,t){return S(await M(`/accounts/${e}/iam/roles/${t}/usage`))}async function Ql(e,t){return S(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Xl(e,t,n){return S(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Jl(e,t,n){return S(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Zl(e,t){return S(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function sx(e,t,n){return S(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function ix(e){return S(await M(`/accounts/${e}/iam/scim/tokens`)).tokens}async function ax(e,t){return S(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function cx(e,t){return S(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function lx(e){return S(await M(`/accounts/${e}/iam/mfa-required`))}async function ux(e){return S(await M(`/accounts/${e}/iam/mfa-required/preview`))}async function px(e,t){return S(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function dx(e){return S(await M(`/accounts/${e}/iam/session-oversight`))}async function gx(e,t){return S(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function mx(e){return S(await M(`/accounts/${e}/iam/sso/provider`)).provider}async function fx(e,t){return S(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function yx(e,t){return S(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function hx(e){return S(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function bx(e){return S(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function _x(e){return S(await M(`/accounts/${e}/iam/sso/mappings`)).mappings}async function Px(e,t){return S(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function xx(e,t){return S(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function Sx(e){return S(await M(`/accounts/${e}/iam/session-policy`))}async function wx(e,t){return S(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function vx(e){return S(await M(`/accounts/${e}/iam/sessions`)).sessions}async function Ax(e,t){return S(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function kx(e){return S(await M(`/accounts/${e}/iam/pat-policy`))}async function Rx(e,t){return S(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function Ix(e){return S(await M(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function Tx(e,t){return S(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function Cx(e,t){return S(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function Ex(e,t){return S(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function Mx(e){return S(await M(`/accounts/${e}/audit/webhooks`)).webhooks}async function Ox(e,t){return S(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function jx(e,t,n){return S(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Dx(e,t){return S(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function $x(e,t={}){let n=je({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 S(await M(`/accounts/${e}/audit${n}`))}async function eu(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),S(await M(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function tu(e,t,n){return n.length===0?[]:S(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function Ux(e){return S(await M(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function Lx(e,t){return S(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function nu(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function ru(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function ou(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function su(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function iu(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function au(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function Fx(e){return je({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 cu(e,t){return u(await M(`/accounts/${e}/iam/assignments${Fx(t)}`)).assignments}async function lu(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 c.post(`/accounts/${e}/iam/assignments`,n))}async function uu(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function pu(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await M(`/accounts/${e}/iam/permissions${n}`)).permissions}async function Nx(){let e=await c.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function Kx(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function qx(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function Gx(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function Bx(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function Wx(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function Hx(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function Vx(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function zx(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function Yx(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function Qx(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function Xx(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var Xg="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function Jx(e){throw q("getGoogleAuthUrl",Xg)}async function Zx(e,t){throw q("convertPresentationToGoogleSlides",Xg)}async function du(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 c.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function gu(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function mu(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function fu(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function yu(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}var hu="call:";function eS(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(hu)&&e.length>hu.length?{type:"connector_call",executionId:e.slice(hu.length)}:{type:"review_item",reviewItemId:e}}function Zg(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function tS(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Zg(n.status)]+=1;return t}function nS(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 bu(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function _u(e){let t=e.indexOf(".");return t<=0?bu(e):`(${bu(e.slice(0,t))}) ${bu(e.slice(t+1))}`}function rS(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var br=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,ge=e=>Array.isArray(e)?e:void 0,Jg=e=>typeof e=="number"?e:0,oS=e=>e.split(`
14
- `).map(t=>t.trim()).filter(Boolean);function sS(e,t){let n=br(e.advanced),r=U(e.description),o=ge(e.whatChanged)??(r?oS(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:o,impact:U(e.impact)??"",verification:ge(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:ge(e.conflicts),requestedChanges:ge(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:Jg(n.additions),deletions:Jg(n.deletions),files:ge(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function iS(e,t){let n=ge(e.actions);if(n)return{actions:n.map((l,p)=>({id:U(l.id)??`${t.review_item_id}-${p}`,title:U(l.title)??"Action",connector:U(l.connector)??"",action:U(l.action)??"",consequence:U(l.consequence)??"",risk:U(l.risk)??t.risk,icon:U(l.icon)??"generic",argsPreview:ge(l.argsPreview)??[],policySource:U(l.policySource)??"Requires approval",decided:l.decided==="approved"||l.decided==="denied"?l.decided:void 0}))};let r=U(e.action_path)??"",{connector:o,action:s}=rS(r),i=br(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?_u(r):t.title||"Run action",connector:o,action:s,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([l,p])=>({key:l,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,approvalContext:U(e.approval_context),connectorRisk:U(e.risk)??null,policySource:"Requires approval"}]}}function aS(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:ge(e.files),note:U(e.note)??t.summary??""}}function cS(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:ge(e.options)??[]}}function lS(e,t){return{note:U(e.note)??t.summary??"",children:ge(e.children)??[]}}function uS(e){let t=br(e.detail);switch(e.kind){case"change":return sS(t,e);case"approval":return iS(t,e);case"output":return aS(t,e);case"decision":return cS(t,e);case"batch":return lS(t,e)}}function pS(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 dS(e,t={}){let n=br(e.detail),r=e.origin_session_id??void 0,o=r?t.sessionLabels?.[r]:void 0,s=e.kind==="approval"?U(n.action_path):void 0,i=e.kind==="change"?pS(n,e.summary):e.kind==="approval"?o??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:s?_u(s):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:uS(e)}}async function Pu(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function xu(e){return u(await c.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Su(e,t){let n=await c.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var _r=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function em(e,t=""){return`${an()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function tm(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 o=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new _r(o,t.status)}return r}async function gS(e){return tm(em(e))}async function mS(e){return tm(em(e,"/messages"))}async function wu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function vu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Au(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function ku(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}async function Ru(e){return u(await c.get(`/projects/${e}/reminders`))}async function Iu(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 c.get(`/accounts/tokens${r}`))}async function Tu(e){let{accountId:t,expiresAt:n,projectId:r,name:o}=e;return u(await c.post("/accounts/tokens",{name:o,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function Cu(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await c.delete(`/accounts/tokens/${e}${n}`))}async function Eu(){return u(await c.get("/oauth/grants")).grants}async function Mu(e){return u(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function Ou(e){return u(await c.get(`/projects/${e}/cli-token`))}async function ju(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function Du(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}function dt(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,o]of Object.entries(e))n.includes(` ${r} `)&&o!=null&&o!==""&&t.set(r,String(o));return t}function $u(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 Uu(e,t){let n=dt($u(t)).toString();return u(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function Lu(e,t){let n=dt($u({...t,projectId:void 0})).toString();return u(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function Fu(e,t){let n=dt($u(t)).toString();return u(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Nu(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function Ku(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function qu(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Gu(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Bu(e,t){return u(await c.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function Wu(e,t){return u(await c.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function fS(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function Hu(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 c.get(`/marketplace/items${n}`))}async function Vu(){return u(await c.get("/marketplace/marketplaces"))}async function zu(){return u(await c.get("/marketplace/marketplaces/featured"))}async function Yu(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Qu(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Xu(){return u(await c.get("/marketplace/sources"))}async function Ju(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Zu(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function yS(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function hS(e){throw q("getTemplate")}async function bS(e,t){throw q("installTemplate")}async function ep(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function tp(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function np(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function rp(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function op(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function sp(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function ip(e,t){return u(await c.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function ap(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function cp(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Pr(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function xr(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function _S(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function PS(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 lp(e,t,n={}){let r=await _S(t),o=n.mediaType??"application/gzip",s=await Pr(e,{kind:"archive",media_type:o});if(!s.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>s.upload.max_bytes)throw new Error(`App artifact exceeds ${s.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(s.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:o}),signal:n.signal,headers:{"content-type":o,"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),xr(e,s.artifact.artifact_id,{sha256:await PS(r),size_bytes:r.byteLength})}async function up(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function pp(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function dp(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function gp(e,t,n,r={}){let o=new URLSearchParams;r.after!==void 0&&o.set("after",String(r.after)),r.limit!==void 0&&o.set("limit",String(r.limit));let s=o.size?`?${o.toString()}`:"";return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${s}`),"Failed to load App logs")}async function mp(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function fp(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function yp(e,t,n){return u(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function hp(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}async function ln(e){return u(await c.get(`/projects/${e}/model-access`))}async function un(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}function xS(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:o,previewHasError:s,previewIsLinkOnly:i}=e;return t||n?!1:o?s&&!i:r==="error"}function bp(e){return typeof e=="string"&&e.trim().length>0}function nm(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return bp(t)||bp(n)||bp(r)}function SS(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 pn(e){if(!e)return!0;let t=SS(e.items);return t?!t.some(nm):!nm(e)}function ae(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function wS(e){return ae(e)==="bash"}function vS(e){let t=ae(e);return t==="question"||t==="ask"}function AS(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var rm=new Set(["show","show_user"]);function _p(e){return rm.has(ae(e))}function kS(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Pp(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Sr(e))}function Sr(e){let t=ae(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:pn(e.state?.input)}var om=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function xp(e){return om.has(ae(e))}var RS=50*1024*1024,Sp="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",IS=new RegExp(`^kortix-attachment://(${Sp})/(${Sp})/(${Sp})$`);function vp(e){if(typeof e!="string")return null;let t=IS.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function TS(e){return vp(e)!==null}var wp=new WeakMap;async function Ap(e,t,n,r={}){if(n.size>RS)throw new Error("Attachments must be 50 MiB or smaller.");let o=`${e}/${t}`,s=r.attachmentId?void 0:wp.get(n)?.get(o);if(s?.promise)return s.promise;let i=s??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let l=wp.get(n)??new Map;l.set(o,i),wp.set(n,l)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=c.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(l=>{throw i.promise=void 0,l}),i.promise}async function kp(e,t){let n=vp(e);if(!n)throw new Error("Invalid attachment reference");let r=k().backendUrl.replace(/\/$/,""),o=await j(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!o.ok)throw new b("Could not load attachment",{status:o.status});return o.blob()}var CS=new Set(["show","show_user"]);function ES(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let o=r+5;if(o>=e.length||!/\s/.test(e[o])){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return t;let i=e.indexOf("</file>",s+1);if(i===-1)return t;t.push(e.slice(o,s).trimStart()),n=i+7}}var gt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),dn=e=>typeof e=="string"&&e.length>0?e:null,sm=e=>typeof e=="string"?dn(e.split("/").pop()):null;function wr(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function MS(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 OS(e,t){for(let n of ES(e))t(wr(n,"attachment"),wr(n,"filename")??sm(wr(n,"path")),wr(n,"mime"))}function jS(e,t){for(let n of[e,...MS(e.items)])gt(n)&&t(n.attachment,sm(n.path),null)}function DS(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 o=dn(r.info.id);if(!o)continue;let s=dn(r.info.role)??"unknown",i=(a,l,p)=>{let d=vp(a);!d||n.has(a)||(n.add(a),t.push({url:a,attachment_id:d.attachmentId,filename:l,mime:p,message_id:o,role:s}))};for(let a of r.parts)gt(a)&&(a.type==="file"?i(a.url,dn(a.filename),dn(a.mime)):a.type==="text"&&typeof a.text=="string"?OS(a.text,i):a.type==="tool"&&typeof a.tool=="string"&&CS.has(ae(a.tool))&&gt(a.state)&&gt(a.state.input)&&jS(a.state.input,i))}return t}function vr(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function $S(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 US(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 Rp(e,t,n){return e!==void 0?e:$S(vr(t),n)}var Ip={get disableMobileAdvertising(){return Rp(k().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Rp(k().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Rp(k().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var LS=new Set(["project-manager"]);function Ar(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Ip.enableProjects||!LS.has(e.name)}function FS(e){let t=e.agents.filter(Ar),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function im(){return{projects:{list:Be,listForAccount:_s,get:Gt,detail:Bt,create:ws,createRepo:vs,provision:As,update:Vt,archive:zt,llmCatalog:Wt,modelPicker:Ht,modelAccess:ln,setModelAccess:un,sandboxHealth:Xt,sandboxTemplates:fa,sessions:We,createSession:He},github:{linkRepository:Cs,replaceProjectRepository:Es,getInstallation:Ms,listInstallations:Os,listLinkableInstallations:js,listRepositories:Ds,listRepositoryBranches:$s,linkInstallation:Ls,saveInstallation:Us,deleteInstallation:Ns,storeUserToken:Fs},gitBackend:{get:Ks,repositories:qs},connectStatus:ua,marketplace:{items:s=>Hu(s),item:s=>Yu(s),itemFile:(s,i)=>Qu(s,i),marketplaces:()=>Vu(),featured:()=>zu(),sources:{list:()=>Xu(),add:s=>Ju(s),remove:s=>Zu(s)}}}}function am(){return{billing:{accountState:$c,accountStateMinimal:Uc,transactions:Lc,transactionsSummary:Fc,creditBreakdown:Nc,usageHistory:Kc,usageRollup:el,sessionCosts:{list:rl,get:cn},tierConfigurations:qc,checkout:{createSession:n=>Gc(n),confirmSession:(n,r)=>Bc(n,r)},subscription:{createPortalSession:(n,r)=>Wc(n,r),cancel:(n,r)=>Hc(n,r),reactivate:n=>Vc(n),scheduleDowngrade:(n,r,o)=>zc(n,r,o),cancelScheduledChange:n=>Yc(n),prorationPreview:(n,r)=>Qc(n,r)},credits:{purchase:n=>Xc(n),autoTopupSettings:n=>Jc(n),configureAutoTopup:n=>Zc(n)}},sandboxShares:{list:Pu,create:xu,revoke:Su}}}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 ve={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function me(){let e=vr("BACKEND_URL")||k().backendUrl;return e||"http://localhost:8008/v1"}function Ve(e){let t=ce(e);return t.endsWith("/v1")?t:`${t}/v1`}function gn(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=gn(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return gn(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}var cm=["http://localhost:8008/v1","http://127.0.0.1:8008/v1"];function lm(e){return`${ce(e)}/platform/local-bridge/status`}function NS(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 Tp(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?`${me()}/p/${n.external_id}/${ve.KORTIX_MASTER}`:""),status:NS(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 Cp(){let e=await Be(),t=[];for(let n of e){let r=await We(n.project_id).catch(()=>[]);for(let o of r)t.push({project:n,session:o,runtime:null,sandbox:Tp(n,o,null)})}return t.sort((n,r)=>{let o={active:0,provisioning:1,stopped:2,error:3},s=(o[n.sandbox.status]??99)-(o[r.sandbox.status]??99);return s!==0?s:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function ze(e){let t=await Cp();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 mt=class extends Error{constructor(n,r,o){super(r);this.code=n;this.status=o;this.name="HeadlessAuthError"}code;status};async function z(e,t,n){let r=n?.fetch??k().fetch??((p,d)=>fetch(p,d)),o=ce(n?.backendUrl??k().backendUrl??"");if(!o)throw new mt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let i=await r(`${Ve(o)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:s,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),l=null;try{l=a?JSON.parse(a):null}catch{l=a}if(!i.ok){let p=l&&typeof l=="object"?l:{};throw new mt(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 l}function kr(e,t){return z("/auth/signup",{body:e},t)}function Rr(e,t){return z("/auth/sign-in/password",{body:e},t)}function Ir(e,t){return z("/auth/sign-in/magic-link",{body:e},t)}function Tr(e,t){return z("/auth/verify-otp",{body:e},t)}function Cr(e,t){return z("/auth/sign-in/oauth",{body:e},t)}function Er(e,t){return z("/auth/oauth/exchange",{body:e},t)}function ft(e,t){return z("/auth/refresh",{body:e},t)}function Mr(e,t){return z("/auth/password/reset",{body:e},t)}function Or(e,t,n){return z("/auth/password/update",{body:e,bearer:t},n)}function jr(e,t){return z("/auth/user",{bearer:e},t)}function Dr(e,t,n){return z("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function $r(e,t){return z("/auth/sign-in/sso",{body:e},t)}var Ur={enroll:(e,t,n)=>z("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function Lr(e,t={},n){return z("/auth/sign-out",{body:t,bearer:e},n)}function Fr(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,o=null,s=!e.storage,i=null,a=null,l=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:o})):await e.storage.remove());for(let w of[...p])try{w(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(s)return r;if(!i){let w=l,L=(async()=>{let O=await e.storage.get();if(w===l&&O)try{let D=JSON.parse(O);D.session?.access_token&&D.session?.refresh_token&&(r=D.session,o=D.user??null)}catch{r=null}return s=!0,r})();i=L,L.then(()=>{i===L&&(i=null)},()=>{i===L&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let w=r.refresh_token,L=l,O=ft({refresh_token:w},e.request).then(async D=>(L!==l||(r=D.session,D.user&&(o=D.user),await m()),r)).catch(async D=>{if(L!==l)return r;let y=D&&typeof D=="object"&&"status"in D?D.status:0;if(y>=400&&y<500)return r=null,o=null,await m(),null;throw D}).finally(()=>{a===O&&(a=null)});a=O}return a}return{subscribe(w){return p.add(w),()=>{p.delete(w)}},current:()=>r,user:()=>o,load:f,async set(w,L){await f(),l+=1,a=null,r=w,L!==void 0&&(o=L),w||(o=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(){l+=1,a=null,r=null,o=null,s=!0,await m()}}}function um(){return{list:Xo,get:Zo,create:Jo,secretResources:{list:Pi,create:xi,rotate:Si,remove:wi,grant:vi,revoke:Ai,setAccess:ki},updateName:es,branding:{get:ts,update:ns,uploadAsset:rs,removeAsset:os,reset:ss},leave:hs,members:is,invite:as,removeMember:fs,updateMemberRole:ys,invites:cs,cancelInvite:ls,resendInvite:us,tokens:{list:Iu,create:Tu,revoke:Cu},connectedApps:{list:Eu,revoke:Mu},audit:{log:Uu,export:Fu,webhooks:{list:Nu,create:Ku,update:qu,remove:Gu}}}}function pm(){return{assignments:{list:cu,create:lu,revoke:uu},permissions:{list:pu,forRole:zl},roles:{list:Wl,create:Ql,update:Xl,setPermissions:Jl,remove:Zl,usage:Yl},groups:{list:Ul,get:Ll,create:Fl,update:Nl,remove:Kl,members:{list:ql,add:Gl,remove:Bl}},agentIdentities:Hl,oauthClients:{list:nu,get:ru,create:ou,update:su,rotateSecret:iu,remove:au},can:eu,canBatch:tu}}function dm(){let e={signUp:kr,signInWithPassword:Rr,sendMagicLink:Ir,verifyOtp:Tr,signInWithProvider:Cr,exchangeCode:Er,refresh:ft,resetPassword:Mr,updatePassword:Or,updateUserMetadata:Dr,signInWithSso:$r,mfa:Ur,user:jr,signOut:Lr,session:Fr},t=um(),n=pm();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:ps,describe:ds,accept:gs,decline:ms}}}var mn=new Map,Ep=new Map;function Mp(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function gm(e){return mn.get(Mp(e))??null}function mm(){return[...mn.values()].filter(e=>typeof e=="string")}function fm(e){return mn.has(Mp(e))}async function yt(e){let t=Mp(e),n=mn.get(t);if(n!==void 0)return n;let r=Ep.get(t);if(r)return r;let o=(async()=>{try{let s=await c.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!s.success)return null;let i=typeof s.data?.preview_url_template=="string"?s.data.preview_url_template:null;return mn.set(t,i),i}catch{return null}finally{Ep.delete(t)}})();return Ep.set(t,o),o}function ym(e){let{apiBaseUrl:t}=e;return fm(t)||yt(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:gm(t)}}function hm(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new b(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let o=k().backendUrl??e.backendUrl,s=80,i=t(o);return i&&(s=i.port?Number(i.port):i.protocol==="https:"?443:80),ym({sandboxId:r,apiBaseUrl:o,backendPort:s})}}function bm(e,t){let n=null;async function r(){n||(n=nn(e,t,{showErrors:!1}).then(o=>{let s=Pc(o)??"",i=s.indexOf("/"),a=i>0&&i<s.length-1?{providerID:s.slice(0,i),modelID:s.slice(i+1)}:void 0,l=o.agent_name?.trim()||void 0;return{model:a,agent:l}}));try{return await n}catch(o){throw n=null,o}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var fn=new Map;function _m(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 o=n?.evidence?.error;return o&&o!==n?.message&&r.push(o),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Ye=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 ht={url:null,sandboxId:null,dbSandboxId:null,version:0},qS=new Set;function Pm(e,t=null,n=null){if(!(ht.url===e&&ht.sandboxId===t&&ht.dbSandboxId===n)){ht={url:e,sandboxId:t,dbSandboxId:n,version:ht.version+1};for(let r of qS)r()}}function xm(){return ht.url}function Sm(e,t){async function n(r){let o=Date.now()+r,s=()=>Math.max(0,o-Date.now()),i=await Oe(e,t,Math.min(3e4,s()));for(;Date.now()<o&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,s()))),i=await Oe(e,t,Math.min(3e4,s()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new b(_m(i),{code:"RUNTIME_UNAVAILABLE"});let l=i.sandbox.external_id;if(!l)throw new b("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=pt(l);return Pm(p,l),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:l}}return n}function wm(e,t,n){let r=null;function o(){if(r)return r;let p=Kg(e,t);return p&&(r=p),r}let s=Sm(e,t);async function i(p){let d=o();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=yt(k().backendUrl??n.backendUrl).catch(()=>null),f=`${e}
15
- ${t}`,h=fn.get(f);if(h)return r=await h,await m,r;let w=s(g);fn.set(f,w);try{return r=await w,await m,r}finally{fn.get(f)===w&&fn.delete(f)}}function a(p){let d=o();if(!d)throw new Ye(p);return d}function l(){r=null,Gg(e,t)}return{ensureReady:i,tryResolveReady:o,requireReady:a,forgetReady:l}}var K=["directory","workspace"],vm=["messageID","model","agent","noReply","tools","format","system","variant","parts"],R=(e,t,n=K,r=[],o)=>({method:e,path:t,query:n,body:r,bodyParam:o}),GS={"session.list":R("GET","/session",[...K,"scope","path","roots","start","search","limit"]),"session.get":R("GET","/session/{sessionID}"),"session.create":R("POST","/session",K,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":R("DELETE","/session/{sessionID}"),"session.update":R("PATCH","/session/{sessionID}",K,["title","metadata","permission","time"]),"session.status":R("GET","/session/status"),"session.messages":R("GET","/session/{sessionID}/message",[...K,"limit","before"]),"session.prompt":R("POST","/session/{sessionID}/message",K,vm),"session.promptAsync":R("POST","/session/{sessionID}/prompt_async",K,vm),"session.abort":R("POST","/session/{sessionID}/abort"),"session.revert":R("POST","/session/{sessionID}/revert",K,["messageID","partID"]),"session.unrevert":R("POST","/session/{sessionID}/unrevert"),"session.summarize":R("POST","/session/{sessionID}/summarize",K,["providerID","modelID","auto"]),"session.command":R("POST","/session/{sessionID}/command",K,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":R("POST","/session/{sessionID}/share"),"session.unshare":R("DELETE","/session/{sessionID}/share"),"session.diff":R("GET","/session/{sessionID}/diff",[...K,"messageID"]),"session.todo":R("GET","/session/{sessionID}/todo"),"permission.list":R("GET","/permission"),"permission.reply":R("POST","/permission/{requestID}/reply",K,["reply","message"]),"question.list":R("GET","/question"),"question.reply":R("POST","/question/{requestID}/reply",K,["answers"]),"question.reject":R("POST","/question/{requestID}/reject"),"part.update":R("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",K,[],"part"),"part.delete":R("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":R("GET","/file",[...K,"path"]),"file.read":R("GET","/file/content",[...K,"path"]),"find.files":R("GET","/find/file",[...K,"query","dirs","type","limit"]),"vcs.diff":R("GET","/vcs/diff",[...K,"mode","context"]),"global.health":R("GET","/global/health",[]),"global.dispose":R("POST","/global/dispose",[]),"global.config.get":R("GET","/global/config",[]),"global.config.update":R("PATCH","/global/config",[],[],"config"),"provider.list":R("GET","/provider"),"provider.auth":R("GET","/provider/auth"),"provider.oauth.authorize":R("POST","/provider/{providerID}/oauth/authorize",K,["method","inputs"]),"provider.oauth.callback":R("POST","/provider/{providerID}/oauth/callback",K,["method","code"]),"auth.set":R("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":R("GET","/agent"),"app.skills":R("GET","/skill"),"app.log":R("POST","/log",K,["service","level","message","extra"]),"command.list":R("GET","/command"),"tool.ids":R("GET","/experimental/tool/ids"),"tool.list":R("GET","/experimental/tool",[...K,"provider","model"]),"mcp.status":R("GET","/mcp"),"mcp.add":R("POST","/mcp",K,["name","config"]),"mcp.connect":R("POST","/mcp/{name}/connect"),"mcp.disconnect":R("POST","/mcp/{name}/disconnect"),"mcp.auth.start":R("POST","/mcp/{name}/auth"),"mcp.auth.callback":R("POST","/mcp/{name}/auth/callback",K,["code"]),"mcp.auth.remove":R("DELETE","/mcp/{name}/auth"),"project.list":R("GET","/project"),"project.current":R("GET","/project/current"),"path.get":R("GET","/path")};function BS(e,t){let n=[];for(let r of e.query){let o=t[r];o!=null&&n.push(`${r}=${encodeURIComponent(String(o))}`)}return n.length?`?${n.join("&")}`:""}function WS(e,t,n={},r={}){let o=GS[t],s=o.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(o.bodyParam)i=n[o.bodyParam],a=i!==void 0;else for(let p of o.body)p in n&&(i={...i,[p]:n[p]},a=!0);let l=new Headers(r.headers);return a&&l.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${s}${BS(o,n)}`,{method:o.method,headers:l,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function HS(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 VS(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=HS(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 o=await r.text(),s=o;try{s=JSON.parse(o)}catch{}return{error:s||{},request:t,response:r}}function Op(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let o=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!o.ok)throw Object.assign(new Error(`SSE failed: ${o.status} ${o.statusText}`),{status:o.status});if(!o.body)throw new Error("No body in SSE response");let s=o.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{s.cancel()}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:l,value:p}=await s.read();if(l)break;a=(a+p).replace(/\r\n/g,`
13
+ `);let h=pP(f);if(h){if(r(h),h.type==="error")throw new b(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function fc(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function yc(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function hc(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function bc(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function _c(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function Pc(e){return u(await l.get(`/projects/${e}/triggers`))}async function xc(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function Sc(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function wc(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function vc(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function Ac(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}var Ce=new Map;function kc(e,t){return`${e}::${t}`}function Ug(e,t){Ce.delete(e),Ce.set(e,t)}function Lg(e,t){let n=kc(e,t),r=Ce.get(n);return r&&Ug(n,r),r}function Fg(e,t,n){let r=kc(e,t);if(!Ce.has(r)&&Ce.size>=512){let o=Ce.keys().next().value;o!==void 0&&Ce.delete(o)}Ug(r,n)}function Ng(e,t){Ce.delete(kc(e,t))}function dP(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function on(){return dP(k().backendUrl||"http://localhost:8008/v1")}function Kg(){let e=k().sandboxId;return e?`${on()}/p/${e}/8000`:""}function gP(e,t=8e3){return`${on()}/p/${e}/${t}`}function lt(e,t=8e3){return gP(e,t)}function mP(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 mr=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 fP(e){return e instanceof Error&&e.name==="SessionStartError"}function yP(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,o=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new mr(o,{status:n,code:r,terminal:!0}):null}async function Ee(e,t,n){let r=typeof n=="number"?n:n?.waitMs,o=typeof n=="number"?void 0:n?.repositoryMode,s=new URLSearchParams;r&&r>0&&s.set("wait_ms",String(Math.floor(r))),o&&s.set("repository_mode",o);let i=s.size>0?`?${s.toString()}`:"",a=await l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1});if(!a.success||!a.data){let g=yP(a.error);if(g&&!(g.status===404&&Wa(t)))throw g;return null}let c=a.data,p=c.sandbox?.external_id,d=c.runtime_session_id??c.opencode_session_id;return c.stage==="ready"&&p&&d&&Fg(e,t,{runtimeSessionId:d,opencodeSessionId:d,runtimeUrl:lt(p),sandboxId:p}),c}function hP(e,t){return["session-start",e,t]}async function Rc(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function Ic(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function Tc(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 bP(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function qg(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function _P(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function fr(e){let t=e.connectors_required?qg(e.connectors_required):void 0,n=e.connectors_personal?qg(e.connectors_personal):void 0;if(t&&n&&!_P(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 Cc(e,t,n){let r=fr(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function PP(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Ec(n.block):null}}async function xP(e,t,n){let r=Ec(n,!0),o=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...o,block:o.block?Ec(o.block):null}}function Ec(e,t=!1){let n=fr(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 SP(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Mc(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}function Oc(){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 wP(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function vP(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??Oc(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),o=(n.tier?.display_name||"").trim()||r;return{family:wP(r),label:o,sublabel:null,isGrandfathered:!1}}async function Gg(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?Oc():t.data}function Bg(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 jc(e){return Gg(`/billing/account-state${Bg(e)}`)}async function Dc(e){return Gg(`/billing/account-state/minimal${Bg(e)}`)}async function $c(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 Uc(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 Lc(){return u(await l.get("/billing/credit-breakdown"))}async function Fc(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function Nc(){return u(await l.get("/billing/tier-configurations"))}async function AP(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return st(e,`/v1/billing/account-state${t}`)}async function Kc(e){return u(await l.post("/billing/create-checkout-session",{account_id:e.accountId,tier_key:e.tierKey,success_url:e.successUrl,cancel_url:e.cancelUrl,commitment_type:e.commitmentType,locale:e.locale,server_type:e.serverType,location:e.location}),"Failed to create checkout session")}async function qc(e,t){return u(await l.post("/billing/confirm-checkout-session",{account_id:t,session_id:e}),"Failed to confirm checkout session")}async function Gc(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Bc(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Wc(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Hc(e,t,n){return u(await l.post("/billing/schedule-downgrade",{account_id:n,target_tier_key:e,commitment_type:t}),"Failed to schedule downgrade")}async function Vc(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function zc(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 Yc(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 Qc(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 Xc(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 kP(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 RP(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 IP(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function TP(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function Jc(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 el(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function yr(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function hr(e){return e.size>0?`?${e}`:""}async function tl(e={}){let t=new URLSearchParams;return el(t,e),e.ownerId&&t.set("owner_id",e.ownerId),yr(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${hr(t)}`))}async function sn(e,t={}){let n=new URLSearchParams;return el(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${hr(n)}`))}async function CP(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),yr(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${hr(t)}`))}async function EP(e={}){let t=new URLSearchParams;return el(t,e),e.sessionId&&t.set("session_id",e.sessionId),yr(t,e),u(await l.get(`/usage/cost-summary${hr(t)}`))}function Zc(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 o=t;o.ownerId&&n.set("owner_id",o.ownerId)}yr(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 MP(e,t={}){let n=Zc(e==="projects"?"projects":"sessions",t),r=await it(),o=await fetch(n,{method:"GET",headers:r?{Authorization:`Bearer ${r}`}:{}});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(c||`Failed to export CSV (HTTP ${o.status})`)}let s=o.headers.get("x-kortix-row-cap"),i=s!=null?Number(s):NaN;return{blob:await o.blob(),rowCap:Number.isFinite(i)?i:null}}async function Wg(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function OP(e){return Wg("slack",e)}function jP(e){return Wg("teams",e)}async function Hg(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function DP(e){return Hg("slack",e)}function $P(e){return Hg("teams",e)}async function nl(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function rl(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var UP={oauth_available:!1,install_url:null};async function ol(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?UP:t.data}async function Vg(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 sl(e,t){return Vg("slack",e,t)}function il(e,t){return Vg("teams",e,t)}async function al(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function cl(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 ll(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 ul(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 pl(e){let t=e.connectionId??e.connection_id??null,n=e.connectorSlug??e.connector_slug??e.connectionSlug??e.connection_slug??"kortix_email";return{...e,connectionId:t,connectorSlug:n}}var LP={provider:"agentmail",managed_available:!1};async function dl(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?pl(r.data):null}async function gl(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?LP:t.data}async function ml(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return pl(n)}async function fl(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 yl(e,t,n){let r=u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return pl(r)}async function FP(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function NP(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 hl(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function bl(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function _l(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Pl(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function xl(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 Sl(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function wl(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function vl(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Al(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function kl(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Rl(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Il(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Tl(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Cl(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function El(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Ml(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Ol(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function jl(e,t,n,r,o){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...o&&Object.keys(o).length?{generationConfig:o}:{}}),"Gateway request failed")}async function KP(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function qP(){throw F("getReferralCode")}async function GP(){throw F("refreshReferralCode")}async function BP(e){throw F("validateReferralCode")}async function WP(){throw F("getReferralStats")}async function HP(e={}){throw F("listReferrals")}async function VP(e){throw F("sendReferralEmails")}function M(e){return l.get(e,{showErrors:!1})}function S(e){return u(e,"Unexpected empty response")}async function Dl(e){return S(await M(`/accounts/${e}/iam/groups`)).groups}async function $l(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}`))}async function Ul(e,t){return S(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Ll(e,t,n){return S(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Fl(e,t){return S(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function Nl(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Kl(e,t,n){return S(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function zP(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function ql(e,t,n){return S(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function YP(e,t){return S(await M(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function QP(e,t){let n=S(await M(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function Me(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}async function XP(e,t={}){let n=Me({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return S(await M(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function JP(e,t={}){let n=Me({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return S(await M(`/accounts/${e}/iam/policies${n}`)).policies}async function ZP(e,t){return S(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function ex(e,t,n){return S(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function tx(e,t){return S(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function nx(e,t){return S(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function rx(e,t){return S(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Gl(e){return S(await M(`/accounts/${e}/iam/roles`)).roles}async function Bl(e){return S(await M(`/accounts/${e}/iam/agent-identities`)).agents}async function Wl(e){return S(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function Hl(e,t){return S(await M(`/accounts/${e}/iam/roles/${t}/permissions`))}async function ox(e){return S(await M(`/accounts/${e}/iam/actions`)).actions}async function Vl(e,t){return S(await M(`/accounts/${e}/iam/roles/${t}/usage`))}async function zl(e,t){return S(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Yl(e,t,n){return S(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Ql(e,t,n){return S(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Xl(e,t){return S(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function sx(e,t,n){return S(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function ix(e){return S(await M(`/accounts/${e}/iam/scim/tokens`)).tokens}async function ax(e,t){return S(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function cx(e,t){return S(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function lx(e){return S(await M(`/accounts/${e}/iam/mfa-required`))}async function ux(e){return S(await M(`/accounts/${e}/iam/mfa-required/preview`))}async function px(e,t){return S(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function dx(e){return S(await M(`/accounts/${e}/iam/session-oversight`))}async function gx(e,t){return S(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function mx(e){return S(await M(`/accounts/${e}/iam/sso/provider`)).provider}async function fx(e,t){return S(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function yx(e,t){return S(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function hx(e){return S(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function bx(e){return S(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function _x(e){return S(await M(`/accounts/${e}/iam/sso/mappings`)).mappings}async function Px(e,t){return S(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function xx(e,t){return S(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function Sx(e){return S(await M(`/accounts/${e}/iam/session-policy`))}async function wx(e,t){return S(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function vx(e){return S(await M(`/accounts/${e}/iam/sessions`)).sessions}async function Ax(e,t){return S(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function kx(e){return S(await M(`/accounts/${e}/iam/pat-policy`))}async function Rx(e,t){return S(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function Ix(e){return S(await M(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function Tx(e,t){return S(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function Cx(e,t){return S(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function Ex(e,t){return S(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function Mx(e){return S(await M(`/accounts/${e}/audit/webhooks`)).webhooks}async function Ox(e,t){return S(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function jx(e,t,n){return S(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Dx(e,t){return S(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function $x(e,t={}){let n=Me({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 S(await M(`/accounts/${e}/audit${n}`))}async function Jl(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),S(await M(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Zl(e,t,n){return n.length===0?[]:S(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function Ux(e){return S(await M(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function Lx(e,t){return S(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function eu(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function tu(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function nu(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function ru(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function ou(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function su(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function Fx(e){return Me({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 iu(e,t){return u(await M(`/accounts/${e}/iam/assignments${Fx(t)}`)).assignments}async function au(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 cu(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function lu(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await M(`/accounts/${e}/iam/permissions${n}`)).permissions}async function Nx(){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 Kx(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function qx(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function Gx(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function Bx(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function Wx(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function Hx(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function Vx(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function zx(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function Yx(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function Qx(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function Xx(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var zg="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function Jx(e){throw F("getGoogleAuthUrl",zg)}async function Zx(e,t){throw F("convertPresentationToGoogleSlides",zg)}async function uu(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 pu(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function du(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function gu(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function mu(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}var fu="call:";function eS(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(fu)&&e.length>fu.length?{type:"connector_call",executionId:e.slice(fu.length)}:{type:"review_item",reviewItemId:e}}function Qg(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function tS(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Qg(n.status)]+=1;return t}function nS(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 yu(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function hu(e){let t=e.indexOf(".");return t<=0?yu(e):`(${yu(e.slice(0,t))}) ${yu(e.slice(t+1))}`}function rS(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var br=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,ge=e=>Array.isArray(e)?e:void 0,Yg=e=>typeof e=="number"?e:0,oS=e=>e.split(`
14
+ `).map(t=>t.trim()).filter(Boolean);function sS(e,t){let n=br(e.advanced),r=U(e.description),o=ge(e.whatChanged)??(r?oS(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:o,impact:U(e.impact)??"",verification:ge(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:ge(e.conflicts),requestedChanges:ge(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:Yg(n.additions),deletions:Yg(n.deletions),files:ge(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function iS(e,t){let n=ge(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:ge(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:o,action:s}=rS(r),i=br(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?hu(r):t.title||"Run action",connector:o,action:s,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:U(e.approval_context),connectorRisk:U(e.risk)??null,policySource:"Requires approval"}]}}function aS(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:ge(e.files),note:U(e.note)??t.summary??""}}function cS(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:ge(e.options)??[]}}function lS(e,t){return{note:U(e.note)??t.summary??"",children:ge(e.children)??[]}}function uS(e){let t=br(e.detail);switch(e.kind){case"change":return sS(t,e);case"approval":return iS(t,e);case"output":return aS(t,e);case"decision":return cS(t,e);case"batch":return lS(t,e)}}function pS(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 dS(e,t={}){let n=br(e.detail),r=e.origin_session_id??void 0,o=r?t.sessionLabels?.[r]:void 0,s=e.kind==="approval"?U(n.action_path):void 0,i=e.kind==="change"?pS(n,e.summary):e.kind==="approval"?o??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:s?hu(s):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:uS(e)}}async function bu(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function _u(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 Pu(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 _r=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Xg(e,t=""){return`${on()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Jg(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 o=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new _r(o,t.status)}return r}async function gS(e){return Jg(Xg(e))}async function mS(e){return Jg(Xg(e,"/messages"))}async function xu(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function Su(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function wu(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function vu(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}async function Au(e){return u(await l.get(`/projects/${e}/reminders`))}async function ku(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 Ru(e){let{accountId:t,expiresAt:n,projectId:r,name:o}=e;return u(await l.post("/accounts/tokens",{name:o,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function Iu(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function Tu(){return u(await l.get("/oauth/grants")).grants}async function Cu(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function Eu(e){return u(await l.get(`/projects/${e}/cli-token`))}async function Mu(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function Ou(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function ut(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,o]of Object.entries(e))n.includes(` ${r} `)&&o!=null&&o!==""&&t.set(r,String(o));return t}function ju(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 Du(e,t){let n=ut(ju(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function $u(e,t){let n=ut(ju({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function Uu(e,t){let n=ut(ju(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Lu(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Fu(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Nu(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Ku(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function qu(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 Gu(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 fS(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function Bu(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 Wu(){return u(await l.get("/marketplace/marketplaces"))}async function Hu(){return u(await l.get("/marketplace/marketplaces/featured"))}async function Vu(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function zu(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Yu(){return u(await l.get("/marketplace/sources"))}async function Qu(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Xu(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function yS(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function hS(e){throw F("getTemplate")}async function bS(e,t){throw F("installTemplate")}async function Ju(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Zu(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function ep(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function tp(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function np(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function rp(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function op(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 sp(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function ip(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Pr(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function xr(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function _S(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function PS(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 ap(e,t,n={}){let r=await _S(t),o=n.mediaType??"application/gzip",s=await Pr(e,{kind:"archive",media_type:o});if(!s.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>s.upload.max_bytes)throw new Error(`App artifact exceeds ${s.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(s.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:o}),signal:n.signal,headers:{"content-type":o,"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),xr(e,s.artifact.artifact_id,{sha256:await PS(r),size_bytes:r.byteLength})}async function cp(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function lp(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function up(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function pp(e,t,n,r={}){let o=new URLSearchParams;r.after!==void 0&&o.set("after",String(r.after)),r.limit!==void 0&&o.set("limit",String(r.limit));let s=o.size?`?${o.toString()}`:"";return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${s}`),"Failed to load App logs")}async function dp(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function gp(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function mp(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function fp(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}async function an(e){return u(await l.get(`/projects/${e}/model-access`))}async function cn(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function xS(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:o,previewHasError:s,previewIsLinkOnly:i}=e;return t||n?!1:o?s&&!i:r==="error"}function yp(e){return typeof e=="string"&&e.trim().length>0}function Zg(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return yp(t)||yp(n)||yp(r)}function SS(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 ln(e){if(!e)return!0;let t=SS(e.items);return t?!t.some(Zg):!Zg(e)}function ae(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function wS(e){return ae(e)==="bash"}function vS(e){let t=ae(e);return t==="question"||t==="ask"}function AS(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var em=new Set(["show","show_user"]);function hp(e){return em.has(ae(e))}function kS(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function bp(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Sr(e))}function Sr(e){let t=ae(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:ln(e.state?.input)}var tm=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function _p(e){return tm.has(ae(e))}var RS=50*1024*1024,Pp="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",IS=new RegExp(`^kortix-attachment://(${Pp})/(${Pp})/(${Pp})$`);function Sp(e){if(typeof e!="string")return null;let t=IS.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function TS(e){return Sp(e)!==null}var xp=new WeakMap;async function wp(e,t,n,r={}){if(n.size>RS)throw new Error("Attachments must be 50 MiB or smaller.");let o=`${e}/${t}`,s=r.attachmentId?void 0:xp.get(n)?.get(o);if(s?.promise)return s.promise;let i=s??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let c=xp.get(n)??new Map;c.set(o,i),xp.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 vp(e,t){let n=Sp(e);if(!n)throw new Error("Invalid attachment reference");let r=k().backendUrl.replace(/\/$/,""),o=await j(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!o.ok)throw new b("Could not load attachment",{status:o.status});return o.blob()}var CS=new Set(["show","show_user"]);function ES(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let o=r+5;if(o>=e.length||!/\s/.test(e[o])){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return t;let i=e.indexOf("</file>",s+1);if(i===-1)return t;t.push(e.slice(o,s).trimStart()),n=i+7}}var pt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),un=e=>typeof e=="string"&&e.length>0?e:null,nm=e=>typeof e=="string"?un(e.split("/").pop()):null;function wr(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function MS(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 OS(e,t){for(let n of ES(e))t(wr(n,"attachment"),wr(n,"filename")??nm(wr(n,"path")),wr(n,"mime"))}function jS(e,t){for(let n of[e,...MS(e.items)])pt(n)&&t(n.attachment,nm(n.path),null)}function DS(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!pt(r)||!pt(r.info)||!Array.isArray(r.parts))continue;let o=un(r.info.id);if(!o)continue;let s=un(r.info.role)??"unknown",i=(a,c,p)=>{let d=Sp(a);!d||n.has(a)||(n.add(a),t.push({url:a,attachment_id:d.attachmentId,filename:c,mime:p,message_id:o,role:s}))};for(let a of r.parts)pt(a)&&(a.type==="file"?i(a.url,un(a.filename),un(a.mime)):a.type==="text"&&typeof a.text=="string"?OS(a.text,i):a.type==="tool"&&typeof a.tool=="string"&&CS.has(ae(a.tool))&&pt(a.state)&&pt(a.state.input)&&jS(a.state.input,i))}return t}function vr(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function $S(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 US(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 Ap(e,t,n){return e!==void 0?e:$S(vr(t),n)}var kp={get disableMobileAdvertising(){return Ap(k().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Ap(k().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Ap(k().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var LS=new Set(["project-manager"]);function Ar(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:kp.enableProjects||!LS.has(e.name)}function FS(e){let t=e.agents.filter(Ar),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function rm(){return{projects:{list:Ge,listForAccount:hs,get:Kt,detail:qt,create:xs,createRepo:Ss,provision:ws,update:Wt,archive:Ht,llmCatalog:Gt,modelPicker:Bt,modelAccess:an,setModelAccess:cn,sandboxHealth:Yt,sandboxTemplates:ga,sessions:Be,createSession:We},github:{linkRepository:Is,replaceProjectRepository:Ts,getInstallation:Cs,listInstallations:Es,listLinkableInstallations:Ms,listRepositories:Os,listRepositoryBranches:js,linkInstallation:$s,saveInstallation:Ds,deleteInstallation:Ls,storeUserToken:Us},gitBackend:{get:Fs,repositories:Ns},connectStatus:ca,marketplace:{items:s=>Bu(s),item:s=>Vu(s),itemFile:(s,i)=>zu(s,i),marketplaces:()=>Wu(),featured:()=>Hu(),sources:{list:()=>Yu(),add:s=>Qu(s),remove:s=>Xu(s)}}}}function om(){return{billing:{accountState:jc,accountStateMinimal:Dc,transactions:$c,transactionsSummary:Uc,creditBreakdown:Lc,usageHistory:Fc,usageRollup:Jc,sessionCosts:{list:tl,get:sn},tierConfigurations:Nc,checkout:{createSession:n=>Kc(n),confirmSession:(n,r)=>qc(n,r)},subscription:{createPortalSession:(n,r)=>Gc(n,r),cancel:(n,r)=>Bc(n,r),reactivate:n=>Wc(n),scheduleDowngrade:(n,r,o)=>Hc(n,r,o),cancelScheduledChange:n=>Vc(n),prorationPreview:(n,r)=>zc(n,r)},credits:{purchase:n=>Yc(n),autoTopupSettings:n=>Qc(n),configureAutoTopup:n=>Xc(n)}},sandboxShares:{list:bu,create:_u,revoke:Pu}}}function le(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var we={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function Oe(){let e=vr("BACKEND_URL")||k().backendUrl;return e||"http://localhost:8008/v1"}function dn(e){let t=le(e);return t.endsWith("/v1")?t:`${t}/v1`}function pn(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=pn(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return pn(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function NS(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 Rp(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?`${Oe()}/p/${n.external_id}/${we.KORTIX_MASTER}`:""),status:NS(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 Ip(){let e=await Ge(),t=[];for(let n of e){let r=await Be(n.project_id).catch(()=>[]);for(let o of r)t.push({project:n,session:o,runtime:null,sandbox:Rp(n,o,null)})}return t.sort((n,r)=>{let o={active:0,provisioning:1,stopped:2,error:3},s=(o[n.sandbox.status]??99)-(o[r.sandbox.status]??99);return s!==0?s:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function He(e){let t=await Ip();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 dt=class extends Error{constructor(n,r,o){super(r);this.code=n;this.status=o;this.name="HeadlessAuthError"}code;status};async function z(e,t,n){let r=n?.fetch??k().fetch??((p,d)=>fetch(p,d)),o=le(n?.backendUrl??k().backendUrl??"");if(!o)throw new dt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let i=await r(`${dn(o)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:s,...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 dt(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 kr(e,t){return z("/auth/signup",{body:e},t)}function Rr(e,t){return z("/auth/sign-in/password",{body:e},t)}function Ir(e,t){return z("/auth/sign-in/magic-link",{body:e},t)}function Tr(e,t){return z("/auth/verify-otp",{body:e},t)}function Cr(e,t){return z("/auth/sign-in/oauth",{body:e},t)}function Er(e,t){return z("/auth/oauth/exchange",{body:e},t)}function gt(e,t){return z("/auth/refresh",{body:e},t)}function Mr(e,t){return z("/auth/password/reset",{body:e},t)}function Or(e,t,n){return z("/auth/password/update",{body:e,bearer:t},n)}function jr(e,t){return z("/auth/user",{bearer:e},t)}function Dr(e,t,n){return z("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function $r(e,t){return z("/auth/sign-in/sso",{body:e},t)}var Ur={enroll:(e,t,n)=>z("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function Lr(e,t={},n){return z("/auth/sign-out",{body:t,bearer:e},n)}function Fr(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,o=null,s=!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:o})):await e.storage.remove());for(let w of[...p])try{w(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(s)return r;if(!i){let w=c,L=(async()=>{let O=await e.storage.get();if(w===c&&O)try{let D=JSON.parse(O);D.session?.access_token&&D.session?.refresh_token&&(r=D.session,o=D.user??null)}catch{r=null}return s=!0,r})();i=L,L.then(()=>{i===L&&(i=null)},()=>{i===L&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let w=r.refresh_token,L=c,O=gt({refresh_token:w},e.request).then(async D=>(L!==c||(r=D.session,D.user&&(o=D.user),await m()),r)).catch(async D=>{if(L!==c)return r;let y=D&&typeof D=="object"&&"status"in D?D.status:0;if(y>=400&&y<500)return r=null,o=null,await m(),null;throw D}).finally(()=>{a===O&&(a=null)});a=O}return a}return{subscribe(w){return p.add(w),()=>{p.delete(w)}},current:()=>r,user:()=>o,load:f,async set(w,L){await f(),c+=1,a=null,r=w,L!==void 0&&(o=L),w||(o=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,o=null,s=!0,await m()}}}function sm(){return{list:Yo,get:Xo,create:Qo,secretResources:{list:bi,create:_i,rotate:Pi,remove:xi,grant:Si,revoke:wi,setAccess:vi},updateName:Jo,branding:{get:Zo,update:es,uploadAsset:ts,removeAsset:ns,reset:rs},leave:fs,members:os,invite:ss,removeMember:gs,updateMemberRole:ms,invites:is,cancelInvite:as,resendInvite:cs,tokens:{list:ku,create:Ru,revoke:Iu},connectedApps:{list:Tu,revoke:Cu},audit:{log:Du,export:Uu,webhooks:{list:Lu,create:Fu,update:Nu,remove:Ku}}}}function im(){return{assignments:{list:iu,create:au,revoke:cu},permissions:{list:lu,forRole:Hl},roles:{list:Gl,create:zl,update:Yl,setPermissions:Ql,remove:Xl,usage:Vl},groups:{list:Dl,get:$l,create:Ul,update:Ll,remove:Fl,members:{list:Nl,add:Kl,remove:ql}},agentIdentities:Bl,oauthClients:{list:eu,get:tu,create:nu,update:ru,rotateSecret:ou,remove:su},can:Jl,canBatch:Zl}}function am(){let e={signUp:kr,signInWithPassword:Rr,sendMagicLink:Ir,verifyOtp:Tr,signInWithProvider:Cr,exchangeCode:Er,refresh:gt,resetPassword:Mr,updatePassword:Or,updateUserMetadata:Dr,signInWithSso:$r,mfa:Ur,user:jr,signOut:Lr,session:Fr},t=sm(),n=im();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:ls,describe:us,accept:ps,decline:ds}}}var gn=new Map,Tp=new Map;function Cp(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function cm(e){return gn.get(Cp(e))??null}function lm(){return[...gn.values()].filter(e=>typeof e=="string")}function um(e){return gn.has(Cp(e))}async function mt(e){let t=Cp(e),n=gn.get(t);if(n!==void 0)return n;let r=Tp.get(t);if(r)return r;let o=(async()=>{try{let s=await l.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!s.success)return null;let i=typeof s.data?.preview_url_template=="string"?s.data.preview_url_template:null;return gn.set(t,i),i}catch{return null}finally{Tp.delete(t)}})();return Tp.set(t,o),o}function pm(e){let{apiBaseUrl:t}=e;return um(t)||mt(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:cm(t)}}function dm(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new b(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let o=k().backendUrl??e.backendUrl,s=80,i=t(o);return i&&(s=i.port?Number(i.port):i.protocol==="https:"?443:80),pm({sandboxId:r,apiBaseUrl:o,backendPort:s})}}function gm(e,t){let n=null;async function r(){n||(n=en(e,t,{showErrors:!1}).then(o=>{let s=bc(o)??"",i=s.indexOf("/"),a=i>0&&i<s.length-1?{providerID:s.slice(0,i),modelID:s.slice(i+1)}:void 0,c=o.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(o){throw n=null,o}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var mn=new Map;function mm(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 o=n?.evidence?.error;return o&&o!==n?.message&&r.push(o),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Ve=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 ft={url:null,sandboxId:null,dbSandboxId:null,version:0},qS=new Set;function fm(e,t=null,n=null){if(!(ft.url===e&&ft.sandboxId===t&&ft.dbSandboxId===n)){ft={url:e,sandboxId:t,dbSandboxId:n,version:ft.version+1};for(let r of qS)r()}}function ym(){return ft.url}function hm(e,t){async function n(r){let o=Date.now()+r,s=()=>Math.max(0,o-Date.now()),i=await Ee(e,t,Math.min(3e4,s()));for(;Date.now()<o&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,s()))),i=await Ee(e,t,Math.min(3e4,s()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new b(mm(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new b("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=lt(c);return fm(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function bm(e,t,n){let r=null;function o(){if(r)return r;let p=Lg(e,t);return p&&(r=p),r}let s=hm(e,t);async function i(p){let d=o();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=mt(k().backendUrl??n.backendUrl).catch(()=>null),f=`${e}
15
+ ${t}`,h=mn.get(f);if(h)return r=await h,await m,r;let w=s(g);mn.set(f,w);try{return r=await w,await m,r}finally{mn.get(f)===w&&mn.delete(f)}}function a(p){let d=o();if(!d)throw new Ve(p);return d}function c(){r=null,Ng(e,t)}return{ensureReady:i,tryResolveReady:o,requireReady:a,forgetReady:c}}var K=["directory","workspace"],_m=["messageID","model","agent","noReply","tools","format","system","variant","parts"],R=(e,t,n=K,r=[],o)=>({method:e,path:t,query:n,body:r,bodyParam:o}),GS={"session.list":R("GET","/session",[...K,"scope","path","roots","start","search","limit"]),"session.get":R("GET","/session/{sessionID}"),"session.create":R("POST","/session",K,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":R("DELETE","/session/{sessionID}"),"session.update":R("PATCH","/session/{sessionID}",K,["title","metadata","permission","time"]),"session.status":R("GET","/session/status"),"session.messages":R("GET","/session/{sessionID}/message",[...K,"limit","before"]),"session.prompt":R("POST","/session/{sessionID}/message",K,_m),"session.promptAsync":R("POST","/session/{sessionID}/prompt_async",K,_m),"session.abort":R("POST","/session/{sessionID}/abort"),"session.revert":R("POST","/session/{sessionID}/revert",K,["messageID","partID"]),"session.unrevert":R("POST","/session/{sessionID}/unrevert"),"session.summarize":R("POST","/session/{sessionID}/summarize",K,["providerID","modelID","auto"]),"session.command":R("POST","/session/{sessionID}/command",K,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":R("POST","/session/{sessionID}/share"),"session.unshare":R("DELETE","/session/{sessionID}/share"),"session.fork":R("POST","/session/{sessionID}/fork",K,["messageID"]),"session.diff":R("GET","/session/{sessionID}/diff",[...K,"messageID"]),"session.todo":R("GET","/session/{sessionID}/todo"),"permission.list":R("GET","/permission"),"permission.reply":R("POST","/permission/{requestID}/reply",K,["reply","message"]),"question.list":R("GET","/question"),"question.reply":R("POST","/question/{requestID}/reply",K,["answers"]),"question.reject":R("POST","/question/{requestID}/reject"),"part.update":R("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",K,[],"part"),"part.delete":R("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":R("GET","/file",[...K,"path"]),"file.read":R("GET","/file/content",[...K,"path"]),"find.files":R("GET","/find/file",[...K,"query","dirs","type","limit"]),"vcs.diff":R("GET","/vcs/diff",[...K,"mode","context"]),"global.health":R("GET","/global/health",[]),"global.dispose":R("POST","/global/dispose",[]),"global.config.get":R("GET","/global/config",[]),"global.config.update":R("PATCH","/global/config",[],[],"config"),"provider.list":R("GET","/provider"),"provider.auth":R("GET","/provider/auth"),"provider.oauth.authorize":R("POST","/provider/{providerID}/oauth/authorize",K,["method","inputs"]),"provider.oauth.callback":R("POST","/provider/{providerID}/oauth/callback",K,["method","code"]),"auth.set":R("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":R("GET","/agent"),"app.skills":R("GET","/skill"),"app.log":R("POST","/log",K,["service","level","message","extra"]),"command.list":R("GET","/command"),"tool.ids":R("GET","/experimental/tool/ids"),"tool.list":R("GET","/experimental/tool",[...K,"provider","model"]),"mcp.status":R("GET","/mcp"),"mcp.add":R("POST","/mcp",K,["name","config"]),"mcp.connect":R("POST","/mcp/{name}/connect"),"mcp.disconnect":R("POST","/mcp/{name}/disconnect"),"mcp.auth.start":R("POST","/mcp/{name}/auth"),"mcp.auth.callback":R("POST","/mcp/{name}/auth/callback",K,["code"]),"mcp.auth.remove":R("DELETE","/mcp/{name}/auth"),"project.list":R("GET","/project"),"project.current":R("GET","/project/current"),"path.get":R("GET","/path")};function BS(e,t){let n=[];for(let r of e.query){let o=t[r];o!=null&&n.push(`${r}=${encodeURIComponent(String(o))}`)}return n.length?`?${n.join("&")}`:""}function WS(e,t,n={},r={}){let o=GS[t],s=o.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(o.bodyParam)i=n[o.bodyParam],a=i!==void 0;else for(let p of o.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(/\/$/,"")}${s}${BS(o,n)}`,{method:o.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function HS(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 VS(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=HS(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 o=await r.text(),s=o;try{s=JSON.parse(o)}catch{}return{error:s||{},request:t,response:r}}function Ep(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let o=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!o.ok)throw Object.assign(new Error(`SSE failed: ${o.status} ${o.statusText}`),{status:o.status});if(!o.body)throw new Error("No body in SSE response");let s=o.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{s.cancel()}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:c,value:p}=await s.read();if(c)break;a=(a+p).replace(/\r\n/g,`
16
16
  `).replace(/\r/g,`
17
17
  `);let d=a.split(`
18
18
 
19
19
  `);a=d.pop()??"";for(let g of d){let m={},f=[];for(let h of g.split(`
20
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 w=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(w)||(m.retry=w)}f.length&&(m.data=f.join(`
21
- `)),yield m}}}finally{r.removeEventListener("abort",i),s.releaseLock()}}}async function*zS(e,t,n){let r=e.eventTransport??Op(e.fetch??globalThis.fetch),o=n.signal??new AbortController().signal,s=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!o.aborted;a++)try{let l=new Headers(n.headers);i!==void 0&&l.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:l,signal:o}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(s=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(l){if(n.onSseError?.(l),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(s*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function yn(e){let t=o=>(s,i)=>VS(e,WS(e.baseUrl,o,s,i)),n=o=>s=>t(o)(void 0,s);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"),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(o={})=>({stream:zS(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,o)}),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 Am=200;async function YS(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 Qe(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new b(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function km(e){let t=e.runtimeUrl.replace(/\/$/,""),n=yn({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let o=encodeURIComponent(r.conversationId??e.rootId),s=async(l,p)=>{let d=new URLSearchParams;l!==void 0&&d.set("limit",String(l)),p&&d.set("before",p);let g=`/messages/${o}${d.size?`?${d}`:""}`,m=w=>e.fetch(new Request(`${t}${w}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new b(`Reading the session transcript failed: ${await YS(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await s(r.limit===void 0?void 0:Math.min(r.limit,Am),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await s(Math.min(r.limit-a.length,Am),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,o,s]=await Promise.all([n.session.status().then(i=>Qe(i,"Reading the session status failed")),n.permission.list().then(i=>Qe(i,"Reading permission requests failed")),n.question.list().then(i=>Qe(i,"Reading questions failed"))]);return{statuses:r??{},permissions:o??[],questions:s??[]}},answerPermission:async(r,o,s)=>{Qe(await n.permission.reply({requestID:r,reply:o,...s!==void 0?{message:s}:{}}),"Answering the permission request failed")},answerQuestion:async(r,o)=>{if(o===null){Qe(await n.question.reject({requestID:r}),"Dismissing the question failed");return}Qe(await n.question.reply({requestID:r,answers:o}),"Answering the question failed")},compact:async r=>{let o=r;if(!o){let s=await n.global.config.get().then(l=>l.error===void 0?l.data:null),i=typeof s?.model=="string"?s.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(o={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!o)throw new b("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return Qe(await n.session.summarize({sessionID:e.rootId,providerID:o.providerID,modelID:o.modelID}),"Compacting the session failed"),o}}}function Rm(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return km({runtimeUrl:r,rootId:n,fetch:j})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,o)=>(await t()).answerPermission(n,r,o),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function Im(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await _c(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var bt=BigInt(4096),Ae=BigInt(0xffffffffffff),Tm=Ae+BigInt(1),QS=Tm/BigInt(2),De=BigInt(3600*1e3)*bt,Nr=120*1e3,Cm=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,XS=/^msg_([0-9a-f]{12})/,Em="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Xe(e){let t=XS.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function _t(e){return BigInt(Math.trunc(e))*bt&Ae}function Je(e,t){let n=e-t&Ae;return n>=QS&&(n-=Tm),n}function jp(e){let t=null;for(let n of e)n!=null&&(t===null||Je(n,t)>BigInt(0))&&(t=n);return t}function Mm(e,t){let n=Xe(e);return n===null?!1:Je(n,_t(t))>De}function Om(e,t){let n=t===void 0?null:_t(t);return jm(e,r=>n===null||Je(r,n)<=De)}function jm(e,t){let n=[];for(let r of e){let o=Xe(r);o!==null&&t(o)&&n.push(o)}return jp(n)}function JS(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Em[n%62])}return e}function Dp(e){let t=e.random,n=_t(e.nowMs-(e.backdateMs??Nr)),r=e.newestKnownTime??null;if(r!==null){let s=Je(r,n);s>=BigInt(0)&&s<=De&&(n=r+BigInt(1)&Ae)}let o="";if(t)for(let s=0;s<14;s++)o+=Em[Math.min(61,Math.floor(t()*62))];else o=JS();return{id:`msg_${n.toString(16).padStart(12,"0")}${o}`,time:n}}function Kr(e={}){let t=e.nowMs??Date.now(),n=_t(t-Nr),r=jm(e.after??[],o=>{let s=Je(o,n);return s>=BigInt(0)&&s<=De});return Dp({nowMs:t,newestKnownTime:r}).id}function Dm(e){return{scope:()=>hc(e.projectId,e.sessionId),providerSecretPool:{list:()=>Ii(e.projectId,e.sessionId),get:t=>Ri(e.projectId,e.sessionId,t),set:(t,n)=>Ti(e.projectId,e.sessionId,t,n)},rescope:t=>bc(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,o=n?.agent??e.agent,s=r&&o?{}:await e.persistedPromptDefaults(),i=r??s.model,a=o??s.agent,l=Kr(),p=await rn(e.projectId,e.sessionId,{clientMessageId:l,messageId:l,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new b("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var ZS="kortix.transcript.v1",$m=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function ew(e){return typeof e=="string"&&$m.includes(e)}var tw=["once","always","reject"],nw=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];function ke(){let e=xm();return e||(k().billingEnabled??!1?"":Bg())}async function $p(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Up(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function Lp(e){let t=Up(e),n=await j(`${t}/env`);if(!n.ok)throw new Error(await $p(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Fp(e,t,n){let r=Up(e),o=await j(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!o.ok)throw new Error(await $p(o,"Failed to save secret"))}async function Np(e,t){let n=Up(e),r=await j(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await $p(r,"Failed to delete secret"))}var Um={list:Lp,set:Fp,delete:Np};async function Lm(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let o=await j(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),s=await o.json();if(!o.ok)throw new Error(s?.error||s?.message||`Request failed with ${o.status}`);return s}async function qr(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function hn(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return ce(e)}async function qp(e){let t=hn(e),n=await j(`${t}/kortix/pty`);if(!n.ok)throw new Error(await qr(n,"Failed to list terminals"));return n.json()}async function Gp(e,t){let n=hn(e),r=await j(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await qr(r,"Failed to create terminal"));return r.json()}async function Bp(e,t,n){let r=hn(e),o=await j(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(await qr(o,"Failed to update terminal"));return o.json()}async function Wp(e,t){let n=hn(e),r=await j(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await qr(r,"Failed to remove terminal"))}async function Hp(e,t,n){let r=hn(t),s=`${(()=>{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://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await lt();a&&i.set("token",a),n?.wake&&i.set("wake","1");let l=i.toString();return l?`${s}${s.includes("?")?"&":"?"}${l}`:s}function Fm(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 $e="\x1B",Nm="\x07",rw="\0",Kp=`(?:${Nm}|${$e}\\\\)`,ow=[new RegExp(`${$e}\\]697;[^${Nm}${$e}]*${Kp}`,"g"),new RegExp(`${rw}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${$e}\\][0-9]+;rgb:[0-9a-fA-F/]+${Kp}`,"g"),new RegExp(`${$e}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Kp}`,"g"),new RegExp(`${$e}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${$e}\\[\\d+;\\d+R`,"g"),new RegExp(`${$e}\\[\\?[0-9;]*c`,"g")];function Km(e){let t=e;for(let n of ow)t=t.replace(n,"");return t}var qm={list:qp,create:Gp,update:Bp,remove:Wp,webSocketUrl:Hp};async function I(e,t,n,r){let o=e;for(;o.endsWith("/");)o=o.slice(0,-1);let s=await j(`${o}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await s.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!s.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${s.status}`);return a}async function sw(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 I(e,`/kortix/tasks${r}`)}async function iw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function aw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function cw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function lw(e,t){return I(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function uw(e,t,n){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function pw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function dw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function gw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function mw(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return I(e,`/kortix/tickets${n}`)}async function fw(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function yw(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function hw(e,t){return I(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function bw(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function _w(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function Pw(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function xw(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function Sw(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function ww(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function vw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function Aw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function kw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function Rw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function Iw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function Tw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function Cw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function Ew(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function Mw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function Ow(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function jw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Dw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function $w(e,t,n=200){return I(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function Uw(e){return I(e,"/kortix/projects")}async function Lw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function Fw(e,t){return I(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function Nw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function Kw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function qw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function Gw(e,t,n="all"){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function Bw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function Ww(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function Hw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function Vw(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function zw(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function Yw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function Qw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Xw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function Jw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function Zw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function ev(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function tv(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var nv=1e4,rv={retryOnAuthError:!1};function Pt(e,t,n){return I(e,t,{signal:AbortSignal.timeout(nv),...n},rv)}async function ov(e,t=!1){return(await Pt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function sv(e){return(await Pt(e,"/kortix/services/templates")).templates??[]}async function iv(e,t){return(await Pt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function av(e,t,n){let r=n==="delete",o=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return Pt(e,o,{method:r?"DELETE":"POST"})}async function cv(e,t){return Pt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function lv(e,t){return Pt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Gr=new Map,xt=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function Ue(){let e=ke();if(!e)throw new xt;return fe(e)}function fe(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Gr.get(e);if(t)return t;if(!Vn())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=yn({baseUrl:e,fetch:j,eventTransport:uv});return Gr.set(e,n),n}var uv=async function*(e){let t=k().eventStreamTransport;if(!t){yield*Op(j)(e);return}let{headers:n,rejected:r}=await Ag(e.url,e.headers);try{yield*t({...e,headers:n})}catch(o){throw o?.status===401&&r(),o}};function pv(e){Gr.delete(e)}function dv(){Gr.clear()}var Br=new Map;function gv(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=Br.get(e);if(t)return t;let n=yn({baseUrl:e,fetch});return Br.set(e,n),n}function mv(e){Br.delete(e)}function fv(){Br.clear()}async function yv(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 hv(e){let t=ke();if(!t)throw new b("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await j(`${t}${n}`,{method:"POST"}),o=r.headers.get("content-type")??"",s=/^application\/([\w.+-]+\+)?json\b/i.test(o.trim());if(!r.ok)throw new b(`System reload failed (${r.status}): ${await yv(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!s)throw new b(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(l){throw new b(`System reload returned malformed JSON from ${n}: ${l instanceof Error?l.message:String(l)}`,{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 Gm="frontend";function Wr(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Gm}] ${t}`,...n?[n]:[]);try{Ue().app.log({service:Gm,level:e,message:t,extra:n})}catch{}}var Le={debug:(e,t)=>Wr("debug",e,t),info:(e,t)=>Wr("info",e,t),warn:(e,t)=>Wr("warn",e,t),error:(e,t)=>Wr("error",e,t)};function Bm(e){return{type:"heartbeat-gap",gapMs:e}}function Wm(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 bv={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},_v=16,Pv=8,xv=6e4,Sv=5e3,wv=250,vv=1e3,Av=3e4,kv=5,Rv=3e3,Iv=3e4,Tv=2e4,Cv=2e3,Ev=8;function Mv(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function Ov(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 o=e.coalesced??[e];return o.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:o}}function Hm(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 Hr=new WeakMap;function jv(e,t,n){let r=t.timers??bv,o=t.connectTimeoutMs??Tv,s=t.heartbeatTimeoutMs??xv,i=t.maxConsecutiveHardFailures??Ev,a=new AbortController;function l(y,...P){for(let v of n){let $=y(v);if($)try{$(...P)}catch(x){console.warn("[opencode-events] subscriber handler threw, skipping",x)}}}let p=null,d=y=>{p!==y&&(p=y,y&&l(P=>P.onConnectionChange,y))},g=r.now(),m=null,f=[],h,w=0,L=new Map,O=()=>{if(h&&r.clearTimeout(h),h=void 0,f.length===0)return;let y=f;f=[],L.clear(),w=r.now(),g=r.now();for(let P of y)P&&l(v=>v.onEvent,P.event)},D=()=>{if(h)return;let y=r.now()-w;h=r.setTimeout(O,Math.max(0,_v-y))};return(async()=>{let y=0,P=0;for(;!a.signal.aborted;){let v=!1,$=!1,x=!1,_,A,T=null,C=r.now(),E=new AbortController;d("connecting");let F=Hm(a.signal);F.promise.then(()=>E.abort());try{let ie=await new Promise((ot,Ke)=>{let re=!1;A=r.setTimeout(()=>{re||(re=!0,Le.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:o}),E.abort(),Ke(new Error(`SSE connect timed out after ${o}ms`)))},o),e.global.event({signal:E.signal,sseDefaultRetryDelay:Rv,sseMaxRetryDelay:Iv,sseMaxRetryAttempts:1}).then(_e=>{re||(re=!0,r.clearTimeout(A),ot(_e))},_e=>{re||(re=!0,r.clearTimeout(A),Ke(_e))})}),{stream:V}=ie;if(m){let ot=r.now()-m.lastActivityAt,Ke=m.eventful;m=null,(Ke||ot>Sv)&&l(re=>re.onGapRehydrate,ot)}g=r.now();let te=()=>{r.clearTimeout(_),_=r.setTimeout(()=>{Le.warn("SSE heartbeat timeout, forcing reconnect"),E.abort()},s)};te();let rt=r.now(),Sb=V[Symbol.asyncIterator]();for(;!E.signal.aborted;){let ot=Sb.next().then(Pe=>({kind:"next",result:Pe}),Pe=>({kind:"error",error:Pe})),Ke=Hm(E.signal),re=await Promise.race([ot,Ke.promise.then(()=>({kind:"aborted"}))]);if(Ke.cleanup(),re.kind==="aborted")break;if(re.kind==="error")throw re.error;if(re.result.done)break;v=!0,d("open"),te();let _e=re.result.value,st=_e&&typeof _e=="object"&&"payload"in _e?_e.payload:_e;if(!st?.type)continue;st.type!=="server.connected"&&($=!0);let To=Ov(f[f.length-1]?.event,st);if(To)f[f.length-1]={type:To.type,event:To};else{let Pe=Mv(st);if(Pe){let pg=L.get(Pe);pg!==void 0&&(f[pg]=void 0),L.set(Pe,f.length)}f.push({type:st.type,event:st})}D(),!(r.now()-rt<Pv)&&(rt=r.now(),await new Promise(Pe=>r.setTimeout(Pe,0)))}x=v}catch(ie){if(a.signal.aborted)break;T=ie;let V=String(ie),te=V.includes("401")||V.includes("403")||V.includes("Unauthorized")||V.includes("Token refresh failed");if(Le.error("SSE event stream error",{error:V,retryCount:y,isAuthError:te}),te)try{ir(),await sr(),Le.info("SSE: refreshed auth token after auth error")}catch(rt){Le.error("SSE: failed to refresh auth token",{error:String(rt)})}}finally{r.clearTimeout(_),r.clearTimeout(A),E.abort(),F.cleanup(),O()}if(a.signal.aborted)break;let ee=r.now()-C,Q=T?.cause?.status;if(P=!v&&(typeof Q=="number"&&Q>=400||ee<Cv)?P+1:0,P>=i){Le.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:P,lastError:String(T)}),p=null,l(ie=>ie.onParked,{consecutiveFailures:P,lastError:T});break}d("lost"),m={lastActivityAt:g,eventful:(m?.eventful??!1)||$},x?y=0:(y++,y>1&&Le.warn("SSE event stream reconnecting",{retryCount:y}));let Ce=x?wv:Math.min(vv*2**Math.min(y-1,kv),Av);await new Promise(ie=>{let V=r.setTimeout(ie,Ce),te=()=>{r.clearTimeout(V),ie()};a.signal.addEventListener("abort",te,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,teardown:()=>{p=null,a.abort(),h&&r.clearTimeout(h)}}}function Vr(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o,signal:s}=e,i=e.client??(e.url?fe(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o},l=Hr.get(i);if(!l)l=jv(i,e,new Set([a])),Hr.set(i,l);else{l.subscribers.add(a);let f=l.connectionState();f&&o?.(f)}let p=l,d=!1,g=()=>{d||(d=!0,s&&s.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),Hr.get(i)===p&&Hr.delete(i)))},m=()=>g();return s&&(s.aborted?g():s.addEventListener("abort",m,{once:!0})),{close:g}}function Vm(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return fe(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return fe(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return fe(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return Vr({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Xm(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new b(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function vt(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 J(e){let t=(e??ke()).trim();if(!t)throw new xt;return t}async function Yr(e,t){let n=await j(`${J(t)}${e}`);if(!n.ok)throw new b(await vt(n),{status:n.status,response:n});return n.json()}var Qr=["/workspace","/tmp","/home","/opt"],Dv=Qr.filter(e=>e!=="/workspace");function Yp(e){return Qr.some(t=>e===t||e.startsWith(`${t}/`))}function At(e){return Yp(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function Ze(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(Dv.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Qp=Ze;async function kt(e,t){let n=J(t),r=Ze(e)||".";return(await Yr(`/file?path=${encodeURIComponent(r)}`,n)).map(s=>({...s,path:s.absolute||`/workspace/${s.path}`}))}async function Rt(e,t){let n=J(t),r=Ze(e),o=await j(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!o.ok)throw new b(await vt(o),{status:o.status,response:o});return o.json()}async function $v(e,t,n){let r=J(n),o=Ze(e),s=await j(`${r}/file/raw?path=${encodeURIComponent(o)}`);if(!s.ok)throw new b(await vt(s),{status:s.status,response:s});if((s.headers.get("content-type")||"").includes("text/html"))throw new b("File could not be loaded (raw byte route unavailable)",{status:s.status,response:s,code:"INVALID_CONTENT_TYPE"});let i=await s.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}async function It(e,t){let n=J(t);try{return await $v(e,void 0,n)}catch{}let r=await Rt(e,n);if(r.encoding==="base64"&&r.content){let o=Uint8Array.from(atob(r.content),s=>s.charCodeAt(0));return new Blob([o],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}async function _n(e){return Yr("/file/status",J(e))}async function Pn(e,t,n){let r=J(n),o=new URLSearchParams({query:e});return t?.type&&o.set("type",t.type),t?.limit&&o.set("limit",String(t.limit)),Yr(`/find/file?${o.toString()}`,r)}async function xn(e,t){let n=J(t);return(await Yr(`/find?pattern=${encodeURIComponent(e)}`,n)).map(o=>({path:typeof o.path=="string"?o.path:o.path?.text??"",lines:typeof o.lines=="string"?o.lines:o.lines?.text??"",line_number:o.line_number,absolute_offset:o.absolute_offset,submatches:(o.submatches??[]).map(s=>({start:s.start,end:s.end}))}))}var bn=[400,1200],Uv=e=>e===408||e===429||e===502||e===503||e===504,zm=e=>new Promise(t=>setTimeout(t,e));function Lv(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Vp=3e4,Fv=15*6e4,Nv=256;function St(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Vp;let t=Vp+e/Nv;return Math.min(Fv,Math.max(Vp,Math.round(t)))}async function Kv(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 zr(e,t){let n;for(let o=0;o<=bn.length;o++){let s;try{s=await t(e())}catch(a){if(n=a,Lv(a)||o===bn.length)break;await zm(bn[o]);continue}if(s.ok)return s.json();let i=await Kv(s);if(n=new b(`Upload failed (${s.status}): ${i}`,{status:s.status,response:s}),!Uv(s.status)||o===bn.length)throw n;await zm(bn[o])}if(n instanceof b)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new b(`Upload failed: ${r}`)}var zp=8*1024*1024;function qv(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new b(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Ym(e,t){try{e?.onProgress?.(t)}catch{}}function Qm(e,t,n){let r=new FormData,o=(t??"").trim();return o&&r.append("path",o.startsWith("/")?o:`/${o}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function Gv(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function Tt(e,t,n,r,o){let s=typeof r=="string"?r:void 0,i=typeof r=="string"?o:r,a=J(s),l=St(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=zp){let f=await zr(()=>Qm(e,t,p),h=>j(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:l}));return qv(f[0],e.size),Ym(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await zr(()=>Qm(new Blob([],{type:e.type}),t,p),f=>j(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:St(0)})))[0]?.path;if(!g)throw new b("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=Gv(g);if(!m.name)throw new b(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=zp){let h=Math.min(e.size,f+zp),w=e.slice(f,h,e.type),L=await zr(()=>{let O=new FormData;return m.parent&&O.append("path",m.parent),O.append("filename",m.name),O.append("first",f===0?"true":"false"),O.append("offset",String(f)),O.append("file",w,m.name),O},O=>j(`${a}/file/append`,{method:"POST",body:O},{timeoutMs:St(w.size)}));if(L.path!==g||L.size!==h)throw new b(`Upload verification failed for ${g}: expected ${h} bytes, received ${L.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Ym(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await et(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function Bv(e,t,n){let r=J(n),o=St(t.size);return zr(()=>{let s=new FormData;return s.append(e,t,e.split("/").pop()||"file"),s},s=>j(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:o}))}var wt=class extends b{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function Sn(e,t){let n=J(t),r=e.trim(),s=(r.startsWith("/")?r:`/${r}`).split("/"),i=s.pop()||"untitled",a=s.join("/")||"/workspace",l=At(`${a}/${i}`),p=[];try{p=await kt(Jm(l),n)}catch(g){if(!(g instanceof b&&g.status===404))throw g}if(p.some(g=>g.name===Zm(l)))throw new wt(l);let d=await ef(l,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function wn(e,t,n){let r=J(n);return Bv(t,await It(e,r),r)}function Wv(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Jm(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Zm(e){return e.slice(e.lastIndexOf("/")+1)}function Hv(){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 vn(e,t,n){let r=J(n),o=At(Wv(e.trim()));return ef(o,t,r,{overwrite:!0})}async function ef(e,t,n,r){let o=Zm(e);if(!o)throw new b(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let s=Jm(e);await Ct(s,n).catch(()=>{});let i=Hv(),a=await Tt(t,s,`.${o}.kortix-write-${i}`,n),l=a[0]?.path;if(!l)throw new b(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=At(l);try{await tf(p,e,n,r.overwrite)}catch(g){throw await et(p,n).catch(()=>{}),!r.overwrite&&g instanceof b&&g.status===409?new wt(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function et(e,t){let n=await j(`${J(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Delete failed (${n.status}): ${await vt(n)}`,{status:n.status,response:n});return n.json()}async function Ct(e,t){let n=await j(`${J(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Mkdir failed (${n.status}): ${await vt(n)}`,{status:n.status,response:n});return n.json()}async function An(e,t,n){return tf(e,t,J(n),!0)}async function tf(e,t,n,r){let o=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(!o.ok)throw new b(`Rename failed (${o.status}): ${await vt(o)}`,{status:o.status,response:o});return o.json()}async function Xp(){return Xm(await Ue().project.current())}async function Xr(){return Xm(await Ue().global.health())}async function Jp(){try{return(await Xr()).healthy===!0}catch{return!1}}var nf={list:kt,read:Rt,readBlob:It,status:_n,findFiles:Pn,findText:xn,upload:Tt,write:vn,create:Sn,copy:wn,remove:et,mkdir:Ct,rename:An,currentProject:Xp,health:Xr,isReachable:Jp,toDaemonPath:Ze,toSandboxAbsolutePath:At,toWorkspaceRelative:Qp};function rf(e){return{list:async t=>kt(t,(await e()).runtimeUrl),read:async t=>Rt(t,(await e()).runtimeUrl),readBlob:async t=>It(t,(await e()).runtimeUrl),status:async()=>_n((await e()).runtimeUrl),findFiles:async(t,n)=>Pn(t,n,(await e()).runtimeUrl),findText:async t=>xn(t,(await e()).runtimeUrl),upload:async(t,n,r,o)=>Tt(t,n,r,(await e()).runtimeUrl,o),write:async(t,n)=>vn(t,n,(await e()).runtimeUrl),create:async t=>Sn(t,(await e()).runtimeUrl),copy:async(t,n)=>wn(t,n,(await e()).runtimeUrl),remove:async t=>et(t,(await e()).runtimeUrl),mkdir:async t=>Ct(t,(await e()).runtimeUrl),rename:async(t,n)=>An(t,n,(await e()).runtimeUrl)}}function of(e){return{get:t=>nn(e.projectId,e.sessionId,t),presence:t=>c.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1}),cost:()=>cn(e.sessionId,{projectId:e.projectId}),update:t=>dc(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),gc(e.projectId,e.sessionId)),start:(...t)=>Oe(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),on(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),sn(e.projectId,e.sessionId)),configState:()=>mc(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),fc(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),yc(e.projectId,e.sessionId,...t)),setSharing:t=>Ya(e.projectId,e.sessionId,t),previews:()=>Xa(e.projectId,e.sessionId),participants:()=>Qa(e.projectId,e.sessionId),commit:t=>Wa(e.projectId,e.sessionId,t),publicShares:{list:()=>Ja(e.projectId,e.sessionId),create:(...t)=>Za(e.projectId,e.sessionId,...t),revoke:(...t)=>ec(e.projectId,e.sessionId,...t)}}}function sf(e){return{reminders:{list:()=>wu(e.projectId,e.sessionId),create:t=>vu(e.projectId,e.sessionId,t),update:(t,n)=>Au(e.projectId,e.sessionId,t,n),remove:t=>ku(e.projectId,e.sessionId,t)},audit:(t,n)=>rc(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Ap(e.projectId,e.sessionId,t,n),read:(t,n)=>kp(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>oc(e.projectId,e.sessionId,t),messageAuthors:()=>xc(e.projectId,e.sessionId),transcriptSync:t=>sc(e.projectId,e.sessionId,t),turn:()=>ic(e.projectId,e.sessionId),prompts:{create:t=>rn(e.projectId,e.sessionId,t),list:()=>ac(e.projectId,e.sessionId),remove:t=>cc(e.projectId,e.sessionId,t),retry:t=>uc(e.projectId,e.sessionId,t),edit:(t,n)=>lc(e.projectId,e.sessionId,t,n),hold:t=>pc(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function af(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var zv=["control_plane","provider_ingress","daemon","upstream_port"];function Zp(e){return typeof e=="string"&&zv.includes(e)?e:null}function ed(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 td(e,t){let n=(e===void 0?ke():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await j(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),o=await r.text().catch(()=>""),s=null;try{s=o?JSON.parse(o):null}catch{s=null}let i=s,a=Zp(r.headers.get("X-Kortix-Proxy-Hop"))??Zp(s?.hop),l=Number(r.headers.get("X-Kortix-Upstream-Status")),p=s?.upstream_status,d=Number.isFinite(l)&&l>0?l:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:o,hop:a,upstreamStatus:d}}var cf=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,lf=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,uf=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,pf=new Set([22,4096,parseInt(ve.KORTIX_MASTER,10)]);function Yv(e){return lf.test(e)}function Jr(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 Qv(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var Xv=new Set(["'",'"',"`","<","(","["]),Jv=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function Zv(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&&Xv.has(e[t]);)t++;for(;n>t&&Jv.has(e[n-1]);)n--;return e.slice(t,n)}function eA(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var tA=/^\/proxy\/(\d{1,5})(\/.*)?$/,nA=/^\/(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 df(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:nA.test(t.pathname)}catch{return!1}}function Rn(e){if(!e)return null;let t=Zv(Qv(e.trim())),n=rd(t);if(n){let r=Jr(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 o=parseInt(r.port,10);if(!Number.isInteger(o)||o<1||o>65535)return null;let s=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(ve.KORTIX_MASTER,10);if(o===i){let l=r.pathname.match(tA);if(l){let p=parseInt(l[1],10);if(p>=1&&p<=65535)return o=p,s=Jr(`${l[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${o}${s}`,port:o,path:s}}}let a=Jr(s);return{originalUrl:`${r.protocol}//${r.hostname}:${o}${a}`,port:o,path:a}}catch{let r=eA(e);return r&&r!==e?Rn(r):null}}function rA(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let o=/`[^`\n]+`/g;for(;(r=o.exec(e))!==null;){let s=r.index,i=s+r[0].length;t.some(([l,p])=>s>=l&&i<=p)||t.push([s,i])}return t}function oA(e,t){return t.some(([n,r])=>e>=n&&e<r)}function gf(e){let t=[],n=new Set,r=rA(e);cf.lastIndex=0;let o;for(;(o=cf.exec(e))!==null;){let s=Rn(o[0]);if(!s)continue;let{originalUrl:i,port:a,path:l}=s;a<1||a>65535||pf.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:l,startIndex:o.index,endIndex:o.index+i.length,inCodeBlock:oA(o.index,r)}))}return t}function sA(e){return gf(e).length>0}function iA(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function mf(e){return e.trim().toLowerCase().split("_").join("-")}function ff(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function aA(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let o=r.split("{port}").join(String(e)).split("{sandbox}").join(mf(n.sandboxId));return`${ff(o)}${t}`}function yf(e){return e.sandboxId.trim().length>0}function Fe(e,t,n){let r=Jr(t);if(!yf(n))return Pf(e,r);let o=aA(e,r,n);return o||(iA(n.apiBaseUrl)?`http://p${e}-${mf(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${ff(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function cA(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(o=>encodeURIComponent(o)).join("/");return Fe(3211,`/open?path=/workspace/${r}`,t)}function hf(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function lA(e){return`http://localhost:3211${hf(e)}`}function bf(){return"/health"}function uA(e){return Fe(3211,bf(),e)}function pA(e,t){return Fe(e,"/",t)}function _f(e){let t=Rn(e);return!(!t||pf.has(t.port)||df(e))}function nd(e,t){if(!e)return e;let n=Rn(e);return n?_f(n.originalUrl)?Fe(n.port,n.path,t):n.originalUrl:e}function Pf(e,t="/"){return`http://localhost:${e}${t}`}var xf=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function rd(e){let t=e.match(lf);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(uf);if(n){let o=443;try{let s=new URL(e);o=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:o,path:n[4]||"/"}}let r=e.match(xf);if(r)try{let o=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(o.port,10)||(o.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function dA(e){try{let t=rd(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function gA(e){return Yv(e)||uf.test(e)||xf.test(e)}function mA(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var kn="/web-proxy/";function fA(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),o=`${kn}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,s=parseInt(ve.KORTIX_MASTER,10);return`${Fe(s,"/",t).replace(/\/$/,"")}${o}`}catch{return null}}function yA(e){try{let t=new URL(e),n=t.pathname.indexOf(kn);if(n===-1)return null;let o=t.pathname.slice(n+kn.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!o)return null;let s=o[1],i=o[2],a=o[3]||"/";return`${s}://${i}${a}${t.search}${t.hash}`}catch{return null}}function hA(e){try{return new URL(e).pathname.includes(kn)}catch{return e.includes(kn)}}function bA(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 _A(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 Sf(e){return{health:t=>td(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>Fe(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>nd(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>pt(e.requireReady("sandboxPortUrl").sandboxId,t)}}function od(e,t,n,r){let o,s,{persistedPromptDefaults:i,clearPersistedDefaults:a}=bm(e,t),{ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g}=wm(e,t,n),m={projectId:e,sessionId:t,ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return o},set model(f){o=f},get agent(){return s},set agent(f){s=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...of(m),...sf(m),...Sf(m),...Im(m),...Dm(m),...Vm(m),files:rf(l),...Rm(m),get runtime(){return fe(d("runtime").runtimeUrl)}}}function wf(e){return{apps:{list:()=>ep(e),create:t=>tp(e,t),get:t=>np(e,t),update:(...t)=>rp(e,...t),access:{get:(...t)=>sp(e,...t),update:(...t)=>ap(e,...t),session:(...t)=>cp(e,...t),agents:t=>ip(e,t)},remove:t=>op(e,t),artifacts:{register:t=>Pr(e,t),uploadArchive:(...t)=>lp(e,...t),finalize:(...t)=>xr(e,...t)},deployments:{create:(...t)=>up(e,...t),list:t=>pp(e,t),get:(...t)=>dp(e,...t),logs:(...t)=>gp(e,...t),remove:(...t)=>yp(e,...t)},start:t=>mp(e,t),stop:t=>fp(e,t),rollback:(...t)=>hp(e,...t)}}}function vf(e){return{list:()=>Hs(e),invite:(...t)=>Ys(e,...t),update:(...t)=>Vs(e,...t),revoke:t=>zs(e,t),pendingInvites:()=>Qs(e),resendInvite:(...t)=>Js(e,...t),revokeInvite:(...t)=>Xs(e,...t),requests:()=>Gs(e),approveRequest:(...t)=>Bs(e,...t),rejectRequest:(...t)=>Ws(e,...t),groupGrants:()=>Zs(e),attachGroupGrant:(...t)=>ei(e,...t),updateGroupGrant:(...t)=>ti(e,...t),detachGroupGrant:t=>ni(e,t),resourceGrants:{list:()=>ri(e),create:t=>oi(e,t),remove:t=>si(e,t)}}}function Af(e){return{tokens:{list:()=>Ou(e),create:t=>ju(e,t),revoke:t=>Du(e,t)},setupLinks:{requestSecret:t=>Bu(e,t),requestConnector:t=>Wu(e,t)},validateManifest:t=>xs(e,t),gitToken:()=>Ss(e),agentIdentities:()=>Vl(e),secrets:{list:()=>li(e),upsert:t=>ui(e,t),setStrategy:(...t)=>pi(e,...t),broker:(...t)=>di(e,...t),remove:t=>yi(e,t),setPersonal:(...t)=>hi(e,...t),removePersonal:t=>bi(e,t),setGitCredential:t=>fi(e,t),listProviderOAuth:()=>gi(e),startProviderOAuth:(...t)=>rr(e,...t),pollProviderOAuth:(...t)=>or(e,...t),removeProviderOAuth:t=>mi(e,t)},access:vf(e)}}function kf(e){return{list:()=>Di(e),listAll:()=>$i(e),reconcile:(...t)=>Ui(e,...t),reconcileMember:(...t)=>Li(e,...t),updateCredential:(...t)=>Fi(e,...t),revoke:(...t)=>Ni(e,...t),activate:(...t)=>Ki(e,...t),setDefault:(...t)=>qi(e,...t),rename:(...t)=>Gi(e,...t),share:(...t)=>Wi(e,...t),addComputer:(...t)=>Bi(e,...t),pipedreamConnect:(...t)=>Hi(e,...t),pipedreamFinalize:(...t)=>Vi(e,...t)}}function Zr(e){return{catalog:t=>Qt(e,t),tools:()=>cr(e),search:(...t)=>Ci(e,...t),describe:(...t)=>Ei(e,...t),call:(...t)=>Mi(e,...t),accounts:(...t)=>Oi(e,...t),uploadAttachment:(...t)=>ji(e,...t)}}var PA=100,xA=0,SA=new Set(["attachment_size_mismatch","attachment_failed"]),Rf=()=>new b("Attachment expired. Attach the file again.",{code:"attachment_expired"});function If(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 sd(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,o=new Set,s=new Set,i=0,a=!1,l,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,P){y.removalDeleted||(y.removalDeleted=!0,ut(e,P).catch(()=>{}))}function m(){l&&clearTimeout(l);let y=d().map(({item:v})=>v);(y.length!==p.attachments.length||y.some((v,$)=>v!==p.attachments[$]))&&(p={attachments:y});let P=Math.min(...y.filter(v=>v.status==="ready").map(v=>Date.parse(v.attachment.expires_at)));Number.isFinite(P)&&!a&&(l=setTimeout(()=>{for(let v of d())v.item.status==="ready"&&Date.parse(v.item.attachment.expires_at)<=Date.now()&&(v.item={...v.item,status:"error",error:Rf()});m()},Math.min(2147483647,Math.max(0,P-Date.now()))),typeof l=="object"&&"unref"in l&&l.unref());for(let v of o)v();for(let v of[...s])v()}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 P=d();if(P.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some($=>!Number.isSafeInteger($)||$<=0||$>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(P.reduce(($,x)=>$+x.item.size,0)+y.reduce(($,x)=>$+x,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function w(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let P=y.item.file;i++;let v=++y.generation,$=new AbortController;y.abort=$,y.item={...y.item,status:"uploading",error:void 0};let x=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===v,_,A=0,T,C=()=>{T=void 0,!(!x()||y.item.status!=="uploading"||_===void 0)&&(y.item={...y.item,receivedBytes:_},_=void 0,A=Date.now(),m())},E=F=>Math.floor(F*100/y.item.size);en(e,P,{resume:y.upload,signal:$.signal,onUpload:F=>{y.upload=F,y.removed&&($.abort(),g(y,F.attachment_id))},onProgress:F=>{if(!x()||E(F)===E(y.item.receivedBytes)||(_=F,T))return;let ee=A+PA-Date.now();if(ee<=0)return C();T=setTimeout(C,ee),typeof T=="object"&&"unref"in T&&T.unref()},onProcessing:()=>{T&&clearTimeout(T),T=void 0,_=void 0,x()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then(F=>{x()&&(y.item={...y.item,status:"ready",attachment:If(F),receivedBytes:F.size})}).catch(F=>{F instanceof b&&SA.has(F.code??"")&&(y.upload=void 0),x()&&(y.item={...y.item,status:F instanceof b&&F.code==="ABORTED"?"aborted":"error",error:F instanceof Error?F:new Error(String(F))})}).finally(()=>{i--,T&&clearTimeout(T),y.abort===$&&(y.abort=void 0),m(),w()})}m()}function L(y){h(y.map(v=>v.size));let P=y.map(v=>{let $=`attachment-${++xA}`;return r.set($,{generation:0,item:{id:$,file:v,filename:v.name,mime:v.type||"application/octet-stream",size:v.size,status:"pending",receivedBytes:0}}),$});return m(),w(),P}function O(y){let P=r.get(y);!P||P.item.status==="ready"||(P.generation++,P.abort?.abort(),P.item={...P.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function D(y,{signal:P}={}){let v=[...y];return new Promise(($,x)=>{let _=()=>{s.delete(C),P?.removeEventListener("abort",T)},A=E=>{_(),x(E)},T=()=>A(pe()),C=()=>{let E=!1;for(let ee of v){let Q=r.get(ee);if(!Q)return A(new Error("Attachment was removed before it was sent"));if(a&&!Q.handedOff)return A(new Error("Attachment controller is disposed"));if(Q.item.status==="error"||Q.item.status==="aborted")return A(Q.item.error??new Error("Attachment upload failed"));Q.item.status!=="ready"&&(E=!0)}if(E)return;let F;try{F=v.map(ee=>{let Q=If(r.get(ee).item.attachment);return{type:"file",attachment_id:Q.attachment_id,filename:Q.filename,mime:Q.mime}})}catch(ee){return A(ee instanceof Error?ee:new Error(String(ee)))}_(),$(F)};if(P?.aborted)return T();s.add(C),P?.addEventListener("abort",T,{once:!0}),C()})}return{add:y=>L([y])[0],addMany:L,retry(y){let P=r.get(y);if(P?.handedOff||f(),!(!P||P.item.status==="ready"||P.item.status==="uploading"||P.item.status==="processing"||P.item.status==="pending")){if(!P.item.file||P.upload&&Date.parse(P.upload.expires_at)<=Date.now())throw Rf();P.item={...P.item,status:"pending",error:void 0},w()}},async remove(y){let P=r.get(y);if(!P)return;P.removed=!0,P.generation++,r.delete(y);let v=P.upload?.attachment_id??P.item.attachment?.attachment_id;v&&P.abort?.abort(),m(),w(),v&&g(P,v)},abort:O,submit(y){if(!a){for(let P of y){let v=r.get(P);v&&(v.handedOff=!0)}m()}},reclaim(y){if(!a){for(let P of y){let v=r.get(P);v&&(v.handedOff=!1)}m()}},whenReady:D,forget(y=d().map(P=>P.item.id)){for(let P of y){let v=r.get(P);v&&(v.generation++,v.abort?.abort(),r.delete(P))}m(),w()},dispose(){if(!a){a=!0,l&&clearTimeout(l);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let P=y.upload?.attachment_id??y.item.attachment?.attachment_id;P&&e&&ut(e,P).catch(()=>{})}o.clear(),m()}},getSnapshot:()=>p,subscribe(y){return o.add(y),()=>{o.delete(y)}}}}function Tf(e){return{attachments:{upload:(...t)=>en(e,...t),delete:(...t)=>ut(e,...t),createController:t=>sd(e,t)},get:t=>Gt(e,t),detail:()=>Bt(e),audit:t=>Lu(e,t),update:t=>Vt(e,t),archive:()=>zt(e),llmCatalog:()=>Wt(e),modelPicker:()=>Ht(e),modelAccess:()=>ln(e),setModelAccess:t=>un(e,t),sandboxHealth:()=>Xt(e),onboardingComplete:(...t)=>Ts(e,...t)}}function Cf(e){return{sessions:{list:t=>We(e,t),listPage:t=>za(e,t),create:t=>He(e,t),ensureWarm:()=>tc(e),claimWarm:t=>nc(e,t)},review:{list:t=>du(e,t),get:t=>gu(e,t),submit:t=>mu(e,t),act:(...t)=>fu(e,...t),bulkAct:t=>yu(e,t)},approvals:{list:t=>ii(e,t),resolve:(...t)=>ci(e,...t),sessionsNeedingInput:t=>ai(e,t)}}}function Ef(e){return{files:{list:t=>va(e,t),read:(t,n)=>ka(e,t,n),search:(...t)=>Aa(e,...t),archive:(...t)=>Ra(e,...t),history:(...t)=>ja(e,...t)},git:{commits:()=>Ea(e),commit:t=>Ma(e,t),commitDiff:t=>Oa(e,t),branches:()=>Ca(e),versionDiff:(...t)=>Da(e,...t),inviteCollaborator:(...t)=>Ps(e,...t)},changeRequests:{list:()=>$a(e),get:t=>Ua(e,t),diff:t=>La(e,t),mergePreview:t=>Fa(e,t),open:(...t)=>Na(e,...t),merge:(...t)=>Ka(e,...t),close:(...t)=>qa(e,...t),reopen:(...t)=>Ga(e,...t),requestChanges:(...t)=>Ba(e,...t)},...Cf(e)}}function Mf(e){return{policies:{list:()=>ga(e),set:(...t)=>ma(e,...t)},reminders:{list:()=>Ru(e)},triggers:{list:()=>Sc(e),create:(...t)=>wc(e,...t),update:(...t)=>vc(e,...t),remove:(...t)=>Ac(e,...t),fire:(...t)=>Rc(e,...t),setActivation:(...t)=>kc(e,...t)},...Ef(e)}}function Of(e,t){return{connectors:{...Zr(e),list:()=>zi(e),config:(...n)=>ta(e,...n),create:(...n)=>oa(e,...n),remove:(...n)=>ia(e,...n),sync:()=>Yi(e),auth:{discover:(...n)=>sa(e,...n)},setName:(...n)=>na(e,...n),setCredentialMode:(...n)=>Qi(e,...n),setAuthorizationStrategy:(...n)=>Xi(e,...n),setCredential:(...n)=>pa(e,...n),setSensitive:(...n)=>Ji(e,...n),connections:t,policies:{get:(...n)=>Zi(e,...n),set:(...n)=>ea(e,...n)},pipedream:{listApps:(...n)=>aa(e,...n),listSections:(...n)=>ca(e,...n),connect:(...n)=>ra(e,...n),finalize:(...n)=>da(e,...n)},discover:{list:(...n)=>lr(e,...n),sections:(...n)=>la(e,...n),detail:(...n)=>ur(e,...n)}},...Mf(e)}}function jf(e){return{gateway:{logs:t=>wl(e,t),log:t=>vl(e,t),overview:t=>Al(e,t),series:t=>kl(e,t),breakdown:t=>Rl(e,t),sessions:t=>Il(e,t),errors:t=>Tl(e,t),budgets:()=>Cl(e),setBudget:t=>El(e,t),deleteBudget:t=>Ml(e,t),keys:()=>Ol(e),createKey:t=>jl(e,t),revokeKey:t=>Dl(e,t),routing:{get:()=>_l(e),set:t=>Pl(e,t),reset:()=>xl(e),preview:t=>Sl(e,t)},playground:(t,n,r)=>$l(e,t,n,r)}}}function Df(e){return{modelDefaults:{get:()=>Tc(e),set:t=>Cc(e,t),clear:t=>Ec(e,t)},setDefaultAgent:t=>jc(e,t),sandbox:{list:()=>wa(e),snapshots:()=>ya(e),rebuildSnapshot:t=>ha(e,t),fixWithAgent:()=>ba(e),createTemplate:t=>_a(e,t),updateTemplate:(...t)=>Pa(e,...t),removeTemplate:t=>xa(e,t),buildTemplate:t=>Sa(e,t),setProvider:t=>Is(e,t)},setAgentScope:(...t)=>Mc(e,...t)}}function $f(e){return{channels:{slack:{installation:()=>ol(e),connect:t=>sl(e,t),mode:()=>il(e),completeInstall:t=>al(e,t),manifest:()=>ll(e),disconnect:()=>ul(e),getFile:t=>pl(e,t),uploadFile:t=>dl(e,t)},teams:{completeInstall:t=>cl(e,t)},email:{installation:t=>ml(e,t),mode:()=>fl(e),connect:t=>yl(e,t),disconnect:t=>hl(e,t),updatePolicy:(...t)=>bl(e,...t)}},updateFeatureFlag:(...t)=>ks(e,...t),updateExperimentalFeature:(...t)=>Rs(e,...t),...Df(e)}}function wA(){return Ue()}function Uf(e,t){Hn(e,t);let n=hm(e),{auth:r,accounts:o,iam:s,accountInvites:i}=dm(),{billing:a,sandboxShares:l}=am(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=im();function h(w){let L=kf(w);return{...Tf(w),...wf(w),...Af(w),...Of(w,L),...jf(w),...$f(w),session:O=>od(w,O,e,n)}}return{config:e,auth:r,accounts:o,iam:s,accountInvites:i,projects:p,connectors:Zr(),project:h,session:(w,L)=>od(w,L,e,n),github:d,gitBackend:g,billing:a,sandboxShares:l,connectStatus:m,marketplace:f,validateToken:bs,runtime:wA}}function Lf(){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 Ff(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Et(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function Nf(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function Kf(e){if(Et(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 qf(e){let t=Et(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function Gf(e,t){let n=Et(e);if(n.length===0)return e;let r=e.pending.filter(o=>n.includes(o.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(o=>!n.includes(o.id)),failed:[...e.failed,...r.map(o=>({...o,lastError:t}))],inFlightId:null,inFlightIds:[]}}function Bf(e,t){let n=e.failed.find(s=>s.id===t);if(!n)return e;let{lastError:r,...o}=n;return{...e,pending:[...e.pending,o],failed:e.failed.filter(s=>s.id!==t)}}function Wf(e,t){return Et(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 Hf(e,t,n){return Et(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 Vf(e,t,n){let r=Et(e);if(r.includes(t))return e;let o=e.pending.findIndex(p=>p.id===t);if(o===-1)return e;let s=r.length,i=Math.min(Math.max(n,s),e.pending.length-1);if(i===o)return e;let a=[...e.pending],[l]=a.splice(o,1);return a.splice(i,0,l),{...e,pending:a}}var id={thinking:!1,toolDetails:!0,assistantMetadata:!0};function vA(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function AA(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 kA(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
21
+ `)),yield m}}}finally{r.removeEventListener("abort",i),s.releaseLock()}}}async function*zS(e,t,n){let r=e.eventTransport??Ep(e.fetch??globalThis.fetch),o=n.signal??new AbortController().signal,s=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!o.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:o}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(s=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(s*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function fn(e){let t=o=>(s,i)=>VS(e,WS(e.baseUrl,o,s,i)),n=o=>s=>t(o)(void 0,s);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(o={})=>({stream:zS(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,o)}),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 Pm=200;async function YS(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 ze(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new b(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function xm(e){let t=e.runtimeUrl.replace(/\/$/,""),n=fn({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let o=encodeURIComponent(r.conversationId??e.rootId),s=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${o}${d.size?`?${d}`:""}`,m=w=>e.fetch(new Request(`${t}${w}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new b(`Reading the session transcript failed: ${await YS(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await s(r.limit===void 0?void 0:Math.min(r.limit,Pm),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await s(Math.min(r.limit-a.length,Pm),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,o,s]=await Promise.all([n.session.status().then(i=>ze(i,"Reading the session status failed")),n.permission.list().then(i=>ze(i,"Reading permission requests failed")),n.question.list().then(i=>ze(i,"Reading questions failed"))]);return{statuses:r??{},permissions:o??[],questions:s??[]}},answerPermission:async(r,o,s)=>{ze(await n.permission.reply({requestID:r,reply:o,...s!==void 0?{message:s}:{}}),"Answering the permission request failed")},answerQuestion:async(r,o)=>{if(o===null){ze(await n.question.reject({requestID:r}),"Dismissing the question failed");return}ze(await n.question.reply({requestID:r,answers:o}),"Answering the question failed")},compact:async r=>{let o=r;if(!o){let s=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof s?.model=="string"?s.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(o={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!o)throw new b("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return ze(await n.session.summarize({sessionID:e.rootId,providerID:o.providerID,modelID:o.modelID}),"Compacting the session failed"),o}}}function Sm(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return xm({runtimeUrl:r,rootId:n,fetch:j})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,o)=>(await t()).answerPermission(n,r,o),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function wm(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await hc(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var yt=BigInt(4096),ve=BigInt(0xffffffffffff),vm=ve+BigInt(1),QS=vm/BigInt(2),je=BigInt(3600*1e3)*yt,Nr=120*1e3,Am=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,XS=/^msg_([0-9a-f]{12})/,km="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Ye(e){let t=XS.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function ht(e){return BigInt(Math.trunc(e))*yt&ve}function Qe(e,t){let n=e-t&ve;return n>=QS&&(n-=vm),n}function Mp(e){let t=null;for(let n of e)n!=null&&(t===null||Qe(n,t)>BigInt(0))&&(t=n);return t}function Rm(e,t){let n=Ye(e);return n===null?!1:Qe(n,ht(t))>je}function Im(e,t){let n=t===void 0?null:ht(t);return Tm(e,r=>n===null||Qe(r,n)<=je)}function Tm(e,t){let n=[];for(let r of e){let o=Ye(r);o!==null&&t(o)&&n.push(o)}return Mp(n)}function JS(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=km[n%62])}return e}function Op(e){let t=e.random,n=ht(e.nowMs-(e.backdateMs??Nr)),r=e.newestKnownTime??null;if(r!==null){let s=Qe(r,n);s>=BigInt(0)&&s<=je&&(n=r+BigInt(1)&ve)}let o="";if(t)for(let s=0;s<14;s++)o+=km[Math.min(61,Math.floor(t()*62))];else o=JS();return{id:`msg_${n.toString(16).padStart(12,"0")}${o}`,time:n}}function Kr(e={}){let t=e.nowMs??Date.now(),n=ht(t-Nr),r=Tm(e.after??[],o=>{let s=Qe(o,n);return s>=BigInt(0)&&s<=je});return Op({nowMs:t,newestKnownTime:r}).id}function Cm(e){return{scope:()=>fc(e.projectId,e.sessionId),providerSecretPool:{list:()=>ki(e.projectId,e.sessionId),get:t=>Ai(e.projectId,e.sessionId,t),set:(t,n)=>Ri(e.projectId,e.sessionId,t,n)},rescope:t=>yc(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,o=n?.agent??e.agent,s=r&&o?{}:await e.persistedPromptDefaults(),i=r??s.model,a=o??s.agent,c=Kr(),p=await tn(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 b("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var ZS="kortix.transcript.v1",Em=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function ew(e){return typeof e=="string"&&Em.includes(e)}var tw=["once","always","reject"],nw=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];function Ae(){let e=ym();return e||(k().billingEnabled??!1?"":Kg())}async function jp(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Dp(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function $p(e){let t=Dp(e),n=await j(`${t}/env`);if(!n.ok)throw new Error(await jp(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Up(e,t,n){let r=Dp(e),o=await j(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!o.ok)throw new Error(await jp(o,"Failed to save secret"))}async function Lp(e,t){let n=Dp(e),r=await j(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await jp(r,"Failed to delete secret"))}var Mm={list:$p,set:Up,delete:Lp};async function Om(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let o=await j(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),s=await o.json();if(!o.ok)throw new Error(s?.error||s?.message||`Request failed with ${o.status}`);return s}async function qr(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function yn(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return le(e)}async function Np(e){let t=yn(e),n=await j(`${t}/kortix/pty`);if(!n.ok)throw new Error(await qr(n,"Failed to list terminals"));return n.json()}async function Kp(e,t){let n=yn(e),r=await j(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await qr(r,"Failed to create terminal"));return r.json()}async function qp(e,t,n){let r=yn(e),o=await j(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(await qr(o,"Failed to update terminal"));return o.json()}async function Gp(e,t){let n=yn(e),r=await j(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await qr(r,"Failed to remove terminal"))}async function Bp(e,t,n){let r=yn(t),s=`${(()=>{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:"),le(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await at();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${s}${s.includes("?")?"&":"?"}${c}`:s}function jm(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 De="\x1B",Dm="\x07",rw="\0",Fp=`(?:${Dm}|${De}\\\\)`,ow=[new RegExp(`${De}\\]697;[^${Dm}${De}]*${Fp}`,"g"),new RegExp(`${rw}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${De}\\][0-9]+;rgb:[0-9a-fA-F/]+${Fp}`,"g"),new RegExp(`${De}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Fp}`,"g"),new RegExp(`${De}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${De}\\[\\d+;\\d+R`,"g"),new RegExp(`${De}\\[\\?[0-9;]*c`,"g")];function $m(e){let t=e;for(let n of ow)t=t.replace(n,"");return t}var Um={list:Np,create:Kp,update:qp,remove:Gp,webSocketUrl:Bp};async function I(e,t,n,r){let o=e;for(;o.endsWith("/");)o=o.slice(0,-1);let s=await j(`${o}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await s.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!s.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${s.status}`);return a}async function sw(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 I(e,`/kortix/tasks${r}`)}async function iw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function aw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function cw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function lw(e,t){return I(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function uw(e,t,n){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function pw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function dw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function gw(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function mw(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return I(e,`/kortix/tickets${n}`)}async function fw(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function yw(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function hw(e,t){return I(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function bw(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function _w(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function Pw(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function xw(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function Sw(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function ww(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function vw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function Aw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function kw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function Rw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function Iw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function Tw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function Cw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function Ew(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function Mw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function Ow(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function jw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Dw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function $w(e,t,n=200){return I(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function Uw(e){return I(e,"/kortix/projects")}async function Lw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function Fw(e,t){return I(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function Nw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function Kw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function qw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function Gw(e,t,n="all"){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function Bw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function Ww(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function Hw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function Vw(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function zw(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function Yw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function Qw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Xw(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function Jw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function Zw(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function ev(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function tv(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var nv=1e4,rv={retryOnAuthError:!1};function bt(e,t,n){return I(e,t,{signal:AbortSignal.timeout(nv),...n},rv)}async function ov(e,t=!1){return(await bt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function sv(e){return(await bt(e,"/kortix/services/templates")).templates??[]}async function iv(e,t){return(await bt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function av(e,t,n){let r=n==="delete",o=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return bt(e,o,{method:r?"DELETE":"POST"})}async function cv(e,t){return bt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function lv(e,t){return bt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Gr=new Map,_t=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function $e(){let e=Ae();if(!e)throw new _t;return me(e)}function me(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Gr.get(e);if(t)return t;if(!Vn())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=fn({baseUrl:e,fetch:j,eventTransport:uv});return Gr.set(e,n),n}var uv=async function*(e){let t=k().eventStreamTransport;if(!t){yield*Ep(j)(e);return}let{headers:n,rejected:r}=await Sg(e.url,e.headers);try{yield*t({...e,headers:n})}catch(o){throw o?.status===401&&r(),o}};function pv(e){Gr.delete(e)}function dv(){Gr.clear()}var Br=new Map;function gv(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=Br.get(e);if(t)return t;let n=fn({baseUrl:e,fetch});return Br.set(e,n),n}function mv(e){Br.delete(e)}function fv(){Br.clear()}async function yv(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 hv(e){let t=Ae();if(!t)throw new b("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await j(`${t}${n}`,{method:"POST"}),o=r.headers.get("content-type")??"",s=/^application\/([\w.+-]+\+)?json\b/i.test(o.trim());if(!r.ok)throw new b(`System reload failed (${r.status}): ${await yv(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!s)throw new b(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new b(`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 Lm="frontend";function Wr(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Lm}] ${t}`,...n?[n]:[]);try{$e().app.log({service:Lm,level:e,message:t,extra:n})}catch{}}var Ue={debug:(e,t)=>Wr("debug",e,t),info:(e,t)=>Wr("info",e,t),warn:(e,t)=>Wr("warn",e,t),error:(e,t)=>Wr("error",e,t)};function Fm(e){return{type:"heartbeat-gap",gapMs:e}}function Nm(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 bv={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},_v=16,Pv=8,xv=6e4,Sv=5e3,wv=250,vv=1e3,Av=3e4,kv=5,Rv=3e3,Iv=3e4,Tv=2e4,Cv=2e3,Ev=8;function Mv(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function Ov(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 o=e.coalesced??[e];return o.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:o}}function Km(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 Hr=new WeakMap;function jv(e,t,n){let r=t.timers??bv,o=t.connectTimeoutMs??Tv,s=t.heartbeatTimeoutMs??xv,i=t.maxConsecutiveHardFailures??Ev,a=new AbortController;function c(y,...P){for(let v of n){let $=y(v);if($)try{$(...P)}catch(x){console.warn("[opencode-events] subscriber handler threw, skipping",x)}}}let p=null,d=y=>{p!==y&&(p=y,y&&c(P=>P.onConnectionChange,y))},g=r.now(),m=null,f=[],h,w=0,L=new Map,O=()=>{if(h&&r.clearTimeout(h),h=void 0,f.length===0)return;let y=f;f=[],L.clear(),w=r.now(),g=r.now();for(let P of y)P&&c(v=>v.onEvent,P.event)},D=()=>{if(h)return;let y=r.now()-w;h=r.setTimeout(O,Math.max(0,_v-y))};return(async()=>{let y=0,P=0;for(;!a.signal.aborted;){let v=!1,$=!1,x=!1,_,A,T=null,C=r.now(),E=new AbortController;d("connecting");let N=Km(a.signal);N.promise.then(()=>E.abort());try{let ie=await new Promise((nt,Ne)=>{let re=!1;A=r.setTimeout(()=>{re||(re=!0,Ue.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:o}),E.abort(),Ne(new Error(`SSE connect timed out after ${o}ms`)))},o),e.global.event({signal:E.signal,sseDefaultRetryDelay:Rv,sseMaxRetryDelay:Iv,sseMaxRetryAttempts:1}).then(be=>{re||(re=!0,r.clearTimeout(A),nt(be))},be=>{re||(re=!0,r.clearTimeout(A),Ne(be))})}),{stream:V}=ie;if(m){let nt=r.now()-m.lastActivityAt,Ne=m.eventful;m=null,(Ne||nt>Sv)&&c(re=>re.onGapRehydrate,nt)}g=r.now();let te=()=>{r.clearTimeout(_),_=r.setTimeout(()=>{Ue.warn("SSE heartbeat timeout, forcing reconnect"),E.abort()},s)};te();let tt=r.now(),xb=V[Symbol.asyncIterator]();for(;!E.signal.aborted;){let nt=xb.next().then(_e=>({kind:"next",result:_e}),_e=>({kind:"error",error:_e})),Ne=Km(E.signal),re=await Promise.race([nt,Ne.promise.then(()=>({kind:"aborted"}))]);if(Ne.cleanup(),re.kind==="aborted")break;if(re.kind==="error")throw re.error;if(re.result.done)break;v=!0,d("open"),te();let be=re.result.value,rt=be&&typeof be=="object"&&"payload"in be?be.payload:be;if(!rt?.type)continue;rt.type!=="server.connected"&&($=!0);let Ro=Ov(f[f.length-1]?.event,rt);if(Ro)f[f.length-1]={type:Ro.type,event:Ro};else{let _e=Mv(rt);if(_e){let cg=L.get(_e);cg!==void 0&&(f[cg]=void 0),L.set(_e,f.length)}f.push({type:rt.type,event:rt})}D(),!(r.now()-tt<Pv)&&(tt=r.now(),await new Promise(_e=>r.setTimeout(_e,0)))}x=v}catch(ie){if(a.signal.aborted)break;T=ie;let V=String(ie),te=V.includes("401")||V.includes("403")||V.includes("Unauthorized")||V.includes("Token refresh failed");if(Ue.error("SSE event stream error",{error:V,retryCount:y,isAuthError:te}),te)try{ir(),await sr(),Ue.info("SSE: refreshed auth token after auth error")}catch(tt){Ue.error("SSE: failed to refresh auth token",{error:String(tt)})}}finally{r.clearTimeout(_),r.clearTimeout(A),E.abort(),N.cleanup(),O()}if(a.signal.aborted)break;let ee=r.now()-C,Q=T?.cause?.status;if(P=!v&&(typeof Q=="number"&&Q>=400||ee<Cv)?P+1:0,P>=i){Ue.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:P,lastError:String(T)}),p=null,c(ie=>ie.onParked,{consecutiveFailures:P,lastError:T});break}d("lost"),m={lastActivityAt:g,eventful:(m?.eventful??!1)||$},x?y=0:(y++,y>1&&Ue.warn("SSE event stream reconnecting",{retryCount:y}));let Ie=x?wv:Math.min(vv*2**Math.min(y-1,kv),Av);await new Promise(ie=>{let V=r.setTimeout(ie,Ie),te=()=>{r.clearTimeout(V),ie()};a.signal.addEventListener("abort",te,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,teardown:()=>{p=null,a.abort(),h&&r.clearTimeout(h)}}}function Vr(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o,signal:s}=e,i=e.client??(e.url?me(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o},c=Hr.get(i);if(!c)c=jv(i,e,new Set([a])),Hr.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&o?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,s&&s.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),Hr.get(i)===p&&Hr.delete(i)))},m=()=>g();return s&&(s.aborted?g():s.addEventListener("abort",m,{once:!0})),{close:g}}function qm(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return me(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return me(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return me(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return Vr({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Hm(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new b(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function St(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 J(e){let t=(e??Ae()).trim();if(!t)throw new _t;return t}async function Yr(e,t){let n=await j(`${J(t)}${e}`);if(!n.ok)throw new b(await St(n),{status:n.status,response:n});return n.json()}var Qr=["/workspace","/tmp","/home","/opt"],Dv=Qr.filter(e=>e!=="/workspace");function Vp(e){return Qr.some(t=>e===t||e.startsWith(`${t}/`))}function wt(e){return Vp(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function Xe(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(Dv.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var zp=Xe;async function vt(e,t){let n=J(t),r=Xe(e)||".";return(await Yr(`/file?path=${encodeURIComponent(r)}`,n)).map(s=>({...s,path:s.absolute||`/workspace/${s.path}`}))}async function At(e,t){let n=J(t),r=Xe(e),o=await j(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!o.ok)throw new b(await St(o),{status:o.status,response:o});return o.json()}async function $v(e,t,n){let r=J(n),o=Xe(e),s=await j(`${r}/file/raw?path=${encodeURIComponent(o)}`);if(!s.ok)throw new b(await St(s),{status:s.status,response:s});if((s.headers.get("content-type")||"").includes("text/html"))throw new b("File could not be loaded (raw byte route unavailable)",{status:s.status,response:s,code:"INVALID_CONTENT_TYPE"});let i=await s.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}async function kt(e,t){let n=J(t);try{return await $v(e,void 0,n)}catch{}let r=await At(e,n);if(r.encoding==="base64"&&r.content){let o=Uint8Array.from(atob(r.content),s=>s.charCodeAt(0));return new Blob([o],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}async function bn(e){return Yr("/file/status",J(e))}async function _n(e,t,n){let r=J(n),o=new URLSearchParams({query:e});return t?.type&&o.set("type",t.type),t?.limit&&o.set("limit",String(t.limit)),Yr(`/find/file?${o.toString()}`,r)}async function Pn(e,t){let n=J(t);return(await Yr(`/find?pattern=${encodeURIComponent(e)}`,n)).map(o=>({path:typeof o.path=="string"?o.path:o.path?.text??"",lines:typeof o.lines=="string"?o.lines:o.lines?.text??"",line_number:o.line_number,absolute_offset:o.absolute_offset,submatches:(o.submatches??[]).map(s=>({start:s.start,end:s.end}))}))}var hn=[400,1200],Uv=e=>e===408||e===429||e===502||e===503||e===504,Gm=e=>new Promise(t=>setTimeout(t,e));function Lv(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Wp=3e4,Fv=15*6e4,Nv=256;function Pt(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Wp;let t=Wp+e/Nv;return Math.min(Fv,Math.max(Wp,Math.round(t)))}async function Kv(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 zr(e,t){let n;for(let o=0;o<=hn.length;o++){let s;try{s=await t(e())}catch(a){if(n=a,Lv(a)||o===hn.length)break;await Gm(hn[o]);continue}if(s.ok)return s.json();let i=await Kv(s);if(n=new b(`Upload failed (${s.status}): ${i}`,{status:s.status,response:s}),!Uv(s.status)||o===hn.length)throw n;await Gm(hn[o])}if(n instanceof b)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new b(`Upload failed: ${r}`)}var Hp=8*1024*1024;function qv(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new b(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Bm(e,t){try{e?.onProgress?.(t)}catch{}}function Wm(e,t,n){let r=new FormData,o=(t??"").trim();return o&&r.append("path",o.startsWith("/")?o:`/${o}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function Gv(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function Rt(e,t,n,r,o){let s=typeof r=="string"?r:void 0,i=typeof r=="string"?o:r,a=J(s),c=Pt(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Hp){let f=await zr(()=>Wm(e,t,p),h=>j(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return qv(f[0],e.size),Bm(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await zr(()=>Wm(new Blob([],{type:e.type}),t,p),f=>j(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:Pt(0)})))[0]?.path;if(!g)throw new b("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=Gv(g);if(!m.name)throw new b(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=Hp){let h=Math.min(e.size,f+Hp),w=e.slice(f,h,e.type),L=await zr(()=>{let O=new FormData;return m.parent&&O.append("path",m.parent),O.append("filename",m.name),O.append("first",f===0?"true":"false"),O.append("offset",String(f)),O.append("file",w,m.name),O},O=>j(`${a}/file/append`,{method:"POST",body:O},{timeoutMs:Pt(w.size)}));if(L.path!==g||L.size!==h)throw new b(`Upload verification failed for ${g}: expected ${h} bytes, received ${L.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Bm(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await Je(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function Bv(e,t,n){let r=J(n),o=Pt(t.size);return zr(()=>{let s=new FormData;return s.append(e,t,e.split("/").pop()||"file"),s},s=>j(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:o}))}var xt=class extends b{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function xn(e,t){let n=J(t),r=e.trim(),s=(r.startsWith("/")?r:`/${r}`).split("/"),i=s.pop()||"untitled",a=s.join("/")||"/workspace",c=wt(`${a}/${i}`),p=[];try{p=await vt(Vm(c),n)}catch(g){if(!(g instanceof b&&g.status===404))throw g}if(p.some(g=>g.name===zm(c)))throw new xt(c);let d=await Ym(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function Sn(e,t,n){let r=J(n);return Bv(t,await kt(e,r),r)}function Wv(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Vm(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function zm(e){return e.slice(e.lastIndexOf("/")+1)}function Hv(){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 wn(e,t,n){let r=J(n),o=wt(Wv(e.trim()));return Ym(o,t,r,{overwrite:!0})}async function Ym(e,t,n,r){let o=zm(e);if(!o)throw new b(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let s=Vm(e);await It(s,n).catch(()=>{});let i=Hv(),a=await Rt(t,s,`.${o}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new b(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=wt(c);try{await Qm(p,e,n,r.overwrite)}catch(g){throw await Je(p,n).catch(()=>{}),!r.overwrite&&g instanceof b&&g.status===409?new xt(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Je(e,t){let n=await j(`${J(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Delete failed (${n.status}): ${await St(n)}`,{status:n.status,response:n});return n.json()}async function It(e,t){let n=await j(`${J(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Mkdir failed (${n.status}): ${await St(n)}`,{status:n.status,response:n});return n.json()}async function vn(e,t,n){return Qm(e,t,J(n),!0)}async function Qm(e,t,n,r){let o=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(!o.ok)throw new b(`Rename failed (${o.status}): ${await St(o)}`,{status:o.status,response:o});return o.json()}async function Yp(){return Hm(await $e().project.current())}async function Xr(){return Hm(await $e().global.health())}async function Qp(){try{return(await Xr()).healthy===!0}catch{return!1}}var Xm={list:vt,read:At,readBlob:kt,status:bn,findFiles:_n,findText:Pn,upload:Rt,write:wn,create:xn,copy:Sn,remove:Je,mkdir:It,rename:vn,currentProject:Yp,health:Xr,isReachable:Qp,toDaemonPath:Xe,toSandboxAbsolutePath:wt,toWorkspaceRelative:zp};function Jm(e){return{list:async t=>vt(t,(await e()).runtimeUrl),read:async t=>At(t,(await e()).runtimeUrl),readBlob:async t=>kt(t,(await e()).runtimeUrl),status:async()=>bn((await e()).runtimeUrl),findFiles:async(t,n)=>_n(t,n,(await e()).runtimeUrl),findText:async t=>Pn(t,(await e()).runtimeUrl),upload:async(t,n,r,o)=>Rt(t,n,r,(await e()).runtimeUrl,o),write:async(t,n)=>wn(t,n,(await e()).runtimeUrl),create:async t=>xn(t,(await e()).runtimeUrl),copy:async(t,n)=>Sn(t,n,(await e()).runtimeUrl),remove:async t=>Je(t,(await e()).runtimeUrl),mkdir:async t=>It(t,(await e()).runtimeUrl),rename:async(t,n)=>vn(t,n,(await e()).runtimeUrl)}}function Zm(e){return{get:t=>en(e.projectId,e.sessionId,t),presence:t=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1}),cost:()=>sn(e.sessionId,{projectId:e.projectId}),update:t=>uc(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),pc(e.projectId,e.sessionId)),start:(...t)=>Ee(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),nn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),rn(e.projectId,e.sessionId)),configState:()=>dc(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),gc(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),mc(e.projectId,e.sessionId,...t)),setSharing:t=>Va(e.projectId,e.sessionId,t),previews:()=>Ya(e.projectId,e.sessionId),participants:()=>za(e.projectId,e.sessionId),commit:t=>Ga(e.projectId,e.sessionId,t),publicShares:{list:()=>Qa(e.projectId,e.sessionId),create:(...t)=>Xa(e.projectId,e.sessionId,...t),revoke:(...t)=>Ja(e.projectId,e.sessionId,...t)}}}function ef(e){return{reminders:{list:()=>xu(e.projectId,e.sessionId),create:t=>Su(e.projectId,e.sessionId,t),update:(t,n)=>wu(e.projectId,e.sessionId,t,n),remove:t=>vu(e.projectId,e.sessionId,t)},audit:(t,n)=>tc(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>wp(e.projectId,e.sessionId,t,n),read:(t,n)=>vp(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>nc(e.projectId,e.sessionId,t),messageAuthors:()=>_c(e.projectId,e.sessionId),transcriptSync:t=>rc(e.projectId,e.sessionId,t),turn:()=>oc(e.projectId,e.sessionId),prompts:{create:t=>tn(e.projectId,e.sessionId,t),list:()=>sc(e.projectId,e.sessionId),remove:t=>ic(e.projectId,e.sessionId,t),retry:t=>cc(e.projectId,e.sessionId,t),edit:(t,n)=>ac(e.projectId,e.sessionId,t,n),hold:t=>lc(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function tf(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var zv=["control_plane","provider_ingress","daemon","upstream_port"];function Xp(e){return typeof e=="string"&&zv.includes(e)?e:null}function Jp(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 Zp(e,t){let n=(e===void 0?Ae():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await j(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),o=await r.text().catch(()=>""),s=null;try{s=o?JSON.parse(o):null}catch{s=null}let i=s,a=Xp(r.headers.get("X-Kortix-Proxy-Hop"))??Xp(s?.hop),c=Number(r.headers.get("X-Kortix-Upstream-Status")),p=s?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:o,hop:a,upstreamStatus:d}}var nf=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,rf=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,of=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,sf=new Set([22,4096,parseInt(we.KORTIX_MASTER,10)]);function Yv(e){return rf.test(e)}function Jr(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 Qv(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var Xv=new Set(["'",'"',"`","<","(","["]),Jv=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function Zv(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&&Xv.has(e[t]);)t++;for(;n>t&&Jv.has(e[n-1]);)n--;return e.slice(t,n)}function eA(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var tA=/^\/proxy\/(\d{1,5})(\/.*)?$/,nA=/^\/(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 af(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:nA.test(t.pathname)}catch{return!1}}function kn(e){if(!e)return null;let t=Zv(Qv(e.trim())),n=td(t);if(n){let r=Jr(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 o=parseInt(r.port,10);if(!Number.isInteger(o)||o<1||o>65535)return null;let s=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(we.KORTIX_MASTER,10);if(o===i){let c=r.pathname.match(tA);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return o=p,s=Jr(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${o}${s}`,port:o,path:s}}}let a=Jr(s);return{originalUrl:`${r.protocol}//${r.hostname}:${o}${a}`,port:o,path:a}}catch{let r=eA(e);return r&&r!==e?kn(r):null}}function rA(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let o=/`[^`\n]+`/g;for(;(r=o.exec(e))!==null;){let s=r.index,i=s+r[0].length;t.some(([c,p])=>s>=c&&i<=p)||t.push([s,i])}return t}function oA(e,t){return t.some(([n,r])=>e>=n&&e<r)}function cf(e){let t=[],n=new Set,r=rA(e);nf.lastIndex=0;let o;for(;(o=nf.exec(e))!==null;){let s=kn(o[0]);if(!s)continue;let{originalUrl:i,port:a,path:c}=s;a<1||a>65535||sf.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:o.index,endIndex:o.index+i.length,inCodeBlock:oA(o.index,r)}))}return t}function sA(e){return cf(e).length>0}function iA(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function lf(e){return e.trim().toLowerCase().split("_").join("-")}function uf(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function aA(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let o=r.split("{port}").join(String(e)).split("{sandbox}").join(lf(n.sandboxId));return`${uf(o)}${t}`}function pf(e){return e.sandboxId.trim().length>0}function Le(e,t,n){let r=Jr(t);if(!pf(n))return ff(e,r);let o=aA(e,r,n);return o||(iA(n.apiBaseUrl)?`http://p${e}-${lf(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${uf(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function cA(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(o=>encodeURIComponent(o)).join("/");return Le(3211,`/open?path=/workspace/${r}`,t)}function df(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function lA(e){return`http://localhost:3211${df(e)}`}function gf(){return"/health"}function uA(e){return Le(3211,gf(),e)}function pA(e,t){return Le(e,"/",t)}function mf(e){let t=kn(e);return!(!t||sf.has(t.port)||af(e))}function ed(e,t){if(!e)return e;let n=kn(e);return n?mf(n.originalUrl)?Le(n.port,n.path,t):n.originalUrl:e}function ff(e,t="/"){return`http://localhost:${e}${t}`}var yf=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function td(e){let t=e.match(rf);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(of);if(n){let o=443;try{let s=new URL(e);o=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:o,path:n[4]||"/"}}let r=e.match(yf);if(r)try{let o=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(o.port,10)||(o.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function dA(e){try{let t=td(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function gA(e){return Yv(e)||of.test(e)||yf.test(e)}function mA(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var An="/web-proxy/";function fA(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),o=`${An}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,s=parseInt(we.KORTIX_MASTER,10);return`${Le(s,"/",t).replace(/\/$/,"")}${o}`}catch{return null}}function yA(e){try{let t=new URL(e),n=t.pathname.indexOf(An);if(n===-1)return null;let o=t.pathname.slice(n+An.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!o)return null;let s=o[1],i=o[2],a=o[3]||"/";return`${s}://${i}${a}${t.search}${t.hash}`}catch{return null}}function hA(e){try{return new URL(e).pathname.includes(An)}catch{return e.includes(An)}}function bA(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 _A(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 hf(e){return{health:t=>Zp(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>Le(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>ed(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>lt(e.requireReady("sandboxPortUrl").sandboxId,t)}}function nd(e,t,n,r){let o,s,{persistedPromptDefaults:i,clearPersistedDefaults:a}=gm(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=bm(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return o},set model(f){o=f},get agent(){return s},set agent(f){s=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...Zm(m),...ef(m),...hf(m),...wm(m),...Cm(m),...qm(m),files:Jm(c),...Sm(m),get runtime(){return me(d("runtime").runtimeUrl)}}}function bf(e){return{apps:{list:()=>Ju(e),create:t=>Zu(e,t),get:t=>ep(e,t),update:(...t)=>tp(e,...t),access:{get:(...t)=>rp(e,...t),update:(...t)=>sp(e,...t),session:(...t)=>ip(e,...t),agents:t=>op(e,t)},remove:t=>np(e,t),artifacts:{register:t=>Pr(e,t),uploadArchive:(...t)=>ap(e,...t),finalize:(...t)=>xr(e,...t)},deployments:{create:(...t)=>cp(e,...t),list:t=>lp(e,t),get:(...t)=>up(e,...t),logs:(...t)=>pp(e,...t),remove:(...t)=>mp(e,...t)},start:t=>dp(e,t),stop:t=>gp(e,t),rollback:(...t)=>fp(e,...t)}}}function _f(e){return{list:()=>Bs(e),invite:(...t)=>Vs(e,...t),update:(...t)=>Ws(e,...t),revoke:t=>Hs(e,t),pendingInvites:()=>zs(e),resendInvite:(...t)=>Qs(e,...t),revokeInvite:(...t)=>Ys(e,...t),requests:()=>Ks(e),approveRequest:(...t)=>qs(e,...t),rejectRequest:(...t)=>Gs(e,...t),groupGrants:()=>Xs(e),attachGroupGrant:(...t)=>Js(e,...t),updateGroupGrant:(...t)=>Zs(e,...t),detachGroupGrant:t=>ei(e,t),resourceGrants:{list:()=>ti(e),create:t=>ni(e,t),remove:t=>ri(e,t)}}}function Pf(e){return{tokens:{list:()=>Eu(e),create:t=>Mu(e,t),revoke:t=>Ou(e,t)},setupLinks:{requestSecret:t=>qu(e,t),requestConnector:t=>Gu(e,t)},validateManifest:t=>_s(e,t),gitToken:()=>Ps(e),agentIdentities:()=>Wl(e),secrets:{list:()=>ai(e),upsert:t=>ci(e,t),setStrategy:(...t)=>li(e,...t),broker:(...t)=>ui(e,...t),remove:t=>mi(e,t),setPersonal:(...t)=>fi(e,...t),removePersonal:t=>yi(e,t),setGitCredential:t=>gi(e,t),listProviderOAuth:()=>pi(e),startProviderOAuth:(...t)=>rr(e,...t),pollProviderOAuth:(...t)=>or(e,...t),removeProviderOAuth:t=>di(e,t)},access:_f(e)}}function xf(e){return{list:()=>Oi(e),listAll:()=>ji(e),reconcile:(...t)=>Di(e,...t),reconcileMember:(...t)=>$i(e,...t),updateCredential:(...t)=>Ui(e,...t),revoke:(...t)=>Li(e,...t),activate:(...t)=>Fi(e,...t),setDefault:(...t)=>Ni(e,...t),rename:(...t)=>Ki(e,...t),share:(...t)=>Gi(e,...t),addComputer:(...t)=>qi(e,...t),pipedreamConnect:(...t)=>Bi(e,...t),pipedreamFinalize:(...t)=>Wi(e,...t)}}function Zr(e){return{catalog:t=>zt(e,t),tools:()=>cr(e),search:(...t)=>Ii(e,...t),describe:(...t)=>Ti(e,...t),call:(...t)=>Ci(e,...t),accounts:(...t)=>Ei(e,...t),uploadAttachment:(...t)=>Mi(e,...t)}}var PA=100,xA=0,SA=new Set(["attachment_size_mismatch","attachment_failed"]),Sf=()=>new b("Attachment expired. Attach the file again.",{code:"attachment_expired"});function wf(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 rd(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,o=new Set,s=new Set,i=0,a=!1,c,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,P){y.removalDeleted||(y.removalDeleted=!0,ct(e,P).catch(()=>{}))}function m(){c&&clearTimeout(c);let y=d().map(({item:v})=>v);(y.length!==p.attachments.length||y.some((v,$)=>v!==p.attachments[$]))&&(p={attachments:y});let P=Math.min(...y.filter(v=>v.status==="ready").map(v=>Date.parse(v.attachment.expires_at)));Number.isFinite(P)&&!a&&(c=setTimeout(()=>{for(let v of d())v.item.status==="ready"&&Date.parse(v.item.attachment.expires_at)<=Date.now()&&(v.item={...v.item,status:"error",error:Sf()});m()},Math.min(2147483647,Math.max(0,P-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let v of o)v();for(let v of[...s])v()}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 P=d();if(P.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some($=>!Number.isSafeInteger($)||$<=0||$>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(P.reduce(($,x)=>$+x.item.size,0)+y.reduce(($,x)=>$+x,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function w(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let P=y.item.file;i++;let v=++y.generation,$=new AbortController;y.abort=$,y.item={...y.item,status:"uploading",error:void 0};let x=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===v,_,A=0,T,C=()=>{T=void 0,!(!x()||y.item.status!=="uploading"||_===void 0)&&(y.item={...y.item,receivedBytes:_},_=void 0,A=Date.now(),m())},E=N=>Math.floor(N*100/y.item.size);Jt(e,P,{resume:y.upload,signal:$.signal,onUpload:N=>{y.upload=N,y.removed&&($.abort(),g(y,N.attachment_id))},onProgress:N=>{if(!x()||E(N)===E(y.item.receivedBytes)||(_=N,T))return;let ee=A+PA-Date.now();if(ee<=0)return C();T=setTimeout(C,ee),typeof T=="object"&&"unref"in T&&T.unref()},onProcessing:()=>{T&&clearTimeout(T),T=void 0,_=void 0,x()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then(N=>{x()&&(y.item={...y.item,status:"ready",attachment:wf(N),receivedBytes:N.size})}).catch(N=>{N instanceof b&&SA.has(N.code??"")&&(y.upload=void 0),x()&&(y.item={...y.item,status:N instanceof b&&N.code==="ABORTED"?"aborted":"error",error:N instanceof Error?N:new Error(String(N))})}).finally(()=>{i--,T&&clearTimeout(T),y.abort===$&&(y.abort=void 0),m(),w()})}m()}function L(y){h(y.map(v=>v.size));let P=y.map(v=>{let $=`attachment-${++xA}`;return r.set($,{generation:0,item:{id:$,file:v,filename:v.name,mime:v.type||"application/octet-stream",size:v.size,status:"pending",receivedBytes:0}}),$});return m(),w(),P}function O(y){let P=r.get(y);!P||P.item.status==="ready"||(P.generation++,P.abort?.abort(),P.item={...P.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function D(y,{signal:P}={}){let v=[...y];return new Promise(($,x)=>{let _=()=>{s.delete(C),P?.removeEventListener("abort",T)},A=E=>{_(),x(E)},T=()=>A(pe()),C=()=>{let E=!1;for(let ee of v){let Q=r.get(ee);if(!Q)return A(new Error("Attachment was removed before it was sent"));if(a&&!Q.handedOff)return A(new Error("Attachment controller is disposed"));if(Q.item.status==="error"||Q.item.status==="aborted")return A(Q.item.error??new Error("Attachment upload failed"));Q.item.status!=="ready"&&(E=!0)}if(E)return;let N;try{N=v.map(ee=>{let Q=wf(r.get(ee).item.attachment);return{type:"file",attachment_id:Q.attachment_id,filename:Q.filename,mime:Q.mime}})}catch(ee){return A(ee instanceof Error?ee:new Error(String(ee)))}_(),$(N)};if(P?.aborted)return T();s.add(C),P?.addEventListener("abort",T,{once:!0}),C()})}return{add:y=>L([y])[0],addMany:L,retry(y){let P=r.get(y);if(P?.handedOff||f(),!(!P||P.item.status==="ready"||P.item.status==="uploading"||P.item.status==="processing"||P.item.status==="pending")){if(!P.item.file||P.upload&&Date.parse(P.upload.expires_at)<=Date.now())throw Sf();P.item={...P.item,status:"pending",error:void 0},w()}},async remove(y){let P=r.get(y);if(!P)return;P.removed=!0,P.generation++,r.delete(y);let v=P.upload?.attachment_id??P.item.attachment?.attachment_id;v&&P.abort?.abort(),m(),w(),v&&g(P,v)},abort:O,submit(y){if(!a){for(let P of y){let v=r.get(P);v&&(v.handedOff=!0)}m()}},reclaim(y){if(!a){for(let P of y){let v=r.get(P);v&&(v.handedOff=!1)}m()}},whenReady:D,forget(y=d().map(P=>P.item.id)){for(let P of y){let v=r.get(P);v&&(v.generation++,v.abort?.abort(),r.delete(P))}m(),w()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let P=y.upload?.attachment_id??y.item.attachment?.attachment_id;P&&e&&ct(e,P).catch(()=>{})}o.clear(),m()}},getSnapshot:()=>p,subscribe(y){return o.add(y),()=>{o.delete(y)}}}}function vf(e){return{attachments:{upload:(...t)=>Jt(e,...t),delete:(...t)=>ct(e,...t),createController:t=>rd(e,t)},get:t=>Kt(e,t),detail:()=>qt(e),audit:t=>$u(e,t),update:t=>Wt(e,t),archive:()=>Ht(e),llmCatalog:()=>Gt(e),modelPicker:()=>Bt(e),modelAccess:()=>an(e),setModelAccess:t=>cn(e,t),sandboxHealth:()=>Yt(e),onboardingComplete:(...t)=>Rs(e,...t)}}function Af(e){return{sessions:{list:t=>Be(e,t),listPage:t=>Ha(e,t),create:t=>We(e,t),ensureWarm:()=>Za(e),claimWarm:t=>ec(e,t)},review:{list:t=>uu(e,t),get:t=>pu(e,t),submit:t=>du(e,t),act:(...t)=>gu(e,...t),bulkAct:t=>mu(e,t)},approvals:{list:t=>oi(e,t),resolve:(...t)=>ii(e,...t),sessionsNeedingInput:t=>si(e,t)}}}function kf(e){return{files:{list:t=>Sa(e,t),read:(t,n)=>va(e,t,n),search:(...t)=>wa(e,...t),archive:(...t)=>Aa(e,...t),history:(...t)=>Ma(e,...t)},git:{commits:()=>Ta(e),commit:t=>Ca(e,t),commitDiff:t=>Ea(e,t),branches:()=>Ia(e),versionDiff:(...t)=>Oa(e,...t),inviteCollaborator:(...t)=>bs(e,...t)},changeRequests:{list:()=>ja(e),get:t=>Da(e,t),diff:t=>$a(e,t),mergePreview:t=>Ua(e,t),open:(...t)=>La(e,...t),merge:(...t)=>Fa(e,...t),close:(...t)=>Na(e,...t),reopen:(...t)=>Ka(e,...t),requestChanges:(...t)=>qa(e,...t)},...Af(e)}}function Rf(e){return{policies:{list:()=>pa(e),set:(...t)=>da(e,...t)},reminders:{list:()=>Au(e)},triggers:{list:()=>Pc(e),create:(...t)=>xc(e,...t),update:(...t)=>Sc(e,...t),remove:(...t)=>wc(e,...t),fire:(...t)=>Ac(e,...t),setActivation:(...t)=>vc(e,...t)},...kf(e)}}function If(e,t){return{connectors:{...Zr(e),list:()=>Hi(e),config:(...n)=>Zi(e,...n),create:(...n)=>na(e,...n),remove:(...n)=>oa(e,...n),sync:()=>Vi(e),auth:{discover:(...n)=>ra(e,...n)},setName:(...n)=>ea(e,...n),setCredentialMode:(...n)=>zi(e,...n),setAuthorizationStrategy:(...n)=>Yi(e,...n),setCredential:(...n)=>la(e,...n),setSensitive:(...n)=>Qi(e,...n),connections:t,policies:{get:(...n)=>Xi(e,...n),set:(...n)=>Ji(e,...n)},pipedream:{listApps:(...n)=>sa(e,...n),listSections:(...n)=>ia(e,...n),connect:(...n)=>ta(e,...n),finalize:(...n)=>ua(e,...n)},discover:{list:(...n)=>lr(e,...n),sections:(...n)=>aa(e,...n),detail:(...n)=>ur(e,...n)}},...Rf(e)}}function Tf(e){return{gateway:{logs:t=>xl(e,t),log:t=>Sl(e,t),overview:t=>wl(e,t),series:t=>vl(e,t),breakdown:t=>Al(e,t),sessions:t=>kl(e,t),errors:t=>Rl(e,t),budgets:()=>Il(e),setBudget:t=>Tl(e,t),deleteBudget:t=>Cl(e,t),keys:()=>El(e),createKey:t=>Ml(e,t),revokeKey:t=>Ol(e,t),routing:{get:()=>hl(e),set:t=>bl(e,t),reset:()=>_l(e),preview:t=>Pl(e,t)},playground:(t,n,r)=>jl(e,t,n,r)}}}function Cf(e){return{modelDefaults:{get:()=>Rc(e),set:t=>Ic(e,t),clear:t=>Tc(e,t)},setDefaultAgent:t=>Mc(e,t),sandbox:{list:()=>xa(e),snapshots:()=>ma(e),rebuildSnapshot:t=>fa(e,t),fixWithAgent:()=>ya(e),createTemplate:t=>ha(e,t),updateTemplate:(...t)=>ba(e,...t),removeTemplate:t=>_a(e,t),buildTemplate:t=>Pa(e,t),setProvider:t=>ks(e,t)},setAgentScope:(...t)=>Cc(e,...t)}}function Ef(e){return{channels:{slack:{installation:()=>nl(e),connect:t=>rl(e,t),mode:()=>ol(e),completeInstall:t=>sl(e,t),manifest:()=>al(e),disconnect:()=>cl(e),getFile:t=>ll(e,t),uploadFile:t=>ul(e,t)},teams:{completeInstall:t=>il(e,t)},email:{installation:t=>dl(e,t),mode:()=>gl(e),connect:t=>ml(e,t),disconnect:t=>fl(e,t),updatePolicy:(...t)=>yl(e,...t)}},updateFeatureFlag:(...t)=>vs(e,...t),updateExperimentalFeature:(...t)=>As(e,...t),...Cf(e)}}function wA(){return $e()}function Mf(e,t){Hn(e,t);let n=dm(e),{auth:r,accounts:o,iam:s,accountInvites:i}=am(),{billing:a,sandboxShares:c}=om(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=rm();function h(w){let L=xf(w);return{...vf(w),...bf(w),...Pf(w),...If(w,L),...Tf(w),...Ef(w),session:O=>nd(w,O,e,n)}}return{config:e,auth:r,accounts:o,iam:s,accountInvites:i,projects:p,connectors:Zr(),project:h,session:(w,L)=>nd(w,L,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,validateToken:ys,runtime:wA}}function Of(){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 jf(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Tt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function Df(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function $f(e){if(Tt(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 Uf(e){let t=Tt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function Lf(e,t){let n=Tt(e);if(n.length===0)return e;let r=e.pending.filter(o=>n.includes(o.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(o=>!n.includes(o.id)),failed:[...e.failed,...r.map(o=>({...o,lastError:t}))],inFlightId:null,inFlightIds:[]}}function Ff(e,t){let n=e.failed.find(s=>s.id===t);if(!n)return e;let{lastError:r,...o}=n;return{...e,pending:[...e.pending,o],failed:e.failed.filter(s=>s.id!==t)}}function Nf(e,t){return Tt(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 Kf(e,t,n){return Tt(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 qf(e,t,n){let r=Tt(e);if(r.includes(t))return e;let o=e.pending.findIndex(p=>p.id===t);if(o===-1)return e;let s=r.length,i=Math.min(Math.max(n,s),e.pending.length-1);if(i===o)return e;let a=[...e.pending],[c]=a.splice(o,1);return a.splice(i,0,c),{...e,pending:a}}var od={thinking:!1,toolDetails:!0,assistantMetadata:!0};function vA(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function AA(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 kA(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
  >
@@ -59,7 +59,7 @@ ${e.state.error}
59
59
 
60
60
  `}function IA(e,t,n){let r="";e.role==="user"?r+=`## User
61
61
 
62
- `:r+=RA(e,n.assistantMetadata);for(let o of t)r+=kA(o,n);return r}function zf(e,t,n=id){let r=`# ${e.title||"Untitled Session"}
62
+ `:r+=RA(e,n.assistantMetadata);for(let o of t)r+=kA(o,n);return r}function Gf(e,t,n=od){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()}
@@ -69,30 +69,30 @@ ${e.state.error}
69
69
 
70
70
  `;for(let o of t)r+=IA(o.info,o.parts,n),r+=`---
71
71
 
72
- `;return r}function Yf(e,t){return`session-${e}.md`}var ad="An error occurred";var TA=["message","error","detail","error_description","msg","errors","data"];function cd(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 Mt(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function CA(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=Mt(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function EA(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=MA(e,t);if(n)return n;let r=jA(e,t);return r?r.slice(0,200):void 0}function Zf(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function Qf(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function MA(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let o=r+6;if(!Zf(t.charCodeAt(o))){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return;let i=e.indexOf("<",s+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(s+1,i).trim();if(a)return a}n=s+1}}var OA=["script","style"];function jA(e,t){let n=[],r=0;for(;r<e.length;){let o=e.indexOf("<",r);if(o===-1){n.push(e.slice(r));break}n.push(e.slice(r,o));let s=OA.find(i=>t.startsWith(`<${i}`,o)&&Zf(t.charCodeAt(o+i.length+1)));if(s){let i=t.indexOf(`</${s}`,o);r=i===-1?e.length:Qf(e,i);continue}r=Qf(e,o)}return n.join(" ").replace(/\s+/g," ").trim()}function DA(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 $A(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function Xf(e,t,n){if(typeof e=="string")return eo(e,t,n);if(e&&typeof e=="object")return to(e,t,n)}function eo(e,t,n=new WeakSet){let r=cd(e);if(!r)return;if(t>=4)return r;let o=DA(r);if(o)return o;let s=Mt(r);if(s!==void 0)return typeof s=="string"?eo(s,t+1,n):s&&typeof s=="object"?to(s,t+1,n):String(s);let i=ey(r);if(i){let a=Mt(i);if(a&&typeof a=="object"){let l=to(a,t+1,n);if(l)return l}}if(r.includes("{")){let a=CA(r);if(a)return eo(a,t+1,n)??a}return EA(r)??r}function to(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=Xf(i,t,n);if(a)return a}return}let r=e;for(let i of TA){let a=Xf(r[i],t,n);if(a)return a}let o=r.type??r.code;if(typeof o=="string"&&o.trim())return $A(o);let s=r.status??r.statusCode??r.upstream_status;if(typeof s=="number"&&Number.isFinite(s))return`Request failed with status ${s}`}function le(e){return e?typeof e=="string"?eo(e,0)??ad:typeof e=="object"?to(e,0)??ad:String(e):ad}function ld(e){let t=UA(e)?.trim();if(!t)return;let n=le(e);if(!(t===n||cd(t)===n))return t}function UA(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:o}=n,s=[r,o].filter((i,a,l)=>typeof i=="string"&&i.trim()!==""&&l.indexOf(i)===a);if(s.length>0)return s.join(`
72
+ `;return r}function Bf(e,t){return`session-${e}.md`}var sd="An error occurred";var TA=["message","error","detail","error_description","msg","errors","data"];function id(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 Ct(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function CA(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=Ct(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function EA(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=MA(e,t);if(n)return n;let r=jA(e,t);return r?r.slice(0,200):void 0}function zf(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function Wf(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function MA(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let o=r+6;if(!zf(t.charCodeAt(o))){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return;let i=e.indexOf("<",s+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(s+1,i).trim();if(a)return a}n=s+1}}var OA=["script","style"];function jA(e,t){let n=[],r=0;for(;r<e.length;){let o=e.indexOf("<",r);if(o===-1){n.push(e.slice(r));break}n.push(e.slice(r,o));let s=OA.find(i=>t.startsWith(`<${i}`,o)&&zf(t.charCodeAt(o+i.length+1)));if(s){let i=t.indexOf(`</${s}`,o);r=i===-1?e.length:Wf(e,i);continue}r=Wf(e,o)}return n.join(" ").replace(/\s+/g," ").trim()}function DA(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 $A(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function Hf(e,t,n){if(typeof e=="string")return eo(e,t,n);if(e&&typeof e=="object")return to(e,t,n)}function eo(e,t,n=new WeakSet){let r=id(e);if(!r)return;if(t>=4)return r;let o=DA(r);if(o)return o;let s=Ct(r);if(s!==void 0)return typeof s=="string"?eo(s,t+1,n):s&&typeof s=="object"?to(s,t+1,n):String(s);let i=Yf(r);if(i){let a=Ct(i);if(a&&typeof a=="object"){let c=to(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=CA(r);if(a)return eo(a,t+1,n)??a}return EA(r)??r}function to(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=Hf(i,t,n);if(a)return a}return}let r=e;for(let i of TA){let a=Hf(r[i],t,n);if(a)return a}let o=r.type??r.code;if(typeof o=="string"&&o.trim())return $A(o);let s=r.status??r.statusCode??r.upstream_status;if(typeof s=="number"&&Number.isFinite(s))return`Request failed with status ${s}`}function ce(e){return e?typeof e=="string"?eo(e,0)??sd:typeof e=="object"?to(e,0)??sd:String(e):sd}function ad(e){let t=UA(e)?.trim();if(!t)return;let n=ce(e);if(!(t===n||id(t)===n))return t}function UA(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:o}=n,s=[r,o].filter((i,a,c)=>typeof i=="string"&&i.trim()!==""&&c.indexOf(i)===a);if(s.length>0)return s.join(`
73
73
 
74
- `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function ey(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function LA(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 FA(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 Jf(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,o=typeof e.upstream_status=="number"?e.upstream_status:void 0,s=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=FA(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,l=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&o===void 0&&!s&&!i?void 0:{message:typeof e.message=="string"&&e.message||LA(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:o,requestId:s,attemptFailures:i,...a?{requestedModel:a}:{},...l?{resolvedModel:l}:{}}}function ue(e){if(e==null)return;if(typeof e=="string"){let i=cd(e),a=Mt(i)??Mt(ey(i));return a!==void 0?ue(a):void 0}if(typeof e!="object")return;let t=e,n=Jf(t);if(n)return n;let r=t.error;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=Jf(r);if(i)return i}let o=t.data;if(o&&typeof o.responseBody=="string"){let i=Mt(o.responseBody);if(i!==void 0){let a=ue(i);if(a)return a}}if(o&&typeof o.message=="string"){let i=ue(o.message);if(i)return i}let s=t.cause;if(s&&typeof s=="object"){let i=s.body;if(i!==void 0){let a=ue(i);if(a)return a}}}var ty={};function B(e,t){for(let n of t)ty[n]=e}B("read",["read"]);B("list",["list","ls"]);B("glob",["glob"]);B("grep",["grep"]);B("write",["write"]);B("edit",["edit","multiedit","morph_edit"]);B("apply_patch",["apply_patch","patch"]);B("bash",["bash"]);B("web_search",["web_search","websearch","image_search"]);B("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);B("media",["image_gen","video_gen"]);B("show",["show","show_user","presentation_gen"]);B("task",["task"]);B("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"]);B("todowrite",["todowrite","todo_write","todoread"]);B("question",["question","ask"]);B("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);B("connectors",["connector_get","connector_list","connector_setup","kortix_connector_call","kortix_connectors","kortix_connectors_connectors","kortix_connectors_discover","kortix_connectors_describe","kortix_connectors_call","kortix_connector_describe","kortix_connector_discover"]);B("automations",["triggers"]);B("skill",["skill"]);B("context",["prune","distill","compress","context_info"]);B("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var NA=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ne(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=ty[t];if(n)return n;for(let[r,o]of NA)if(t.startsWith(r))return o;return"other"}function Re(e){for(let t of[e?.filePath,e?.file_path,e?.path])if(typeof t=="string"&&t)return t}var KA=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function qA(){return new RegExp(`(^|\\s)([-+]?)(${KA.join("|")}):("[^"]*"|\\S+)`,"gi")}function GA(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function BA(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function WA(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function HA(e){return WA(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function ny(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function In(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(qA(),(o,s,i,a,l)=>{if(!i&&a.toLowerCase()==="site"){let p=HA(l);p&&!n.includes(p)&&n.push(p)}return s});return r=r.replace(GA(),"$1").replace(BA(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${ny(n)}`:r:n.length>0?ny(n):t}var VA=/\s/,zA=/\w/;function oe(e){return e!==void 0&&VA.test(e)}function Tn(e){return e===`
75
- `||e==="\r"||e==="\u2028"||e==="\u2029"}function ud(e){return e!==void 0&&zA.test(e)}function tt(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(YA(n.charCodeAt(0))):n;return t}function YA(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 Ie(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function ry(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Ie(e.slice(t))}function Cn(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let o=e.indexOf(n,r+t.length);return o===-1?null:e.slice(r+t.length,o)}function pd(e,t){let n=Cn(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
74
+ `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function Yf(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function LA(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 FA(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 Vf(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,o=typeof e.upstream_status=="number"?e.upstream_status:void 0,s=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=FA(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&&o===void 0&&!s&&!i?void 0:{message:typeof e.message=="string"&&e.message||LA(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:o,requestId:s,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function ue(e){if(e==null)return;if(typeof e=="string"){let i=id(e),a=Ct(i)??Ct(Yf(i));return a!==void 0?ue(a):void 0}if(typeof e!="object")return;let t=e,n=Vf(t);if(n)return n;let r=t.error;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=Vf(r);if(i)return i}let o=t.data;if(o&&typeof o.responseBody=="string"){let i=Ct(o.responseBody);if(i!==void 0){let a=ue(i);if(a)return a}}if(o&&typeof o.message=="string"){let i=ue(o.message);if(i)return i}let s=t.cause;if(s&&typeof s=="object"){let i=s.body;if(i!==void 0){let a=ue(i);if(a)return a}}}var Qf={};function B(e,t){for(let n of t)Qf[n]=e}B("read",["read"]);B("list",["list","ls"]);B("glob",["glob"]);B("grep",["grep"]);B("write",["write"]);B("edit",["edit","multiedit","morph_edit"]);B("apply_patch",["apply_patch","patch"]);B("bash",["bash"]);B("web_search",["web_search","websearch","image_search"]);B("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);B("media",["image_gen","video_gen"]);B("show",["show","show_user","presentation_gen"]);B("task",["task"]);B("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"]);B("todowrite",["todowrite","todo_write","todoread"]);B("question",["question","ask"]);B("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);B("connectors",["connector_get","connector_list","connector_setup","kortix_connector_call","kortix_connectors","kortix_connectors_connectors","kortix_connectors_discover","kortix_connectors_describe","kortix_connectors_call","kortix_connector_describe","kortix_connector_discover"]);B("automations",["triggers"]);B("skill",["skill"]);B("context",["prune","distill","compress","context_info"]);B("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var NA=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ne(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=Qf[t];if(n)return n;for(let[r,o]of NA)if(t.startsWith(r))return o;return"other"}function ke(e){for(let t of[e?.filePath,e?.file_path,e?.path])if(typeof t=="string"&&t)return t}var KA=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function qA(){return new RegExp(`(^|\\s)([-+]?)(${KA.join("|")}):("[^"]*"|\\S+)`,"gi")}function GA(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function BA(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function WA(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function HA(e){return WA(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function Xf(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Rn(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(qA(),(o,s,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=HA(c);p&&!n.includes(p)&&n.push(p)}return s});return r=r.replace(GA(),"$1").replace(BA(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${Xf(n)}`:r:n.length>0?Xf(n):t}var VA=/\s/,zA=/\w/;function oe(e){return e!==void 0&&VA.test(e)}function In(e){return e===`
75
+ `||e==="\r"||e==="\u2028"||e==="\u2029"}function cd(e){return e!==void 0&&zA.test(e)}function Ze(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(YA(n.charCodeAt(0))):n;return t}function YA(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 Re(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function Jf(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Re(e.slice(t))}function Tn(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let o=e.indexOf(n,r+t.length);return o===-1?null:e.slice(r+t.length,o)}function ld(e,t){let n=Tn(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 dd(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let o=e.indexOf(">",r+1+t.length);return o===-1?null:{open:r,end:o}}function oy(e,t){let n=dd(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function sy(e,t){let n=dd(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 iy(e,t){let n=`</${t}>`,r="",o=0;for(;;){let s=dd(e,t,o);if(!s)break;let i=e.indexOf(n,s.end+1);if(i===-1)break;r+=e.slice(o,s.open),o=i+n.length}return r+e.slice(o)}function ay(e,t,n){let r=[];for(let o of e.split(/[\n\r\u2028\u2029]/)){let s=0;for(;;){let i=o.indexOf(t,s);if(i===-1)break;let a=o.indexOf(n,i+t.length);if(a===-1)break;r.push(o.slice(i+t.length,a)),s=a+n.length}}return r}function En(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&&oe(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function cy(e,t,n){let r=tt(t),o=tt(n);for(let s of tt(e).split(/[\n\r\u2028\u2029]/)){let i=s.indexOf(r);if(i!==-1&&s.lastIndexOf(o)>=i+r.length)return!0}return!1}function ly(e,t){let n=tt(e),r=t.map(tt),o=e.length,s=l=>{let p=l;for(;p<o&&oe(e[p]);)p++;return p},i=l=>{for(let p=l;p<o;p++)if(Tn(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=o;){let l=s(a);if(l>=o)return null;let p=r.find(d=>n.startsWith(d,l));if(p!==void 0){let d=s(l+p.length);if(e[d]===":"){let g=s(d+1);if(g<o){let m=g;for(;m<o&&!Tn(e[m]);)m++;for(;m>g+1&&oe(e[m-1]);)m--;return e.slice(g,m)}for(let m=o-1;m>d;m--)if(!Tn(e[m]))return e[m];return null}}a=i(l)}return null}function uy(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=oe(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"||!oe(e[a-1]))continue;let l=a+1;if(oe(e[l])){for(;l<t&&oe(e[l]);)l++;ud(e[l])&&(r[a]=a)}}let o=new Array(t+1);o[0]=0;for(let a=0;a<t;a++)o[a+1]=o[a]+(Tn(e[a])?1:0);let s=(a,l)=>o[l]===o[a],i=a=>{let l=a+1;for(;oe(e[l]);)l++;let p=l;for(;p<t&&ud(e[p]);)p++;return e.slice(l,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let l=a+7;for(;l<t&&/[a-z0-9]/.test(e[l]);)l++;if(l===a+7||e[l]!=="*"||e[l+1]!=="*")continue;let p=l+2,d=p;for(;d<t&&oe(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(s(d,m))return{id:e.slice(a+2,l),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Tn(e[g]))return{id:e.slice(a+2,l),title:e[g],status:i(d)}}}}return null}function py(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&oe(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&oe(e[i]);)i++;n=i}let r=e.slice(n),o="",s=0;for(;s<r.length;){if(t(r,s)&&(s===0||!ud(r[s-1]))){let i=s,a=0;for(;t(r,i);){for(i+=6;i<r.length&&oe(r[i]);)i++;a++}if(a>=2){s=i;continue}}o+=r[s],s++}return o}function dy(e,t){let n=t?"![":"[",r="",o=0,s=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let l=a+n.length;if(s<l&&(s=e.indexOf("]",l)),s===-1)break;let p=s;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(o,a)+(t?" ":e.slice(l,p)),o=i+1,a=e.indexOf(n,o)}return r+e.slice(o)}function gy(e){return dy(e,!0)}function my(e){return dy(e,!1)}function QA(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function fy(e,t){let n=tt(e),r=tt(t),o=e.length,s=i=>{let a=i;for(;a<o&&oe(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=s(i+r.length);if(e[a]!==":")continue;let l=s(a+1);for(let p=l;p<o;){if(!oe(e[p])){p++;continue}let d=s(p);if(QA(e,d))return e.slice(l,p);p=d}return e.slice(l)}return null}var yy=new Set(["read","glob","grep","list"]);function W(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function XA(e){return yy.has(ne(e))}function JA(e){let t=0,n=0,r=0;for(let o of e){let s=ne(o.tool);s==="read"?t++:s==="glob"||s==="grep"?n++:s==="list"&&r++}return{read:t,search:n,list:r}}function gd(e){if(!e)return"";let t=Ie(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function no(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function ro(e){let n=(e.state??{}).input??{};switch(W(e.tool)){case"read":case"edit":case"write":case"morph_edit":{let s=n.filePath??n.file_path??n.path;return s?gd(String(s)):""}case"glob":return n.pattern?String(n.pattern):"";case"grep":{let s=n.pattern??n.query,i=n.path??n.include;return s&&i?`"${no(String(s),40)}" in ${gd(String(i))}`:s?`"${no(String(s),60)}"`:""}case"list":return n.path?gd(String(n.path)):"";case"bash":return no(String(n.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let s of o){let i=n[s];if(typeof i=="string"&&i.length>0)return no(s==="query"&&In(i)||i,60)}return""}var hy={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 ZA(e,t={}){let n={...hy,...t},r=W(e.tool),o=ro(e);switch(r){case"read":return{title:n.read,subtitle:o};case"glob":case"grep":return{title:n.search,subtitle:o};case"list":return{title:n.list,subtitle:o};case"bash":return{title:n.shell,subtitle:o};case"edit":case"morph_edit":return{title:n.edit,subtitle:o};case"write":return{title:n.write,subtitle:o};case"webfetch":case"web_fetch":return{title:n.fetch,subtitle:o};case"websearch":case"web_search":return{title:n.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:n.scrape,subtitle:o};case"apply_patch":return{title:n.applyPatch,subtitle:o};case"task":return{title:n.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:n.worker,subtitle:o};case"project_select":case"project_list":return{title:n.workspace,subtitle:o};default:return{title:r.replace(/_/g," ").replace(/\b\w/g,i=>i.toUpperCase()),subtitle:o}}}function ye(e){return e.type==="text"}function he(e){return e.type==="reasoning"}function Y(e){return e.type==="tool"}function fd(e){return e.type==="file"}function ek(e){return e.type==="agent"}function tk(e){return e.type==="compaction"}function nk(e){return e.type==="snapshot"}function rk(e){return e.type==="patch"}function ok(e){return e.type==="step-start"||e.type==="step-finish"}function sk(e){if(ye(e)||he(e))return e.text}function ik(e){if(!fd(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function ak(e){let t=[],n=[];for(let r of e)fd(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function ck(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function lk(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var uk=new Set(["todoread","context_info"]);function by(e){return!uk.has(e.tool)}var pk=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 yd(e){let t=e.tool||"";if(t.startsWith("oc-"))return;let n=ne(t);if(n==="task"||n==="delegate"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r}return dk(t,e.state)}function dk(e,t){let n=W(e);if(pk.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 gk(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return le(n.error)}}function mk(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)Y(r)&&by(r)&&t.push(r);return t}function fk(e,t={}){switch(W(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:xy(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"KortixWorker"})`,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 yk(e,t)}}function yk(e,t){switch(ne(e)){case"read":return{icon:"glasses",title:"Read",subtitle:_y(Re(t))};case"list":return{icon:"list",title:"List",subtitle:Py(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:md(Re(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:md(Re(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function _y(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function md(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 Py(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function hk(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 Mn(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 xy(e){let t=Mn(e.description);if(t)return t;let n=Mn(e.title,80);if(n)return n;let r=Mn(e.message);if(r)return r;let o=Mn(e.prompt);if(o)return o;let s=Mn(e.agent_id,40);return s?`Agent ${s}`:"Worker task"}function bk(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function _k(e,t){return e.find(n=>n.tool?.callID===t)}function Pk(e,t){return e.find(n=>n.tool?.callID===t)}var xk=/\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 Sk(e){return e?e.replace(xk,""):""}var wk={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"},vk={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function Ak(e){return e.replace(/^oc[-_]/,"")}function hd(e){return Ak(e).replace(/-/g,"_")}function bd(e){return hd(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function oo(e){return{label:wk[hd(e)]??bd(e),category:vk[ne(e)]}}var kk=256*1024;function Rk(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function Ik(e){if(e===void 0)return{};if(e.length>kk)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function Tk(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,o=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!o))return o?le(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var Z=e=>typeof e=="string"?e:void 0,so=e=>typeof e=="number"?e:void 0,io=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function _d(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Ck=new Set(["add","update","delete","move"]);function Ek(e,t,n){if(e==="apply_patch"){let l=(Array.isArray(n.files)?n.files:[]).flatMap(p=>{let d=io(p),g=d&&(Z(d.relativePath)||Z(d.filePath));if(!d||!g)return[];let m=Z(d.type);return[_d({path:g,type:m&&Ck.has(m)?m:void 0,before:Z(d.before),after:Z(d.after),patch:Z(d.patch)??Z(d.diff),additions:so(d.additions),deletions:so(d.deletions),movePath:Z(d.movePath)})]});return l.length?l:void 0}let r=Re(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[_d({path:r,after:Z(t.content)})];if(e!=="edit")return;let o=io(n.filediff),s=o?void 0:Z(n.patch),i=s?Mk(s):void 0;return[_d({path:r,before:Z(o?.before)??Z(t.oldString),after:Z(o?.after)??Z(t.newString),patch:s,additions:so(o?.additions)??i?.additions,deletions:so(o?.deletions)??i?.deletions})]}function Mk(e){let t=0,n=0;for(let r of e.split(`
79
- `))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function Ok(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function Sy(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:o,outputText:s}=Ik(r),i=Rk(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=Tk(o);m&&(i="error",a=m)}let l=ne(e),p=t.input??{},d="metadata"in t&&io(t.metadata)||{},g=io(d.diagnostics);return{name:e,kind:l,title:n||oo(e).label,status:i,input:t.input,output:r,outputParsed:o,outputText:s,error:a,files:Ek(l,p,d),diff:Z(d.patch)??Z(d.diff),diagnostics:g,answers:l==="question"?Ok(d):void 0,childSessionId:yd({tool:e,state:t})}}function jk(e){return Sy(e.tool,e.state)}function Dk(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function $k(e){return{kind:"reasoning",id:e.id,text:e.text}}function Uk(e){return{kind:"tool",id:e.id,tool:Sy(e.tool,e.state)}}function Lk(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 Fk(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function Nk(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function Kk(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function qk(e){return{kind:"agent",id:e.id,name:e.name}}function Gk(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:le(e.error),createdAt:e.time.created}}function Bk(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function Wk(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function Hk(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Pd(e){switch(e.type){case"text":return Dk(e);case"reasoning":return $k(e);case"tool":return Uk(e);case"file":return Lk(e);case"subtask":return Fk(e);case"patch":return Nk(e);case"snapshot":return Kk(e);case"agent":return qk(e);case"retry":return Gk(e);case"compaction":return Bk(e);case"step-start":return Wk(e);case"step-finish":return Hk(e);default:return{kind:"unknown",raw:e}}}function Vk(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=ue(e);return{name:t,message:n?.message||le(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function zk(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function wy(e){let t=e.parts.map(Pd),n=e.info.role==="assistant"?e.info.error:void 0,r=Vk(n),o=!r&&!t.some(zk);return{parts:t,error:r,isEmpty:o}}var xd=Ae+BigInt(1),vy=xd/BigInt(2);function ao(e){return BigInt(Math.trunc(e))*bt}function Sd(e,t){let r=t-(t&Ae)+e;return r-t>vy?r-=xd:t-r>vy&&(r+=xd),r}function Ay(e,t){let n=Xe(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return Sd(n,t);let o=ao(r),s=Sd(n,o);return(s>o?s-o:o-s)<=De?s:o}function ky(e){return Xe(e)===null?1:0}function Ry(e,t){return e<t?-1:e>t?1:0}function Yk(e,t){return Iy(e,t,ao(Date.now()))}function Qk(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 ao(t??Date.now())}function Iy(e,t,n){let r=ky(e.info.id),o=ky(t.info.id);if(r!==o)return r-o;if(r===0){let a=Ay(e,n),l=Ay(t,n);return a!==l?a<l?-1:1:Ry(e.info.id,t.info.id)}let s=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return s===null&&i===null?0:s===null?1:i===null?-1:s!==i?s<i?-1:1:Ry(e.info.id,t.info.id)}function Xk(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=Qk(e),o=[...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:Iy(d,g,r)}),s=[],i=new Map;for(let d of o)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};s.push(g),i.set(d.info.id,g)}let a=null,l=[],p=[];for(let d of o){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=l[l.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):l.push({userMessage:Zk(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=s[0]??l[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;s.push({userMessage:g,assistantMessages:m})}}return l.length>0?[...l,...s]:s}var On=new Map,Jk=256;function Zk(e,t){let n=t.info,r=n.time?.created,o=`${n.sessionID??""}|${e}|${r??""}`,s=On.get(o);if(s)return s;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(On.size>=Jk){let a=On.keys().next().value;a!==void 0&&On.delete(a)}return On.set(o,i),i}function eR(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function tR(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(ye(n)&&n.text?.trim())return n}}function nR(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function rR(e,t,n){if(n)return[];let r=[];for(let o of e.assistantMessages)for(let s of o.parts){if(!Y(s))continue;let i=s,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:s,message:o})}return r}function oR(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 sR(e){let t=e-6e4;return(n,r)=>{let o=n.time.updated??n.time.created,s=r.time.updated??r.time.created,i=o>t,a=s>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:s-o}}function Ty(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let o of n)r.push(o),r.push(...Ty(e,o));return r}function Cy(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function iR(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&&Cy(n.error)}return!1}function co(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function wd(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 aR(e){return!!e&&(wd(e)||My(e)!==null)}function vd(e){let t=Ey.get(e);if(t&&t.state===e.state)return t.outcome;let n=cR(e);return Ey.set(e,{state:e.state,outcome:n}),n}var Ey=new WeakMap;function cR(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(wd(n))return"failed";let r=lR(n);return r===void 0?"ok":uR(r)?"failed":pR(r)}function lR(e){try{return JSON.parse(e)}catch{return}}function uR(e){return co(e)&&e.success===!1&&typeof e.error=="string"}function pR(e){let t=co(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 My(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!co(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},o=En(r.errorSummary);if(o===null)return r;try{let s=JSON.parse(o);typeof s.message=="string"&&s.message.trim()&&(r.nestedMessage=s.message.trim()),typeof s.status=="number"&&(r.status=s.status),typeof s.error=="boolean"&&(r.nestedError=s.error)}catch{}return r}function dR(e){return py(e).replace(/\s+/g," ").trim()||e.trim()}function gR(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!co(n))return null;let r=n.success,o=n.error,s=n.hint;if(r!==!1||typeof o!="string")return null;let i=[];i.push(o.trim());let a=En(o);if(a!==null)try{let p=JSON.parse(a).message;typeof p=="string"&&p.trim()&&i.push(`Details: ${p.trim()}`)}catch{}return typeof s=="string"&&s.trim()&&i.push(`Hint: ${s.trim()}`),i.join(`
77
+ `)&&(n=n.slice(0,-1)),n)}function ud(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let o=e.indexOf(">",r+1+t.length);return o===-1?null:{open:r,end:o}}function Zf(e,t){let n=ud(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function ey(e,t){let n=ud(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 ty(e,t){let n=`</${t}>`,r="",o=0;for(;;){let s=ud(e,t,o);if(!s)break;let i=e.indexOf(n,s.end+1);if(i===-1)break;r+=e.slice(o,s.open),o=i+n.length}return r+e.slice(o)}function ny(e,t,n){let r=[];for(let o of e.split(/[\n\r\u2028\u2029]/)){let s=0;for(;;){let i=o.indexOf(t,s);if(i===-1)break;let a=o.indexOf(n,i+t.length);if(a===-1)break;r.push(o.slice(i+t.length,a)),s=a+n.length}}return r}function Cn(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&&oe(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function ry(e,t,n){let r=Ze(t),o=Ze(n);for(let s of Ze(e).split(/[\n\r\u2028\u2029]/)){let i=s.indexOf(r);if(i!==-1&&s.lastIndexOf(o)>=i+r.length)return!0}return!1}function oy(e,t){let n=Ze(e),r=t.map(Ze),o=e.length,s=c=>{let p=c;for(;p<o&&oe(e[p]);)p++;return p},i=c=>{for(let p=c;p<o;p++)if(In(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=o;){let c=s(a);if(c>=o)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=s(c+p.length);if(e[d]===":"){let g=s(d+1);if(g<o){let m=g;for(;m<o&&!In(e[m]);)m++;for(;m>g+1&&oe(e[m-1]);)m--;return e.slice(g,m)}for(let m=o-1;m>d;m--)if(!In(e[m]))return e[m];return null}}a=i(c)}return null}function sy(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=oe(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"||!oe(e[a-1]))continue;let c=a+1;if(oe(e[c])){for(;c<t&&oe(e[c]);)c++;cd(e[c])&&(r[a]=a)}}let o=new Array(t+1);o[0]=0;for(let a=0;a<t;a++)o[a+1]=o[a]+(In(e[a])?1:0);let s=(a,c)=>o[c]===o[a],i=a=>{let c=a+1;for(;oe(e[c]);)c++;let p=c;for(;p<t&&cd(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&&oe(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(s(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(!In(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function iy(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&oe(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&oe(e[i]);)i++;n=i}let r=e.slice(n),o="",s=0;for(;s<r.length;){if(t(r,s)&&(s===0||!cd(r[s-1]))){let i=s,a=0;for(;t(r,i);){for(i+=6;i<r.length&&oe(r[i]);)i++;a++}if(a>=2){s=i;continue}}o+=r[s],s++}return o}function ay(e,t){let n=t?"![":"[",r="",o=0,s=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(s<c&&(s=e.indexOf("]",c)),s===-1)break;let p=s;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(o,a)+(t?" ":e.slice(c,p)),o=i+1,a=e.indexOf(n,o)}return r+e.slice(o)}function cy(e){return ay(e,!0)}function ly(e){return ay(e,!1)}function QA(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function uy(e,t){let n=Ze(e),r=Ze(t),o=e.length,s=i=>{let a=i;for(;a<o&&oe(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=s(i+r.length);if(e[a]!==":")continue;let c=s(a+1);for(let p=c;p<o;){if(!oe(e[p])){p++;continue}let d=s(p);if(QA(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var py=new Set(["read","glob","grep","list"]);function W(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function XA(e){return py.has(ne(e))}function JA(e){let t=0,n=0,r=0;for(let o of e){let s=ne(o.tool);s==="read"?t++:s==="glob"||s==="grep"?n++:s==="list"&&r++}return{read:t,search:n,list:r}}function pd(e){if(!e)return"";let t=Re(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function no(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function ro(e){let n=(e.state??{}).input??{};switch(W(e.tool)){case"read":case"edit":case"write":case"morph_edit":{let s=n.filePath??n.file_path??n.path;return s?pd(String(s)):""}case"glob":return n.pattern?String(n.pattern):"";case"grep":{let s=n.pattern??n.query,i=n.path??n.include;return s&&i?`"${no(String(s),40)}" in ${pd(String(i))}`:s?`"${no(String(s),60)}"`:""}case"list":return n.path?pd(String(n.path)):"";case"bash":return no(String(n.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let s of o){let i=n[s];if(typeof i=="string"&&i.length>0)return no(s==="query"&&Rn(i)||i,60)}return""}var dy={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 ZA(e,t={}){let n={...dy,...t},r=W(e.tool),o=ro(e);switch(r){case"read":return{title:n.read,subtitle:o};case"glob":case"grep":return{title:n.search,subtitle:o};case"list":return{title:n.list,subtitle:o};case"bash":return{title:n.shell,subtitle:o};case"edit":case"morph_edit":return{title:n.edit,subtitle:o};case"write":return{title:n.write,subtitle:o};case"webfetch":case"web_fetch":return{title:n.fetch,subtitle:o};case"websearch":case"web_search":return{title:n.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:n.scrape,subtitle:o};case"apply_patch":return{title:n.applyPatch,subtitle:o};case"task":return{title:n.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:n.worker,subtitle:o};case"project_select":case"project_list":return{title:n.workspace,subtitle:o};default:return{title:r.replace(/_/g," ").replace(/\b\w/g,i=>i.toUpperCase()),subtitle:o}}}function fe(e){return e.type==="text"}function ye(e){return e.type==="reasoning"}function Y(e){return e.type==="tool"}function gd(e){return e.type==="file"}function ek(e){return e.type==="agent"}function tk(e){return e.type==="compaction"}function nk(e){return e.type==="snapshot"}function rk(e){return e.type==="patch"}function ok(e){return e.type==="step-start"||e.type==="step-finish"}function sk(e){if(fe(e)||ye(e))return e.text}function ik(e){if(!gd(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function ak(e){let t=[],n=[];for(let r of e)gd(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function ck(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function lk(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var uk=new Set(["todoread","context_info"]);function gy(e){return!uk.has(e.tool)}var pk=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 md(e){let t=e.tool||"";if(t.startsWith("oc-"))return;let n=ne(t);if(n==="task"||n==="delegate"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r}return dk(t,e.state)}function dk(e,t){let n=W(e);if(pk.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 gk(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return ce(n.error)}}function mk(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)Y(r)&&gy(r)&&t.push(r);return t}function fk(e,t={}){switch(W(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:yy(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"KortixWorker"})`,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 yk(e,t)}}function yk(e,t){switch(ne(e)){case"read":return{icon:"glasses",title:"Read",subtitle:my(ke(t))};case"list":return{icon:"list",title:"List",subtitle:fy(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:dd(ke(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:dd(ke(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function my(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function dd(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 fy(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function hk(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 En(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 yy(e){let t=En(e.description);if(t)return t;let n=En(e.title,80);if(n)return n;let r=En(e.message);if(r)return r;let o=En(e.prompt);if(o)return o;let s=En(e.agent_id,40);return s?`Agent ${s}`:"Worker task"}function bk(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function _k(e,t){return e.find(n=>n.tool?.callID===t)}function Pk(e,t){return e.find(n=>n.tool?.callID===t)}var xk=/\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 Sk(e){return e?e.replace(xk,""):""}var wk={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"},vk={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function Ak(e){return e.replace(/^oc[-_]/,"")}function fd(e){return Ak(e).replace(/-/g,"_")}function yd(e){return fd(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function oo(e){return{label:wk[fd(e)]??yd(e),category:vk[ne(e)]}}var kk=256*1024;function Rk(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function Ik(e){if(e===void 0)return{};if(e.length>kk)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function Tk(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,o=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!o))return o?ce(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var Z=e=>typeof e=="string"?e:void 0,so=e=>typeof e=="number"?e:void 0,io=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function hd(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var Ck=new Set(["add","update","delete","move"]);function Ek(e,t,n){if(e==="apply_patch"){let c=(Array.isArray(n.files)?n.files:[]).flatMap(p=>{let d=io(p),g=d&&(Z(d.relativePath)||Z(d.filePath));if(!d||!g)return[];let m=Z(d.type);return[hd({path:g,type:m&&Ck.has(m)?m:void 0,before:Z(d.before),after:Z(d.after),patch:Z(d.patch)??Z(d.diff),additions:so(d.additions),deletions:so(d.deletions),movePath:Z(d.movePath)})]});return c.length?c:void 0}let r=ke(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[hd({path:r,after:Z(t.content)})];if(e!=="edit")return;let o=io(n.filediff),s=o?void 0:Z(n.patch),i=s?Mk(s):void 0;return[hd({path:r,before:Z(o?.before)??Z(t.oldString),after:Z(o?.after)??Z(t.newString),patch:s,additions:so(o?.additions)??i?.additions,deletions:so(o?.deletions)??i?.deletions})]}function Mk(e){let t=0,n=0;for(let r of e.split(`
79
+ `))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function Ok(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function hy(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:o,outputText:s}=Ik(r),i=Rk(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=Tk(o);m&&(i="error",a=m)}let c=ne(e),p=t.input??{},d="metadata"in t&&io(t.metadata)||{},g=io(d.diagnostics);return{name:e,kind:c,title:n||oo(e).label,status:i,input:t.input,output:r,outputParsed:o,outputText:s,error:a,files:Ek(c,p,d),diff:Z(d.patch)??Z(d.diff),diagnostics:g,answers:c==="question"?Ok(d):void 0,childSessionId:md({tool:e,state:t})}}function jk(e){return hy(e.tool,e.state)}function Dk(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function $k(e){return{kind:"reasoning",id:e.id,text:e.text}}function Uk(e){return{kind:"tool",id:e.id,tool:hy(e.tool,e.state)}}function Lk(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 Fk(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function Nk(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function Kk(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function qk(e){return{kind:"agent",id:e.id,name:e.name}}function Gk(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:ce(e.error),createdAt:e.time.created}}function Bk(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function Wk(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function Hk(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function bd(e){switch(e.type){case"text":return Dk(e);case"reasoning":return $k(e);case"tool":return Uk(e);case"file":return Lk(e);case"subtask":return Fk(e);case"patch":return Nk(e);case"snapshot":return Kk(e);case"agent":return qk(e);case"retry":return Gk(e);case"compaction":return Bk(e);case"step-start":return Wk(e);case"step-finish":return Hk(e);default:return{kind:"unknown",raw:e}}}function Vk(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=ue(e);return{name:t,message:n?.message||ce(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function zk(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function by(e){let t=e.parts.map(bd),n=e.info.role==="assistant"?e.info.error:void 0,r=Vk(n),o=!r&&!t.some(zk);return{parts:t,error:r,isEmpty:o}}var _d=ve+BigInt(1),_y=_d/BigInt(2);function ao(e){return BigInt(Math.trunc(e))*yt}function Pd(e,t){let r=t-(t&ve)+e;return r-t>_y?r-=_d:t-r>_y&&(r+=_d),r}function Py(e,t){let n=Ye(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return Pd(n,t);let o=ao(r),s=Pd(n,o);return(s>o?s-o:o-s)<=je?s:o}function xy(e){return Ye(e)===null?1:0}function Sy(e,t){return e<t?-1:e>t?1:0}function Yk(e,t){return wy(e,t,ao(Date.now()))}function Qk(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 ao(t??Date.now())}function wy(e,t,n){let r=xy(e.info.id),o=xy(t.info.id);if(r!==o)return r-o;if(r===0){let a=Py(e,n),c=Py(t,n);return a!==c?a<c?-1:1:Sy(e.info.id,t.info.id)}let s=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return s===null&&i===null?0:s===null?1:i===null?-1:s!==i?s<i?-1:1:Sy(e.info.id,t.info.id)}function Xk(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=Qk(e),o=[...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:wy(d,g,r)}),s=[],i=new Map;for(let d of o)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};s.push(g),i.set(d.info.id,g)}let a=null,c=[],p=[];for(let d of o){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:Zk(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=s[0]??c[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;s.push({userMessage:g,assistantMessages:m})}}return c.length>0?[...c,...s]:s}var Mn=new Map,Jk=256;function Zk(e,t){let n=t.info,r=n.time?.created,o=`${n.sessionID??""}|${e}|${r??""}`,s=Mn.get(o);if(s)return s;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(Mn.size>=Jk){let a=Mn.keys().next().value;a!==void 0&&Mn.delete(a)}return Mn.set(o,i),i}function eR(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function tR(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(fe(n)&&n.text?.trim())return n}}function nR(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function rR(e,t,n){if(n)return[];let r=[];for(let o of e.assistantMessages)for(let s of o.parts){if(!Y(s))continue;let i=s,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:s,message:o})}return r}function oR(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 sR(e){let t=e-6e4;return(n,r)=>{let o=n.time.updated??n.time.created,s=r.time.updated??r.time.created,i=o>t,a=s>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:s-o}}function vy(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let o of n)r.push(o),r.push(...vy(e,o));return r}function Ay(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function iR(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&&Ay(n.error)}return!1}function co(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function xd(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 aR(e){return!!e&&(xd(e)||Ry(e)!==null)}function Sd(e){let t=ky.get(e);if(t&&t.state===e.state)return t.outcome;let n=cR(e);return ky.set(e,{state:e.state,outcome:n}),n}var ky=new WeakMap;function cR(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(xd(n))return"failed";let r=lR(n);return r===void 0?"ok":uR(r)?"failed":pR(r)}function lR(e){try{return JSON.parse(e)}catch{return}}function uR(e){return co(e)&&e.success===!1&&typeof e.error=="string"}function pR(e){let t=co(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 Ry(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!co(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},o=Cn(r.errorSummary);if(o===null)return r;try{let s=JSON.parse(o);typeof s.message=="string"&&s.message.trim()&&(r.nestedMessage=s.message.trim()),typeof s.status=="number"&&(r.status=s.status),typeof s.error=="boolean"&&(r.nestedError=s.error)}catch{}return r}function dR(e){return iy(e).replace(/\s+/g," ").trim()||e.trim()}function gR(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!co(n))return null;let r=n.success,o=n.error,s=n.hint;if(r!==!1||typeof o!="string")return null;let i=[];i.push(o.trim());let a=Cn(o);if(a!==null)try{let p=JSON.parse(a).message;typeof p=="string"&&p.trim()&&i.push(`Details: ${p.trim()}`)}catch{}return typeof s=="string"&&s.trim()&&i.push(`Hint: ${s.trim()}`),i.join(`
80
80
 
81
- `)}var Oy=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),mR={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 fR(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&In(t)||t}function yR(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim())return fR(r,o.trim())}}function Ad(e){if(he(e))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!Y(e))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let t=ae(e.tool),n=mR[t],r=e.state?.input;return n?{verb:n.verb,running:n.running,object:yR(r,n.objectKeys),tier:Oy.has(t)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:t,tier:"primary"}}function hR(e){let t=0,n=0,r=!1,o=!1;for(let s of e){if(Ad(s).tier==="plumbing"){r=!0;continue}if(he(s)){if(!s.text?.trim())continue;o||(o=!0,t+=1);continue}o=!1,t+=1,Y(s)&&vd(s)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function kd(e){return`${e} ${e===1?"step":"steps"}`}function bR(e,t){let{total:n,failed:r,completed:o,hasPlumbing:s}=e;return t?n===0?"Working":`Working \xB7 ${kd(n)}`:n===0?s?"Housekeeping":"Worked":r===0?`Completed ${kd(n)}`:o===0?`${kd(n)} failed`:`Completed ${o} of ${n} steps \xB7 ${r} failed`}function _R(e){let t=!1,n=!1,r=!1,o=null,s=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),o==null&&d.error!=null&&(o=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)},l=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");l&&(t=!0),e.userMessage&&s(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)s(p.info),i(p.parts);return l&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:o}}function PR(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function xR(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 SR(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=gy(n),n=my(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 wR(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 o=r.error.trim(),s;for(let i=0;i<3;i++){let a=En(o);if(a===null)break;let l;try{l=JSON.parse(a)}catch{break}if(typeof l.status=="number"&&(s=l.status),typeof l.message=="string"&&l.message.trim())o=l.message.trim();else if(typeof l.error=="string"&&l.error.trim())o=l.error.trim();else break}return{message:o,status:s}}function jn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function lo(e,t=30){if(!e)return[];let n=[],r=new Set,o=(a,l,p)=>{!/^https?:\/\//i.test(l)||r.has(l)||n.length>=t||(r.add(l),n.push({title:a.trim()||l,url:l,snippet:p?.trim()||void 0}))},s=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=s.exec(e))!==null;)if(o(jn(i[1]),jn(i[2]),i[3]?jn(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(o(jn(i[2]),jn(i[1])),n.length>=t)return n}return n}function jy(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 uo(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 Rd(e){if(!e)return[];let t=jy(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 o of t.results)typeof o.query=="string"&&r.push({query:o.query,answer:o.answer||void 0,sources:Array.isArray(o.results)?uo(o.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=uo(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)?uo(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=uo(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let o of n){let s=o.match(/^Title:\s*(.+)/m),i=o.match(/^URL:\s*(.+)/m),a=o.match(/^Author:\s*(.+)/m),l=o.match(/^Published Date:\s*(.+)/m),p=o.match(/^Text:\s*([\s\S]*?)$/m);s&&i&&r.push({title:s[1].trim(),url:i[1].trim(),snippet:p?.[1]?.trim()||void 0,author:a?.[1]?.trim()||void 0,publishedDate:l?.[1]?.trim()||void 0})}if(r.length>0)return[{query:"",sources:r}]}if(typeof e=="string"){let n=lo(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function po(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function vR(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return po(e)}}function AR(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function kR(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 Dy(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 o=r.trim();/^https?:\/\//i.test(o)&&n.push(o)}return n}return[]}function $y(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let o=fy(n,r)?.trim()||n;return{url:r,success:!1,error:o}})}function RR(e,t){let n=Uy(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?$y(r,Dy(t)):[]}function Uy(e){if(!e)return null;let t=jy(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=lo(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 IR(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 TR={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 go(e){return TR[ne(e)]}function $n(e){let t=W(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var CR={run:"Terminal",memory:"Memory"};function ER(e){let t=go(e);return(t==="hidden"?void 0:CR[t])??$n(e)}function Dn(e,t,n){return e===1?t:n}function Id(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 Ny(e){return e.length?ro(e[0]):""}function be(e){return(e.state??{}).input??{}}var MR={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 OR(e){let t=W(e.tool);if(t==="agent_task_update"||t==="task_update")switch(be(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return MR[t]??"message"}function Ly(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 jR(e){let t=W(e.tool);if(t==="triggers"){let r=be(e).action||"list";return Ly(r)}let n=t.match(/^trigger_(.+)$/);return Ly(n?n[1]:"list")}var DR={connector_setup:"connect",connector_get:"read",connector_list:"read",kortix_connector_discover:"read",kortix_connector_describe:"read",kortix_connectors:"read",kortix_connectors_connectors:"read",kortix_connectors_discover:"read",kortix_connectors_describe:"read",kortix_connector_call:"call",kortix_connectors_call:"call"};function $R(e){return DR[W(e.tool)]??"read"}var UR={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function LR(e){return UR[W(e.tool)]??"open"}function Ot(e){return e.every(t=>t===e[0])}var FR={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function NR(e){if(W(e.tool)!=="memory")return"read";let n=be(e).command;return n&&FR[n]||"unknown"}var KR={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},qR={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 GR(e){let t=Ie(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function BR(e){let t=be(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 WR(r,60);let o=typeof t.path=="string"?t.path:"";if(o)return GR(o);let s=typeof t.url=="string"?t.url:"";if(s){let i=IR(s);return i?po(i):"a link"}return""}function WR(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function HR(e){let t=be(e).action;return t&&KR[t]||"Worked on an image"}function VR(e){let t=be(e).action;return t&&qR[t]||"Worked on a presentation"}function zR(e){return e.slice(0,e.indexOf(":"))}var YR={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},QR={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 XR(e){let t=W(e.tool);if(t==="image_gen"){let n=be(e).action;return n&&YR[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=be(e).action;return n&&QR[n]||"presentation:unknown"}return"shown:result"}var JR=new Set(["create_slide","export_pdf","export_pptx"]);function ZR(e){let t=W(e.tool);if(t==="image_gen")return"image";if(t==="video_gen")return"video";if(t==="presentation_gen"){let n=be(e).action;return n?JR.has(n)?"presentation":null:"presentation"}return null}var eI={"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`},Fy={image:"image",video:"video",presentation:"presentation",shown:"result"};function tI(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[zR(r)]++;let n=[];return Object.keys(t).forEach(r=>{let o=t[r];o&&n.push(`${o} ${Dn(o,Fy[r],`${Fy[r]}s`)}`)}),`Worked on ${Id(n)}`}function Td(e,t){let n=t.length,r=Ny(t);switch(e){case"explore":{let o=t.filter(s=>W(s.tool)==="read").length;return o===n?`Read ${n} ${Dn(n,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(t.map(i=>Re(be(i))).filter(Boolean)).size||n,s=t.every(i=>W(i.tool)==="write")?"Wrote":"Updated";return o===1?r?`${s} ${r}`:`${s} a file`:`${s} ${o} files`}case"run":return n===1?"Ran a command":`Ran ${n} commands`;case"web":{let o=l=>{let p=W(l.tool);return p==="web_search"||p==="websearch"||p==="image_search"},s=t.filter(o).length;if(s===n)return`Searched the web \xB7 ${n} ${Dn(n,"query","queries")}`;if(s===0)return`Read ${n} ${Dn(n,"page","pages")}`;let i=new Set;for(let l of t)if(o(l)){let p=l.state?.output;for(let d of Rd(p).flatMap(g=>g.sources))d.url&&i.add(d.url)}else{let p=l.state?.input?.url;typeof p=="string"&&p&&i.add(p)}let a=i.size||n;return`Searched and read ${a} ${Dn(a,"source","sources")}`}case"create":{if(n===1){let s=t[0],i=W(s.tool);if(i==="image_gen")return HR(s);if(i==="video_gen")return"Made a video";if(i==="presentation_gen")return VR(s);let a=BR(s);return a?`Showed you ${a}`:"Showed you the result"}let o=t.map(XR);return Ot(o)?eI[o[0]](n):tI(o)}case"plan":return n===1?"Planned the work":`Planned the work \xB7 ${n} steps`;case"delegate":{let o=t.map(OR);if(Ot(o))switch(o[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 o=t.map(NR);if(Ot(o))switch(o[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 o=t.map($R);if(Ot(o))switch(o[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 o=t.map(jR);if(Ot(o))switch(o[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 o=t.map(LR);if(Ot(o))switch(o[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 ${$n(t[0].tool)}`;let o=Array.from(new Set(t.map(s=>$n(s.tool))));return o.length===1?`Used ${o[0]} \xB7 ${n} times`:`Used ${Id(o)}`}}}function Cd(e,t){let n=Ny(t);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(t.length===1){let r=W(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"),o=r.length?r:t,s=Array.from(new Set(o.map(i=>$n(i.tool))));return`Couldn't finish using ${Id(s)}`}}}function nI(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function rI(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let o=r.state.time;typeof o?.start=="number"&&(t=Math.min(t,o.start)),typeof o?.end=="number"&&(n=Math.max(n,o.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function Ky(e,t){let n=nI(t);return{id:t[0].callID,family:e,label:n==="error"?Cd(e,t):Td(e,t),parts:t,status:n,durationMs:n==="running"?void 0:rI(t)}}function Ed(e){let t=[],n=null,r=[],o=()=>{n&&r.length&&t.push(Ky(n,r)),n=null,r=[]};for(let s of e){let i=go(s.tool);if(i!=="hidden"&&!Sr(s)){if(_p(s.tool)){o(),t.push(Ky(i,[s]));continue}i!==n&&(o(),n=i),r.push(s)}}return o(),t}function qy(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function oI(e,t){let n=[],r=null,o=[],s=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:l}=r,p=typeof a=="number"&&typeof l=="number"&&l>a?l-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(o.length!==0){for(let a of Ed(o))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});o=[]}};for(let a of e)if(t(a)!=="plumbing"){if(he(a)){let l=a.text?.trim();if(!l)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(l);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=qy(a);continue}if(s(),Y(a)){o.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}s(),i();for(let a=0;a<n.length-1;a++){let l=n[a];l.kind==="thought"&&(l.running=!1)}return n}var sI=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function iI(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 aI(e){let t=e.flatMap(o=>{let s=iI(o);return s?[s]:[]}).join(" ").trim();return t?sI.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function Vy(e){return e?.info?.time??{}}function cI(e){let t=Vy(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var mo=6e4,lI=10080*mo,Gy=1440;function By(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 uI(e,t){let n=t.getTime()-e.getTime(),r=n/mo,o=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return o(Math.round(r),"minute");if(r<Gy)return o(Math.round(r/60),"hour");let s=(n-(By(t)-By(e)))/mo;return o(Math.round(s/Gy),"day")}function zy(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 Wy=new Map;function pI(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,o=Wy.get(r);return o||(o=new Intl.DateTimeFormat(t.locale,n),Wy.set(r,o)),o}function fo(e,t,n){return pI(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?dI(r.value,n):r.value).join("")}function dI(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function Hy(e,t){return fo(e,{year:"numeric"},t)}function gI(e,t,n={}){let r=zy(e);if(!r)return"";let o=i=>fo(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return o(!0);let s=Math.max(0,t-r.getTime());return s<mo?"just now":s<lI?uI(r,new Date(t)):o(Hy(r,n)!==Hy(new Date(t),n))}function mI(e,t={}){let n=zy(e);if(!n)return"";let r=fo(n,{month:"long",day:"numeric",year:"numeric"},t),o=fo(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${o}`}function fI(e,t={}){let n=[],r=[],o=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let s of e)if(!Pp(s)){if(ye(s)){o(),n.push({kind:"text",part:s});continue}if(Y(s)&&(xp(s.tool)||!!t.standaloneCallIds?.has(s.callID))){o(),n.push({kind:"standalone",part:s});continue}r.push(s)}return o(),n}function yI(e){let t=ae(e);return t==="show"||t==="show_user"}function hI(e,t={}){let n=[],r=[],o=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(s=>s.part)}),r=[]};for(let s of e){if(s.kind==="standalone"&&yI(s.part.tool)&&!t.standaloneCallIds?.has(s.part.callID)){r.push(s);continue}o(),n.push(s)}return o(),n}var bI=["title","description","path","url","content","language","aspect_ratio","attachment"];function Yy(e,t){if(!t||typeof t!="object")return null;let n=t;if(pn(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let o of bI){let s=n[o];typeof s=="string"&&s&&(r[o]=s)}return r}function _I(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 PI(e){let t=[];for(let n of e){let r=n.state,o=r.input??{};if(r.status==="error"){let a=typeof o.title=="string"&&o.title?o.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let s=_I(o.items),i=s?s.map(a=>Yy(n.callID,a)).filter(a=>!!a):[Yy(n.callID,o)].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 Md(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var xI=e=>e.time?.completed;function SI(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function wI(e,t){let n=e.userMessage.info.id;return t.pendingTurnIds.has(n)||e.assistantMessages.length===0&&t.pendingPromptIds.has(n)}function vI(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=>wI(r,e));return n<=0?null:e.turns[n-1].userMessage.info.id}function AI(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function kI(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Md({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function RI(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 II(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),o=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(l=>l.userMessage.info.id)}),s=e.hintMessageId??null;if(s){if(n>=0&&t[n].userMessage.info.id===s)return o(n);let a=r.indexOf(s);if(a>=0)return o(n+1+a)}if(n>=0){let a=t[n],l=a.assistantMessages[a.assistantMessages.length-1];if(!xI(l.info)&&!l.info.error)return o(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 o(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:o(n)}function Qy(e){let t=e.userMessage.parts;if(t.length===0||!t.every(s=>ye(s)&&s.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let o=r[0];return Y(o)&&o.tool==="bash"}function TI(e){if(Qy(e))return e.assistantMessages[0].parts[0]}function CI(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 EI(e,t){return!t||!e?!1:e.type!=="idle"}function MI(e,t){return!e&&!!t}function OI(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ue(n.error)?.message||le(n.error)}}function jI(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ld(n.error)}}function DI(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ue(n.error)}}function Od(e){if(e){if(Y(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(he(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(ye(e))return"Gathering thoughts..."}}function $I(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,o=Y(r)?r:void 0;if(o&&(o.tool==="task"||o.tool==="agent_task"||o.tool==="agent-task"||o.tool==="task_create"||o.tool==="task-create"||o.tool==="task_start"||o.tool==="task-start")&&o.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 l=a.parts.length-1;l>=0;l--){let p=Od(a.parts[l]);if(p)return p}}return"Handing off to an agent..."}let s=Od(r);if(s)return s}return"Figuring out what\u2019s next..."}function UI(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}var jd=1.2;function Xy(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),o=e.cache?.read??0,s=e.cache?.write??0,i=Math.max(0,n-o-s),l=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*l.inputPer1M;return p+=r/1e6*l.outputPer1M,o>0&&(p+=o/1e6*(l.cacheReadPer1M??l.inputPer1M)),s>0&&(p+=s/1e6*(l.cacheWritePer1M??l.inputPer1M)),p}function Dd(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function Jy(e,t,n,r){if(Dd(t,n))return 0;let o=e.cost||0;if(o>0)return o;if(!r||!t||!n)return 0;let s=r(t,n);return s?Xy(e.tokens,s):0}function Zy(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function LI(e,t){let n=0,r=0,o=0,s=0,i=0,a=0,l=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){l=!0;let g=p,{providerID:m,modelID:f}=Zy(d.info);n+=Jy(g,m,f,t),r+=g.tokens?.input||0,o+=g.tokens?.output||0,s+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!l){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=eh(g,t),f=g.tokens&&Dd(g.providerID,g.modelID);if(m<=0&&!f)continue;l=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,o+=h.output??0,s+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(l)return{cost:n*jd,tokens:{input:r,output:o,reasoning:s,cacheRead:i,cacheWrite:a}}}function eh(e,t){if(Dd(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?Xy({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function FI(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let o=r.info,{providerID:s,modelID:i}=Zy(o),a=0,l=!1;for(let p of r.parts)p.type==="step-finish"&&(l=!0,a+=Jy(p,s,i,t));l||(a+=eh(o,t)),n+=a}return n*jd}function NI(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function KI(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function qI(e){if(!e||e.type!=="retry")return;let t=e,n=le(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:ue(t.message)}}function GI(e){if(!(!e||e.type!=="retry"))return le(e.message)}function BI(e){return(e.info.summary?.diffs?.length??0)>0}function WI(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=iy(t,"kortix_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 HI(e){return e?e.split(`
81
+ `)}var Iy=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),mR={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 fR(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Rn(t)||t}function yR(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim())return fR(r,o.trim())}}function wd(e){if(ye(e))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!Y(e))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let t=ae(e.tool),n=mR[t],r=e.state?.input;return n?{verb:n.verb,running:n.running,object:yR(r,n.objectKeys),tier:Iy.has(t)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:t,tier:"primary"}}function hR(e){let t=0,n=0,r=!1,o=!1;for(let s of e){if(wd(s).tier==="plumbing"){r=!0;continue}if(ye(s)){if(!s.text?.trim())continue;o||(o=!0,t+=1);continue}o=!1,t+=1,Y(s)&&Sd(s)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function vd(e){return`${e} ${e===1?"step":"steps"}`}function bR(e,t){let{total:n,failed:r,completed:o,hasPlumbing:s}=e;return t?n===0?"Working":`Working \xB7 ${vd(n)}`:n===0?s?"Housekeeping":"Worked":r===0?`Completed ${vd(n)}`:o===0?`${vd(n)} failed`:`Completed ${o} of ${n} steps \xB7 ${r} failed`}function _R(e){let t=!1,n=!1,r=!1,o=null,s=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),o==null&&d.error!=null&&(o=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&&s(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)s(p.info),i(p.parts);return c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:o}}function PR(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function xR(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 SR(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=cy(n),n=ly(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 wR(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 o=r.error.trim(),s;for(let i=0;i<3;i++){let a=Cn(o);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(s=c.status),typeof c.message=="string"&&c.message.trim())o=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())o=c.error.trim();else break}return{message:o,status:s}}function On(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function lo(e,t=30){if(!e)return[];let n=[],r=new Set,o=(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}))},s=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=s.exec(e))!==null;)if(o(On(i[1]),On(i[2]),i[3]?On(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(o(On(i[2]),On(i[1])),n.length>=t)return n}return n}function Ty(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 uo(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 Ad(e){if(!e)return[];let t=Ty(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 o of t.results)typeof o.query=="string"&&r.push({query:o.query,answer:o.answer||void 0,sources:Array.isArray(o.results)?uo(o.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=uo(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)?uo(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=uo(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let o of n){let s=o.match(/^Title:\s*(.+)/m),i=o.match(/^URL:\s*(.+)/m),a=o.match(/^Author:\s*(.+)/m),c=o.match(/^Published Date:\s*(.+)/m),p=o.match(/^Text:\s*([\s\S]*?)$/m);s&&i&&r.push({title:s[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=lo(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function po(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function vR(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return po(e)}}function AR(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function kR(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 Cy(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 o=r.trim();/^https?:\/\//i.test(o)&&n.push(o)}return n}return[]}function Ey(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let o=uy(n,r)?.trim()||n;return{url:r,success:!1,error:o}})}function RR(e,t){let n=My(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?Ey(r,Cy(t)):[]}function My(e){if(!e)return null;let t=Ty(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=lo(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 IR(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 TR={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 go(e){return TR[ne(e)]}function Dn(e){let t=W(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var CR={run:"Terminal",memory:"Memory"};function ER(e){let t=go(e);return(t==="hidden"?void 0:CR[t])??Dn(e)}function jn(e,t,n){return e===1?t:n}function kd(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 Dy(e){return e.length?ro(e[0]):""}function he(e){return(e.state??{}).input??{}}var MR={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 OR(e){let t=W(e.tool);if(t==="agent_task_update"||t==="task_update")switch(he(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return MR[t]??"message"}function Oy(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 jR(e){let t=W(e.tool);if(t==="triggers"){let r=he(e).action||"list";return Oy(r)}let n=t.match(/^trigger_(.+)$/);return Oy(n?n[1]:"list")}var DR={connector_setup:"connect",connector_get:"read",connector_list:"read",kortix_connector_discover:"read",kortix_connector_describe:"read",kortix_connectors:"read",kortix_connectors_connectors:"read",kortix_connectors_discover:"read",kortix_connectors_describe:"read",kortix_connector_call:"call",kortix_connectors_call:"call"};function $R(e){return DR[W(e.tool)]??"read"}var UR={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function LR(e){return UR[W(e.tool)]??"open"}function Et(e){return e.every(t=>t===e[0])}var FR={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function NR(e){if(W(e.tool)!=="memory")return"read";let n=he(e).command;return n&&FR[n]||"unknown"}var KR={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},qR={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 GR(e){let t=Re(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function BR(e){let t=he(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 WR(r,60);let o=typeof t.path=="string"?t.path:"";if(o)return GR(o);let s=typeof t.url=="string"?t.url:"";if(s){let i=IR(s);return i?po(i):"a link"}return""}function WR(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function HR(e){let t=he(e).action;return t&&KR[t]||"Worked on an image"}function VR(e){let t=he(e).action;return t&&qR[t]||"Worked on a presentation"}function zR(e){return e.slice(0,e.indexOf(":"))}var YR={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},QR={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 XR(e){let t=W(e.tool);if(t==="image_gen"){let n=he(e).action;return n&&YR[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=he(e).action;return n&&QR[n]||"presentation:unknown"}return"shown:result"}var JR=new Set(["create_slide","export_pdf","export_pptx"]);function ZR(e){let t=W(e.tool);if(t==="image_gen")return"image";if(t==="video_gen")return"video";if(t==="presentation_gen"){let n=he(e).action;return n?JR.has(n)?"presentation":null:"presentation"}return null}var eI={"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`},jy={image:"image",video:"video",presentation:"presentation",shown:"result"};function tI(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[zR(r)]++;let n=[];return Object.keys(t).forEach(r=>{let o=t[r];o&&n.push(`${o} ${jn(o,jy[r],`${jy[r]}s`)}`)}),`Worked on ${kd(n)}`}function Rd(e,t){let n=t.length,r=Dy(t);switch(e){case"explore":{let o=t.filter(s=>W(s.tool)==="read").length;return o===n?`Read ${n} ${jn(n,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(t.map(i=>ke(he(i))).filter(Boolean)).size||n,s=t.every(i=>W(i.tool)==="write")?"Wrote":"Updated";return o===1?r?`${s} ${r}`:`${s} a file`:`${s} ${o} files`}case"run":return n===1?"Ran a command":`Ran ${n} commands`;case"web":{let o=c=>{let p=W(c.tool);return p==="web_search"||p==="websearch"||p==="image_search"},s=t.filter(o).length;if(s===n)return`Searched the web \xB7 ${n} ${jn(n,"query","queries")}`;if(s===0)return`Read ${n} ${jn(n,"page","pages")}`;let i=new Set;for(let c of t)if(o(c)){let p=c.state?.output;for(let d of Ad(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} ${jn(a,"source","sources")}`}case"create":{if(n===1){let s=t[0],i=W(s.tool);if(i==="image_gen")return HR(s);if(i==="video_gen")return"Made a video";if(i==="presentation_gen")return VR(s);let a=BR(s);return a?`Showed you ${a}`:"Showed you the result"}let o=t.map(XR);return Et(o)?eI[o[0]](n):tI(o)}case"plan":return n===1?"Planned the work":`Planned the work \xB7 ${n} steps`;case"delegate":{let o=t.map(OR);if(Et(o))switch(o[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 o=t.map(NR);if(Et(o))switch(o[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 o=t.map($R);if(Et(o))switch(o[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 o=t.map(jR);if(Et(o))switch(o[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 o=t.map(LR);if(Et(o))switch(o[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 ${Dn(t[0].tool)}`;let o=Array.from(new Set(t.map(s=>Dn(s.tool))));return o.length===1?`Used ${o[0]} \xB7 ${n} times`:`Used ${kd(o)}`}}}function Id(e,t){let n=Dy(t);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(t.length===1){let r=W(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"),o=r.length?r:t,s=Array.from(new Set(o.map(i=>Dn(i.tool))));return`Couldn't finish using ${kd(s)}`}}}function nI(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function rI(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let o=r.state.time;typeof o?.start=="number"&&(t=Math.min(t,o.start)),typeof o?.end=="number"&&(n=Math.max(n,o.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function $y(e,t){let n=nI(t);return{id:t[0].callID,family:e,label:n==="error"?Id(e,t):Rd(e,t),parts:t,status:n,durationMs:n==="running"?void 0:rI(t)}}function Td(e){let t=[],n=null,r=[],o=()=>{n&&r.length&&t.push($y(n,r)),n=null,r=[]};for(let s of e){let i=go(s.tool);if(i!=="hidden"&&!Sr(s)){if(hp(s.tool)){o(),t.push($y(i,[s]));continue}i!==n&&(o(),n=i),r.push(s)}}return o(),t}function Uy(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function oI(e,t){let n=[],r=null,o=[],s=()=>{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(o.length!==0){for(let a of Td(o))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});o=[]}};for(let a of e)if(t(a)!=="plumbing"){if(ye(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=Uy(a);continue}if(s(),Y(a)){o.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}s(),i();for(let a=0;a<n.length-1;a++){let c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var sI=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function iI(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 aI(e){let t=e.flatMap(o=>{let s=iI(o);return s?[s]:[]}).join(" ").trim();return t?sI.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function qy(e){return e?.info?.time??{}}function cI(e){let t=qy(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var mo=6e4,lI=10080*mo,Ly=1440;function Fy(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 uI(e,t){let n=t.getTime()-e.getTime(),r=n/mo,o=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return o(Math.round(r),"minute");if(r<Ly)return o(Math.round(r/60),"hour");let s=(n-(Fy(t)-Fy(e)))/mo;return o(Math.round(s/Ly),"day")}function Gy(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 Ny=new Map;function pI(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,o=Ny.get(r);return o||(o=new Intl.DateTimeFormat(t.locale,n),Ny.set(r,o)),o}function fo(e,t,n){return pI(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?dI(r.value,n):r.value).join("")}function dI(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function Ky(e,t){return fo(e,{year:"numeric"},t)}function gI(e,t,n={}){let r=Gy(e);if(!r)return"";let o=i=>fo(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return o(!0);let s=Math.max(0,t-r.getTime());return s<mo?"just now":s<lI?uI(r,new Date(t)):o(Ky(r,n)!==Ky(new Date(t),n))}function mI(e,t={}){let n=Gy(e);if(!n)return"";let r=fo(n,{month:"long",day:"numeric",year:"numeric"},t),o=fo(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${o}`}function fI(e,t={}){let n=[],r=[],o=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let s of e)if(!bp(s)){if(fe(s)){o(),n.push({kind:"text",part:s});continue}if(Y(s)&&(_p(s.tool)||!!t.standaloneCallIds?.has(s.callID))){o(),n.push({kind:"standalone",part:s});continue}r.push(s)}return o(),n}function yI(e){let t=ae(e);return t==="show"||t==="show_user"}function hI(e,t={}){let n=[],r=[],o=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(s=>s.part)}),r=[]};for(let s of e){if(s.kind==="standalone"&&yI(s.part.tool)&&!t.standaloneCallIds?.has(s.part.callID)){r.push(s);continue}o(),n.push(s)}return o(),n}var bI=["title","description","path","url","content","language","aspect_ratio","attachment"];function By(e,t){if(!t||typeof t!="object")return null;let n=t;if(ln(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let o of bI){let s=n[o];typeof s=="string"&&s&&(r[o]=s)}return r}function _I(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 PI(e){let t=[];for(let n of e){let r=n.state,o=r.input??{};if(r.status==="error"){let a=typeof o.title=="string"&&o.title?o.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let s=_I(o.items),i=s?s.map(a=>By(n.callID,a)).filter(a=>!!a):[By(n.callID,o)].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 Cd(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var xI=e=>e.time?.completed;function SI(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function wI(e,t){let n=e.userMessage.info.id;return t.pendingTurnIds.has(n)||e.assistantMessages.length===0&&t.pendingPromptIds.has(n)}function vI(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=>wI(r,e));return n<=0?null:e.turns[n-1].userMessage.info.id}function AI(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function kI(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Cd({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function RI(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 II(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),o=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(c=>c.userMessage.info.id)}),s=e.hintMessageId??null;if(s){if(n>=0&&t[n].userMessage.info.id===s)return o(n);let a=r.indexOf(s);if(a>=0)return o(n+1+a)}if(n>=0){let a=t[n],c=a.assistantMessages[a.assistantMessages.length-1];if(!xI(c.info)&&!c.info.error)return o(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 o(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:o(n)}function Wy(e){let t=e.userMessage.parts;if(t.length===0||!t.every(s=>fe(s)&&s.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let o=r[0];return Y(o)&&o.tool==="bash"}function TI(e){if(Wy(e))return e.assistantMessages[0].parts[0]}function CI(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 EI(e,t){return!t||!e?!1:e.type!=="idle"}function MI(e,t){return!e&&!!t}function OI(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ue(n.error)?.message||ce(n.error)}}function jI(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ad(n.error)}}function DI(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ue(n.error)}}function Ed(e){if(e){if(Y(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(ye(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(fe(e))return"Gathering thoughts..."}}function $I(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,o=Y(r)?r:void 0;if(o&&(o.tool==="task"||o.tool==="agent_task"||o.tool==="agent-task"||o.tool==="task_create"||o.tool==="task-create"||o.tool==="task_start"||o.tool==="task-start")&&o.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=Ed(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let s=Ed(r);if(s)return s}return"Figuring out what\u2019s next..."}function UI(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}var Md=1.2;function Hy(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),o=e.cache?.read??0,s=e.cache?.write??0,i=Math.max(0,n-o-s),c=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*c.inputPer1M;return p+=r/1e6*c.outputPer1M,o>0&&(p+=o/1e6*(c.cacheReadPer1M??c.inputPer1M)),s>0&&(p+=s/1e6*(c.cacheWritePer1M??c.inputPer1M)),p}function Od(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function Vy(e,t,n,r){if(Od(t,n))return 0;let o=e.cost||0;if(o>0)return o;if(!r||!t||!n)return 0;let s=r(t,n);return s?Hy(e.tokens,s):0}function zy(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function LI(e,t){let n=0,r=0,o=0,s=0,i=0,a=0,c=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){c=!0;let g=p,{providerID:m,modelID:f}=zy(d.info);n+=Vy(g,m,f,t),r+=g.tokens?.input||0,o+=g.tokens?.output||0,s+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!c){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=Yy(g,t),f=g.tokens&&Od(g.providerID,g.modelID);if(m<=0&&!f)continue;c=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,o+=h.output??0,s+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(c)return{cost:n*Md,tokens:{input:r,output:o,reasoning:s,cacheRead:i,cacheWrite:a}}}function Yy(e,t){if(Od(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?Hy({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function FI(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let o=r.info,{providerID:s,modelID:i}=zy(o),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=Vy(p,s,i,t));c||(a+=Yy(o,t)),n+=a}return n*Md}function NI(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function KI(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function qI(e){if(!e||e.type!=="retry")return;let t=e,n=ce(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:ue(t.message)}}function GI(e){if(!(!e||e.type!=="retry"))return ce(e.message)}function BI(e){return(e.info.summary?.diffs?.length??0)>0}function WI(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=ty(t,"kortix_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 HI(e){return e?e.split(`
82
82
  `).filter(n=>n.trim()).length<=3:!1}function VI(e){if(!e)return null;let n=e.split(`
83
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 zI(e){if(!e)return[];let t=[],n=e.split(`
84
- `).filter(r=>r.trim());for(let r of n){let o=uy(r);if(o){let s=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...o,sessionId:s?.[0]})}}return t}var Ne={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 YI(e,t){let n=Ne[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function QI(e,t){return t?"failed":e?"running":"done"}var XI={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function JI(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function ZI(e,t){if(!e)return null;let n=e.indexOf(`
85
- `),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1);if(cy(r,"content of "," with line numbers"))return{type:"file",content:o.split(`
84
+ `).filter(r=>r.trim());for(let r of n){let o=sy(r);if(o){let s=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...o,sessionId:s?.[0]})}}return t}var Fe={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 YI(e,t){let n=Fe[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function QI(e,t){return t?"failed":e?"running":"done"}var XI={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function JI(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function ZI(e,t){if(!e)return null;let n=e.indexOf(`
85
+ `),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1);if(ry(r,"content of "," with line numbers"))return{type:"file",content:o.split(`
86
86
  `).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
87
87
  `)};if(/files and directories/i.test(r)){let s=t.replace(/\/$/,""),i=[];for(let a of o.split(`
88
- `)){if(!a.trim())continue;let l=a.indexOf(" ");if(l===-1)continue;let p=a.slice(0,l).trim(),d=a.slice(l+1).trim();d!==s&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var eT={add:{...Ne.write,icon:"create"},delete:{...Ne.delete,icon:"delete"},move:{...Ne.rename,icon:"edit"},update:{...Ne.edit,icon:"edit"}},th={...Ne.change,icon:"edit"};function tT(e){if(e.length===0)return th;let t=nh(e[0]);for(let n=1;n<e.length;n++)if(nh(e[n])!==t)return th;return eT[t]}function nh(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function nT(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 rT(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],o;for(;(o=n.exec(e))!==null;)r.push(o[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(s,i)=>r[i]?[r[i]]:[])}function oT(e){if(!e)return null;let t=Cn(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=pd(e,"content");if(r!==null){let s=r.split(`
88
+ `)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==s&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var eT={add:{...Fe.write,icon:"create"},delete:{...Fe.delete,icon:"delete"},move:{...Fe.rename,icon:"edit"},update:{...Fe.edit,icon:"edit"}},Qy={...Fe.change,icon:"edit"};function tT(e){if(e.length===0)return Qy;let t=Xy(e[0]);for(let n=1;n<e.length;n++)if(Xy(e[n])!==t)return Qy;return eT[t]}function Xy(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function nT(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 rT(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],o;for(;(o=n.exec(e))!==null;)r.push(o[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(s,i)=>r[i]?[r[i]]:[])}function oT(e){if(!e)return null;let t=Tn(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=ld(e,"content");if(r!==null){let s=r.split(`
89
89
  `).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
90
- `);return{path:n,type:"file",content:s}}let o=pd(e,"entries");if(o!==null){let s=o.split(`
91
- `).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:s}}return null}function sT(e){let t=sy(e,"skill_content");return t!==null?t.trim():e}function rh(e){let t=Cn(e,"<skill_files>","</skill_files>");return t===null?[]:ay(t,"<file>","</file>").map(n=>n.trim())}function iT(e){let t=oy(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 aT(e){return ly(e,["Base directory","Directory","Skill directory"])?.trim()??""}function oh(e){return Ie(iT(e)||aT(e))}function cT(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Ie(n.trim())}return""}var lT="skills";function uT(e){let t=ry(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(o=>o.trim());if(n.some(o=>o===".."||o==="."))return"";let r=n.at(-1)??"";return r?`${lT}/${r}`:""}function pT(e,t,n){let o=Ie(t?.trim()??"")||oh(e)||uT(n),s=rh(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(s){if(s.startsWith("/"))return s;if(o)return`${o}/${s}`}return o?`${o}/SKILL.md`:null}var dT=4e3;function Un(e,t=dT){return e.length>t?`${e.slice(0,t)}
92
- \u2026`:e}function sh(e){if(e!==void 0)try{return Un(JSON.stringify(e,null,2))}catch{return}}function G(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function nt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function gT(e){let t=G(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=nt(e.outputParsed);if(!n)return{kind:"web-search",query:t};let o=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(s=>{let i=nt(s)??{};return{title:G(i.title)??"",url:G(i.url,i.link)??"",snippet:G(i.snippet,i.description,i.source)}});return{kind:"web-search",query:G(n.query)??t,results:o.length>0?o:void 0,answer:G(n.answer)}}var mT=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Ud(e){let t=e.match(mT);return t?Number(t[1]):void 0}function fT(e,t,n){let r="",o=0;for(;;){let s=e.indexOf(t,o);if(s===-1)return r+e.slice(o);let i=e.indexOf(n,s+t.length);if(i===-1)return r+e.slice(o);r+=e.slice(o,s),o=i+n.length}}var yT=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function hT(e){let t=-1;for(let n of yT){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var bT=/\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 _T(e){return e.replace(bT,"")}function PT(e){let t=G(e.input?.command)??"",n=e.output??"",r=Ud(n),s=_T(hT(fT(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:s||void 0,exitCode:r}}function Ld(e){return G(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function xT(e){let t=e.status==="error"?e.error:e.output&&Un(e.output)||void 0;return{kind:"file-read",path:Ld(e),preview:t}}function ST(e){let t=G(e.input?.content),n=e.status==="error"?e.error:Un(t??e.output??"")||void 0;return{kind:"file-write",path:Ld(e),preview:n}}var wT=256*1024;function vT(e,t){if(e.length+t.length>wT)return;let n=e.split(`
90
+ `);return{path:n,type:"file",content:s}}let o=ld(e,"entries");if(o!==null){let s=o.split(`
91
+ `).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:s}}return null}function sT(e){let t=ey(e,"skill_content");return t!==null?t.trim():e}function Jy(e){let t=Tn(e,"<skill_files>","</skill_files>");return t===null?[]:ny(t,"<file>","</file>").map(n=>n.trim())}function iT(e){let t=Zf(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 aT(e){return oy(e,["Base directory","Directory","Skill directory"])?.trim()??""}function Zy(e){return Re(iT(e)||aT(e))}function cT(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Re(n.trim())}return""}var lT="skills";function uT(e){let t=Jf(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(o=>o.trim());if(n.some(o=>o===".."||o==="."))return"";let r=n.at(-1)??"";return r?`${lT}/${r}`:""}function pT(e,t,n){let o=Re(t?.trim()??"")||Zy(e)||uT(n),s=Jy(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(s){if(s.startsWith("/"))return s;if(o)return`${o}/${s}`}return o?`${o}/SKILL.md`:null}var dT=4e3;function $n(e,t=dT){return e.length>t?`${e.slice(0,t)}
92
+ \u2026`:e}function eh(e){if(e!==void 0)try{return $n(JSON.stringify(e,null,2))}catch{return}}function G(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function gT(e){let t=G(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=et(e.outputParsed);if(!n)return{kind:"web-search",query:t};let o=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(s=>{let i=et(s)??{};return{title:G(i.title)??"",url:G(i.url,i.link)??"",snippet:G(i.snippet,i.description,i.source)}});return{kind:"web-search",query:G(n.query)??t,results:o.length>0?o:void 0,answer:G(n.answer)}}var mT=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Dd(e){let t=e.match(mT);return t?Number(t[1]):void 0}function fT(e,t,n){let r="",o=0;for(;;){let s=e.indexOf(t,o);if(s===-1)return r+e.slice(o);let i=e.indexOf(n,s+t.length);if(i===-1)return r+e.slice(o);r+=e.slice(o,s),o=i+n.length}}var yT=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function hT(e){let t=-1;for(let n of yT){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var bT=/\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 _T(e){return e.replace(bT,"")}function PT(e){let t=G(e.input?.command)??"",n=e.output??"",r=Dd(n),s=_T(hT(fT(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:s||void 0,exitCode:r}}function $d(e){return G(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function xT(e){let t=e.status==="error"?e.error:e.output&&$n(e.output)||void 0;return{kind:"file-read",path:$d(e),preview:t}}function ST(e){let t=G(e.input?.content),n=e.status==="error"?e.error:$n(t??e.output??"")||void 0;return{kind:"file-write",path:$d(e),preview:n}}var wT=256*1024;function vT(e,t){if(e.length+t.length>wT)return;let n=e.split(`
93
93
  `),r=t.split(`
94
- `),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length,i=r.length;for(;s>o&&i>o&&n[s-1]===r[i-1];)s--,i--;let a=[];for(let l=0;l<o;l++)a.push({type:"unchanged",text:n[l]});for(let l=o;l<s;l++)a.push({type:"removed",text:n[l]});for(let l=o;l<i;l++)a.push({type:"added",text:r[l]});for(let l=s;l<n.length;l++)a.push({type:"unchanged",text:n[l]});return a}function AT(e){let t=G(e?.oldString),n=G(e?.newString);return t!==void 0&&n!==void 0?[[t,n]]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(o=>{let s=nt(o),i=s&&G(s.oldText),a=s&&G(s.newText);return i!==void 0&&a!==void 0?[[i,a]]:[]})}function kT(e){let t=AT(e.input),n=t.map(([o,s])=>vT(o,s)),r=t.length&&n.every(Boolean)?n.flatMap(o=>o??[]):void 0;return{kind:"file-edit",path:Ld(e),diff:r}}var ah=/^Found\s+(\d+)\s+match/i,RT=/^(\/[^:]+?):\s*/,ih=/Line\s+(\d+):/g;function IT(e){let t=e.trim(),n=t.match(ah),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let o=[];for(let s of r.split(/\n\n+/)){let i=s.trim();if(!i)continue;let a=i.match(RT);if(!a)continue;let l=a[1],p=i.slice(a[0].length),d=[],g;for(ih.lastIndex=0;(g=ih.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();o.push({path:l,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return o}function TT(e){return e.trim().split(`
95
- `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function CT(e){let t=G(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=ah.test(e.output.trim())?IT(e.output):TT(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function ET(e){let t=G(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=G(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function $d(e){let t=nt(e)??{};return{content:G(t.content)??"",status:G(t.status)??"pending",priority:G(t.priority)}}function MT(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map($d)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map($d)};let n=nt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map($d)}:{kind:"todo",items:[]}}function OT(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let o=nt(r)??{},i=(Array.isArray(o.options)?o.options:[]).flatMap(a=>{let l=nt(a),p=l&&G(l.label);return p?[{label:p,description:l?G(l.description):void 0}]:[]});return{question:G(o.question)??"",header:G(o.header),options:i}})}}function jT(e){let n=e.input&&Object.keys(e.input).length>0?sh(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Un(e.outputParsed):sh(e.outputParsed):e.outputText!==void 0?r=Un(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function ch(e){switch(ne(e.name)){case"web_search":return gT(e);case"bash":return PT(e);case"read":return xT(e);case"write":return ST(e);case"edit":return kT(e);case"grep":case"glob":return CT(e);case"task":return ET(e);case"todowrite":return MT(e);case"question":return OT(e);default:return jT(e)}}var DT=new Set(["AbortError","MessageAbortedError"]),$T=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],UT=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function lh(e){let t=e.toLowerCase();return UT.some(n=>t.includes(n))?!1:$T.some(n=>t.includes(n))}function LT(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 Ln(e){if(typeof e=="string")return lh(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&DT.has(n))return!0;let r=LT(t);return typeof r=="string"?lh(r):!1}var uh=["user","runtime-disposed","orphan-finalized","wake"],FT=["orphan-finalized","wake"];function NT(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 uh.includes(n)?n:void 0}var Fn="kortix-active-instance",ph=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function dh(e){return ph.some(t=>e===t||e.startsWith(`${t}/`))}function jt(e){let t=e.match(/^\/instances\/([^/]+)(?:\/(.*))?$/);if(!t)return null;let n=decodeURIComponent(t[1]),r=t[2]??"";return{instanceId:n,innerPath:r?`/${r}`:""}}function KT(e){let t=jt(e);return!!t&&t.innerPath===""}function qT(e){let t=jt(e);return!t||!t.innerPath?e:t.innerPath}function gh(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=jt(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return dh(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function mh(e){return e?jt(e)?.instanceId??null:null}function GT(){return typeof window>"u"?null:mh(window.location.pathname)||fh()}function fh(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Fn}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function BT(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Fn}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Fn}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Fn}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function WT(e,t){return t?gh(t,e):e}function HT(e){let t=jt(e);return t?t.innerPath||"/dashboard":e}function Kn(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 Fd(e){let t=Kn(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 o of n)if(o)try{return JSON.parse(o)}catch{}return null}var VT=Fd;function yo(e){let t=Fd(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var zT=yo;function yh(e){return yo(e)!==null}var YT=yh,QT=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],XT=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],JT=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function hh(e){return JT.test(Kn(e))}function Dt(e){let t=Kn(e);return t?hh(t)||QT.some(n=>n.test(t)):!1}var ZT=/server url not ready|sandbox is still loading/i;function eC(e){return ZT.test(Kn(e))||Dt(e)}var Nn=class extends Error{constructor(t){let n=t?.trim();super(n&&Dt(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function bh(e){let t=yo(e);if(t){let o=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),s=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:`${o} is preventing OpenCode from loading. ${a}`,detail:s?`${i?`${i}: `:""}${s}`:void 0}}let n=Kn(e);return Dt(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 tC=bh;function Nd(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`${me()}/p/${e.external_id}/${ve.KORTIX_MASTER}`}function nC(e,t){return e.external_id?`${me()}/p/${e.external_id}/${t}`:null}async function rC(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function _h(e){let t=await ze();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Be())[0];if(!r)throw new Error("Create a project before starting a sandbox");let o=await He(r.project_id,{...e?.provider?{provider:e.provider}:{}}),s=(await Oe(r.project_id,o.session_id))?.sandbox??null;return{sandbox:Tp(r,o,s),created:!0}}async function oC(){return(await ze().catch(()=>null))?.sandbox??null}async function sC(e){return{sandbox:(await _h(e)).sandbox}}async function iC(e){let t=gn(e);return t?(await ze(t).catch(()=>null))?.sandbox??null:null}async function aC(e,t){throw await ze(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function cC(e){let t=gn(e);return(await Cp().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function lC(){if(typeof window>"u")return null;let e=me(),t=Array.from(new Set([e,...cm]));for(let n of t)try{let r=await fetch(lm(n),{method:"GET",signal:AbortSignal.timeout(1500),headers:{Accept:"application/json"}});if(!r.ok)continue;let o=await r.json();if(!o.success||o.status!=="ready"||!o.data?.sandbox_id)continue;return o.data}catch{continue}return null}async function uC(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await ze(e);if(!t)throw new Error("Project session sandbox not found");await on(t.project.project_id,t.session.session_id)}async function pC(e){if(!e)throw new Error("No sandbox selected to stop");let t=await ze(e);if(!t)throw new Error("Project session sandbox not found");await sn(t.project.project_id,t.session.session_id)}async function dC(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function gC(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function Kd(e,t,n){let r=Nd(e),o=await j(`${ce(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`Request failed (${o.status})`)}return await o.json()}async function mC(e,t){return Kd(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function fC(e,t,n,r="member"){await Kd(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function yC(e,t,n){await Kd(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var qd="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function hC(e){throw q("getInvite",qd)}async function bC(e){throw q("acceptInvite",qd)}async function _C(e){throw q("declineInvite",qd)}async function PC(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function xC(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function SC(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function wC(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function vC(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function AC(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var Ph=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function kC(e){return Ph.includes(e)}async function RC(e){return{phase:"idle",progress:0,message:"Sandbox image updates are managed by project-session provisioning.",targetVersion:null,previousVersion:null,currentVersion:e?.version??null,error:null,startedAt:null,updatedAt:null}}async function IC(e){let t=e?`?channel=${e}`:"",n=await fetch(`${me()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Version check failed: ${n.status}`);let r=await n.json();try{let o=await xh(e||"stable");r.changelog=o.find(s=>s.version===r.version)??o[0]??null}catch{r.changelog=null}return r}async function xh(e){let t=e?`?channel=${e}`:"",n=await fetch(`${me()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Changelog fetch failed: ${n.status}`);return(await n.json()).changelog}async function TC(){let e=await fetch(`${me()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`All versions fetch failed: ${e.status}`);return e.json()}async function CC(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function EC(e){}async function MC(e){}async function OC(e){return{serverTypes:[],location:e||"hel1"}}async function jC(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function DC(e){throw q("deleteInstance")}async function $C(e,t){}async function UC(){throw q("claimComputer")}async function LC(e){return null}function FC(e,t){throw q("getSandboxProvisionStreamUrl")}var Te=class extends Error{constructor(n,r,o){super(n);this.status=r;this.body=o;this.name="HostBoundaryError"}status;body};function Gd(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 ho(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function bo(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 H(e,t,n){let r=n?.body!==void 0,o=await fetch(`${Ve(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:Gd(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),s=await ho(o);if(!o.ok)throw new Te(bo(o,s),o.status,s);return s}function NC(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 KC(e,t){return H(`/marketplace/items${NC(t)}`,e)}function qC(e){return H("/marketplace/marketplaces",e)}function GC(e,t){return H(`/marketplace/items/${encodeURIComponent(e)}`,t)}function BC(e,t,n){return H(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function WC(e,t){return H("/access/check-email",t,{method:"POST",body:{email:e}})}function HC(e,t){return H("/access/request-access",t,{method:"POST",body:e})}function VC(e){return H("/auth/logout",e,{method:"POST",body:{}})}function zC(e,t){return H(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function YC(e,t){return H("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function QC(e,t){return H(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function XC(e,t){return H(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function JC(e,t,n={}){return H(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function ZC(e,t){return H(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function eE(e,t,n,r){return H(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function tE(e,t){return H(`/p/public-share/${encodeURIComponent(e)}`,t)}function nE(e,t,n){return H(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function rE(e){return H("/system/maintenance",e)}function oE(e,t){return H("/system/maintenance",t,{method:"PUT",body:e})}function sE(e){return H("/user-roles",e)}function iE(e,t){return H("/system/demo-request",t,{method:"POST",body:e})}async function aE(e,t,n){let r=await fetch(`${Ve(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${dt(t)}`,{headers:Gd(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let o=await ho(r);throw new Te(bo(r,o),r.status,o)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function cE(e,t){let n=await fetch(`${Ve(t.backendUrl)}/admin/stress-test/run`,{method:"POST",headers:Gd(t,!0),body:JSON.stringify(e),...t.signal?{signal:t.signal}:{}});if(!n.ok){let r=await ho(n);throw new Te(bo(n,r),n.status,r)}if(!n.body)throw new Te("No response body",n.status,null);return n.body}var lE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Sh(e,t){return lE.test(t)?new URL(`templates/public/${t.toLowerCase()}`,`${Ve(e)}/`):null}async function uE(e,t,n){let r=Sh(e,t);if(!r)throw new Te("Invalid shareId parameter",400,null);let o=await fetch(r,{signal:n}),s=await ho(o);if(!o.ok)throw new Te(bo(o,s),o.status,s);return s}async function pE(){let e=await c.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function dE(e={}){let t=await c.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function gE(e){let t=await c.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function mE(e){let t=await c.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function fE(){let e=await c.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var NK="1";var yE="kortix.query-cache";function vh(e){return!!e&&typeof e.then=="function"}function wh(e){return vh(e)?e:Promise.resolve()}function hE(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 bE(e){let{storage:t,userId:n,shouldPersist:r,version:o="1",maxAgeMs:s=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:l=yE,now:p=()=>Date.now()}=e,d=`${l}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),w=()=>{try{return wh(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},L=(x,_)=>{if(!_)return 0;let A;try{A=JSON.parse(_)}catch{return w(),0}if(!A||A.v!==o||A.user!==n||!Array.isArray(A.queries)||p()-A.at>s)return w(),0;let T=0;for(let C of A.queries){if(!C||!Array.isArray(C.k)||C.d===void 0||typeof C.t!="number"||p()-C.t>s||!r(C.k))continue;let E=x.getQueryState(C.k);E&&E.data!==void 0&&E.dataUpdatedAt>=C.t||(x.setQueryData(C.k,C.d,{updatedAt:C.t}),x.invalidateQueries?.({queryKey:C.k,exact:!0,refetchType:"none"}),T+=1)}return T},O=x=>x.getQueryCache().getAll().filter(_=>_.state.data!==void 0&&r(_.queryKey)).map(_=>({k:_.queryKey,d:_.state.data,t:_.state.dataUpdatedAt})).sort((_,A)=>A.t-_.t),D=(x,_)=>{let A=[],T=0;for(let C of x){let E=JSON.stringify(C).length+1;T+E>_||(A.push(C),T+=E)}return A},y=async x=>{let _=D(O(x),i);for(;;){let A={v:o,user:n,at:p(),queries:_};try{await wh(t.setItem(d,JSON.stringify(A)));return}catch{if(_.length===0)return;_=_.slice(0,Math.floor(_.length/2))}}},P=()=>{f!==null&&(clearTimeout(f),f=null)},v=()=>{P();let x=g;return!x||!m||(m=!1,h=h.then(()=>y(x)).catch(()=>{})),h},$=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,v()},a))};return{storageKey:d,restore(x){let _;try{_=t.getItem(d)}catch{return 0}return vh(_)?_.then(A=>L(x,A)).catch(()=>0):L(x,_)},persist(x){g=x,m=!0;let _=x.getQueryCache().subscribe(A=>{A.type!=="updated"&&A.type!=="removed"&&A.type!=="added"||r(A.query.queryKey)&&$()});return()=>{_(),g===x&&(g=null,P())}},flush(){return v()},async clear(){P(),g=null,m=!1,await h,await w()}}}function _E(){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 Ah="/kortix/part/";function kh(e){return typeof e=="string"&&e.startsWith(Ah)}async function PE(e){if(!kh(e))throw new Error(`not an attachment part reference: ${e}`);let t=ke();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 Rh(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 xE(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let s=new Set;if(t)try{s.add(new URL(t).origin)}catch{}return typeof window<"u"&&s.add(window.location.origin),s.has(n.origin)}catch{return!1}}function Bd(e,t){return xE(e,t)?(t?Rh(t):null)??Rh(e):null}function qn(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 Wd(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var SE=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function wE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vE(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 o=(t.slice(n+3).split("/")[0]??"").toLowerCase(),s=`${r}://${o}`.split("{port}").map(i=>i.split("{sandbox}").map(wE).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${s}$`).test(e)}function AE(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function Ih(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function kE(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:SE.test(n.hostname)?t.backendUrls.some(r=>{let o=AE(r);return o!==null&&Ih(o)===Ih(n)}):t.templates.some(r=>vE(n.origin,r))}async function Th(e,t={}){if(!qn(e))return!1;let n=k().backendUrl;n&&await yt(n).catch(()=>null);let r=[n,t.serverUrl].filter(o=>typeof o=="string"&&o.length>0);return kE(e,{templates:mm(),backendUrls:r})}async function Ch(e,t={}){let n=Bd(e,t.serverUrl||k().backendUrl||void 0);if(!n)return!1;let r=await lt();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 RE(e,t={}){if(qn(e)){if(!await Th(e,t))return e;let n=await lt();return n?Wd(e,n):e}return await Ch(e,t),e}var IE=3e3;function Eh(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 TE(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let o=setTimeout(r,t?.timeoutMs??3e3);try{let s=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return Eh(s.status)}catch{return"unknown"}finally{clearTimeout(o),t?.signal?.removeEventListener("abort",r)}}function Hd(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function CE(e,t){return`${Hd(e)}/presentation-templates/${encodeURIComponent(t)}/pdf#toolbar=0&navpanes=0&scrollbar=0&view=FitH`}function EE(e,t){return`${Hd(e)}/presentation-templates/${encodeURIComponent(t)}/image.png`}function Mh(e,t){return`${Hd(e)}/presentation/convert-to-${t}`}async function ME(e,t,n,r){let o=Mh(t,e),s=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),l=!1;for(;;){let p=await fetch(o,{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(l||(l=!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 L=setTimeout(h,s);r?.signal?.addEventListener("abort",()=>{clearTimeout(L),w(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 OE(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 jE(e){return e==="unreachable"}function DE(e){return!e||e.status===0?"unknown":e.ok&&ed(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var Oh=1e4,$E={connection:"unknown",faultSinceMs:null};function UE(e,t,n,r=Oh){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let o=e.faultSinceMs??n;return n-o>=r?{connection:t,faultSinceMs:o}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:o}}function jh({optimistic:e,abort:t,inbox:n,server:r,stream:o,activity:s,nowMs:i}){let a=!!e&&i-e.atMs<_o,l=!!t&&i-t.atMs<So;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:l,abortFloor:l?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=Po,streamFresh:!!o&&i-o.atMs<=$t,inboxFresh:!!n&&i-n.atMs<=xo,activityFresh:!!s&&i-s.atMs<=$t}}function Ut(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Vd(e,t,n){if(!t)return!1;let r=Ut(e.started_at);if(r===null||r>=t.atMs)return!1;let o=n?.lastEnded,s=Ut(o?.ended_at);return!(o&&s!==null&&Math.abs(s-t.atMs)<=1e3&&o.turn_token!==e.turn_token)}function LE(e,t,n,r){let{activity:o,server:s}=e,{serverFresh:i,abortFloor:a,activityFresh:l}=t;return l&&(!n||o.atMs>n.atMs)&&o.atMs>=a?{state:"working",source:"stream",turnId:i?s.turns.find(d=>d.state==="active"&&!Vd(d,n,s))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:r}:null}function FE(e,t,n,r){let{server:o,stream:s}=e,{serverFresh:i,abortFloor:a}=t,l=i?o.turns.filter(g=>!Vd(g,n,o)):[],p=l.find(g=>g.state==="active")??l[0],d=!!s&&!(s.type==="idle"&&s.origin==="local");return p&&o.atMs>=a&&(!d||o.atMs>=s.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:Ut(p.started_at)??o.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function NE(e,t,n){let{inbox:r,server:o,stream:s}=e,{inboxFresh:i,abortFloor:a,streamFresh:l,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...l&&s.type!=="idle"&&(!p||s.atMs>o.atMs)&&s.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&&o.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function KE(e,t,n,r){let{server:o,stream:s,optimistic:i,nowMs:a}=e,{serverFresh:l,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,w=l&&!n&&o.atMs>=p,L=d&&s.atMs>=g&&(s.type==="idle"||s.atMs>=m);if(w&&(!s||o.atMs>=s.atMs))return{state:"idle",source:"server",turnId:null,since:Ut(o.lastEnded?.ended_at)??o.atMs,serverOpenTurnToken:r};if(L)return{state:s.type==="idle"?"idle":"working",source:"stream",turnId:null,since:s.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let O=o&&s?o.atMs>=s.atMs?{source:"server",atMs:o.atMs}:{source:"stream",atMs:s.atMs}:o?{source:"server",atMs:o.atMs}:s?{source:"stream",atMs:s.atMs}:{source:"server",atMs:a};return{state:"idle",source:O.source,turnId:null,since:O.atMs,serverOpenTurnToken:r}}function Dh(e){let t=jh(e),{server:n,stream:r}=e,o=r&&r.type==="idle"&&r.origin!=="local"?r:null,s=n?.turns[0]?.turn_token??null,i=LE(e,t,o,s);if(i)return i;let{result:a,openTurn:l}=FE(e,t,o,s);return a??NE(e,t,s)??KE(e,t,l,s)}var _o=6e4,Po=45e3,$t=45e3,xo=1e4,qE=3e3,So=15e3;function GE(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function BE(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 WE(e){return Dh(e)}function HE(e){let{optimistic:t,abort:n,inbox:r,server:o,stream:s,activity:i,nowMs:a}=e,l=[null,t?t.atMs+_o:null,n?n.atMs+So:null,r?r.atMs+xo:null,o?o.atMs+Po:null,s?s.atMs+$t:null,i?i.atMs+$t:null],p=null;for(let d of l)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function $h(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(s=>s.message_id===t),r=e.last_ended,o=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!o?.message||Ln({name:o.name??void 0,message:o.message})?null:o}var VE="SandboxMemoryGuard";function zE(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=$h(e,t);if(r?.message){if(r.name!==VE)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],l=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:l}}let o=e.recent_failures?.find(a=>a.message_id===t);if(!o)return null;let s=o.ended_at?Date.parse(o.ended_at):Number.NaN;return Number.isFinite(s)&&typeof e.atMs=="number"&&e.atMs-s<2500?null:{kind:"unexplained"}}var YE=6e4;function QE(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function XE(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var Uh=9e4;function JE(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+Uh}var ZE=75e3,eM=2,tM=2e4;function zd(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function nM(e){return e.filter(t=>t!=null).join("|")}function rM(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function oM(e,t,n={}){let r=n.noProgressMs??75e3,o=n.maxRestarts??2,s=n.cooldownMs??2e4;if(t.runtimeReachable)return{...zd(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...zd(),settled:!0};let i=e.lastProgressAtMs,a=i===null,l=t.progress!==e.fingerprint,p=i===null||l?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&&!l&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<s)return g;let f=rM(e.attempts,o);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 sM={"retry-start":"retrying",restart:"restarting"};function iM(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${sM[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function aM(e){return e===1?"once":e===2?"twice":`${e} times`}function cM(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(o=>o.step==="restart").length,n=e.attempts.some(o=>o.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 ${aM(t)}`),`Tried: ${r.join(", then ")}.`}var lM={"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 Lh(e){return!!(e.metadata??{}).legacy_migration}function uM(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 Lh(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function pM(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 dM={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 gM(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function wo(e){return e.runtime_sessions??e.opencode_sessions??[]}function Fh(e){let t=wo(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 mM(e){let t=Fh(e);return t?wo(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 fM(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=>wo(r).some(o=>o.id===t))??null)}var yM=new Set;function Nh(e){for(let t of[...yM])try{t(e)}catch{}}var hM=12e4,vo=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},bM=1e3,_M=15e3,Kh=100,PM=50,xM=10;function qh(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:o},s)=>{let i=new URLSearchParams({limit:String(r)});o&&i.set("before",o);let a=await e.getToken?.(),l=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...s?{signal:s}:{}});if(!l.ok)throw l.status===503?new Nn(`session ${l.status}`):new b(`Session synchronization failed: ${l.status}`,{status:l.status});return{messages:await l.json(),nextCursor:l.headers.get("x-next-cursor")||void 0}}}function Gh(e){return SM(qh(e))}function Bh(e){return new Yd({...e,loadPage:qh(e)})}async function SM(e){let t=[],n=new Set,r;do{let i=await e({limit:Kh,...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 o=[],s=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])s.has(a.info.id)||(s.add(a.info.id),o.push(a));return o}var wM={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Yd=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;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??wM,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??hM,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"})}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 vo;if(!r&&Ln(n))return;if(r||this.update({freshness:Dt(n)?"loading":"error"}),n instanceof b&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(bM*2**this.retryAttempt,_M);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let o=this.scheduler.now();try{let s=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?PM:Kh,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:s.messages.length,succeeded:!0}),s}catch(s){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:0,succeeded:!1}),s}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,o=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",o,{once:!0});let s,i=new Promise((l,p)=>{s=this.startTimer(()=>{let d=new vo(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(l){a=Promise.reject(l)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(s),n.removeEventListener("abort",o)})}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,o,s){let i=[...t.messages],a=new Set(this.knownUserMessageIds),l=new Set(o?[o]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<xM&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(l.has(p))throw new Error(`Session history cursor repeated: ${p}`);l.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw s?.({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,s?.({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)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 o,s=!1,i=()=>{s||(s=!0,this.cancelTimer(o),r())};o=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 Qd(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 Ao=1,vM=12,AM=15e5,kM=3e5,RM=336*60*60*1e3,IM="kortix.saved-copy";function Xd(e){return!!e&&typeof e.then=="function"}function TM(e,t){return Xd(e)?e.then(t):t(e)}function CM(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 o=a=>{let l=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:l,message_count:l.length,complete:!1,next_cursor:String(l[0].info.id)}})},s=o(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(s+a>t)break;s+=a,i+=1}for(;i>0;i-=1){let a=o(i);if(a.length<=t)return a}return null}function EM(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}function MM(e){let{storage:t,userId:n,maxSessions:r=vM,maxBytes:o=AM,maxEnvelopeBytes:s=kM,maxAgeMs:i=RM,namespace:a=IM,now:l=()=>Date.now()}=e,p=`${a}:${n}:`,d=`${p}index`,g=(x,_)=>`${p}${x}/${_}`,m=x=>{try{let _=t.getItem(x);return Xd(_)?_.catch(()=>null):_}catch{return null}},f=x=>{try{let _=t.removeItem(x);Xd(_)&&_.catch(()=>{})}catch{}},h=async x=>{try{await t.removeItem(x)}catch{}},w=x=>{if(!x)return[];try{let _=JSON.parse(x);return _?.v===Ao&&Array.isArray(_.entries)?_.entries:[]}catch{return[]}},L=Promise.resolve(),O=x=>{let _=L.then(x,x);return L=_.catch(()=>{}),_},D=async x=>{try{await t.setItem(d,JSON.stringify({v:Ao,entries:x}))}catch{}},y=async()=>w(await m(d)),P=async(x,_)=>{let A=[...x].sort((C,E)=>C.u-E.u),T=A.reduce((C,E)=>C+E.b,0);for(;A.length>r||T>o;){let C=A.findIndex(F=>F.s!==_);if(C===-1)break;let[E]=A.splice(C,1);T-=E.b,await h(`${p}${E.s}`)}return A},v=x=>{O(async()=>{let _=await y(),A=_.find(T=>T.s===x);A&&(A.u=l(),await D(_))})},$=x=>O(async()=>{await h(`${p}${x}`);let _=await y(),A=_.filter(T=>T.s!==x);A.length!==_.length&&await D(A)});return{keyFor:g,read(x,_){let A=`${x}/${_}`;return TM(m(g(x,_)),T=>{if(!T)return null;let C;try{C=JSON.parse(T)}catch{return f(g(x,_)),$(A),null}return!C||C.v!==Ao||C.user!==n||l()-C.at>i||!Qd(C.e)?(f(g(x,_)),$(A),null):(v(A),C.e)})},write(x,_,A){let T=`${x}/${_}`;if(!Qd(A))return $(T);let C={v:Ao,user:n,at:l(),e:A},E=CM(C,s);if(E===null)return $(T);let F=EM(A);return O(async()=>{let ee=await y(),Q=ee.find(V=>V.s===T);if(Q&&F>0&&Q.c>F)return;let lg=ee.filter(V=>V.s!==T),ug={s:T,b:E.length,u:l(),c:F},Ce=await P([...lg,ug],T),ie=g(x,_);try{await t.setItem(ie,E)}catch{let V=Ce.filter(te=>te.s!==T).sort((te,rt)=>te.u-rt.u)[0];V&&(await h(`${p}${V.s}`),Ce=Ce.filter(te=>te.s!==V.s));try{await t.setItem(ie,E)}catch{await h(ie),Ce=Ce.filter(te=>te.s!==T)}}await D(Ce)})},remove(x,_){return $(`${x}/${_}`)},clear(){return O(async()=>{let x=await y();for(let _ of x)await h(`${p}${_.s}`);await h(d)})}}}var Wh=null;function OM(e){Wh=e}function jM(){return Wh}function Hh(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 Vh(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function zh(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return`${t}/tunnel/permission-requests/stream`}function Yh(e){let{url:t,token:n,method:r="GET",body:o,onEvent:s,onOpen:i,onError:a,signal:l}=e,p=new Map,d=null,g=!1;function m(O,D){s?.(O,D);let y=p.get(O);if(y)for(let P of y)try{P(D)}catch{}}async function f(){if(g)return;d=new AbortController;let O=l?AbortSignal.any([d.signal,l]):d.signal;try{let D={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&o!==void 0&&(D["Content-Type"]="application/json");let y=await fetch(t,{method:r,headers:D,body:r!=="GET"&&o!==void 0?JSON.stringify(o):void 0,signal:O,credentials:"include"});if(!y.ok)throw new Error(`SSE connection failed: ${y.status} ${y.statusText}`);if(!y.body)throw new Error("SSE response has no body");i?.();let P=y.body.getReader(),v=new TextDecoder,$="",x="message",_="";for(;!g;){let{done:A,value:T}=await P.read();if(A)break;$+=v.decode(T,{stream:!0});let C=$.split(`
94
+ `),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length,i=r.length;for(;s>o&&i>o&&n[s-1]===r[i-1];)s--,i--;let a=[];for(let c=0;c<o;c++)a.push({type:"unchanged",text:n[c]});for(let c=o;c<s;c++)a.push({type:"removed",text:n[c]});for(let c=o;c<i;c++)a.push({type:"added",text:r[c]});for(let c=s;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function AT(e){let t=G(e?.oldString),n=G(e?.newString);return t!==void 0&&n!==void 0?[[t,n]]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(o=>{let s=et(o),i=s&&G(s.oldText),a=s&&G(s.newText);return i!==void 0&&a!==void 0?[[i,a]]:[]})}function kT(e){let t=AT(e.input),n=t.map(([o,s])=>vT(o,s)),r=t.length&&n.every(Boolean)?n.flatMap(o=>o??[]):void 0;return{kind:"file-edit",path:$d(e),diff:r}}var nh=/^Found\s+(\d+)\s+match/i,RT=/^(\/[^:]+?):\s*/,th=/Line\s+(\d+):/g;function IT(e){let t=e.trim(),n=t.match(nh),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let o=[];for(let s of r.split(/\n\n+/)){let i=s.trim();if(!i)continue;let a=i.match(RT);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(th.lastIndex=0;(g=th.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();o.push({path:c,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return o}function TT(e){return e.trim().split(`
95
+ `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function CT(e){let t=G(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=nh.test(e.output.trim())?IT(e.output):TT(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function ET(e){let t=G(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=G(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function jd(e){let t=et(e)??{};return{content:G(t.content)??"",status:G(t.status)??"pending",priority:G(t.priority)}}function MT(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(jd)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(jd)};let n=et(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(jd)}:{kind:"todo",items:[]}}function OT(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let o=et(r)??{},i=(Array.isArray(o.options)?o.options:[]).flatMap(a=>{let c=et(a),p=c&&G(c.label);return p?[{label:p,description:c?G(c.description):void 0}]:[]});return{question:G(o.question)??"",header:G(o.header),options:i}})}}function jT(e){let n=e.input&&Object.keys(e.input).length>0?eh(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?$n(e.outputParsed):eh(e.outputParsed):e.outputText!==void 0?r=$n(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function rh(e){switch(ne(e.name)){case"web_search":return gT(e);case"bash":return PT(e);case"read":return xT(e);case"write":return ST(e);case"edit":return kT(e);case"grep":case"glob":return CT(e);case"task":return ET(e);case"todowrite":return MT(e);case"question":return OT(e);default:return jT(e)}}var DT=new Set(["AbortError","MessageAbortedError"]),$T=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],UT=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function oh(e){let t=e.toLowerCase();return UT.some(n=>t.includes(n))?!1:$T.some(n=>t.includes(n))}function LT(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 Un(e){if(typeof e=="string")return oh(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&DT.has(n))return!0;let r=LT(t);return typeof r=="string"?oh(r):!1}var sh=["user","runtime-disposed","orphan-finalized","wake"],FT=["orphan-finalized","wake"];function NT(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 sh.includes(n)?n:void 0}var Ln="kortix-active-instance",ih=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function ah(e){return ih.some(t=>e===t||e.startsWith(`${t}/`))}function Mt(e){let t=e.match(/^\/instances\/([^/]+)(?:\/(.*))?$/);if(!t)return null;let n=decodeURIComponent(t[1]),r=t[2]??"";return{instanceId:n,innerPath:r?`/${r}`:""}}function KT(e){let t=Mt(e);return!!t&&t.innerPath===""}function qT(e){let t=Mt(e);return!t||!t.innerPath?e:t.innerPath}function ch(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=Mt(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return ah(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function lh(e){return e?Mt(e)?.instanceId??null:null}function GT(){return typeof window>"u"?null:lh(window.location.pathname)||uh()}function uh(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Ln}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function BT(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Ln}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Ln}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Ln}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function WT(e,t){return t?ch(t,e):e}function HT(e){let t=Mt(e);return t?t.innerPath||"/dashboard":e}function Nn(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 Ud(e){let t=Nn(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 o of n)if(o)try{return JSON.parse(o)}catch{}return null}var VT=Ud;function yo(e){let t=Ud(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var zT=yo;function ph(e){return yo(e)!==null}var YT=ph,QT=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],XT=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],JT=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function dh(e){return JT.test(Nn(e))}function Ot(e){let t=Nn(e);return t?dh(t)||QT.some(n=>n.test(t)):!1}var ZT=/server url not ready|sandbox is still loading/i;function eC(e){return ZT.test(Nn(e))||Ot(e)}var Fn=class extends Error{constructor(t){let n=t?.trim();super(n&&Ot(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function gh(e){let t=yo(e);if(t){let o=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),s=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:`${o} is preventing OpenCode from loading. ${a}`,detail:s?`${i?`${i}: `:""}${s}`:void 0}}let n=Nn(e);return Ot(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 tC=gh;function Ld(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`${Oe()}/p/${e.external_id}/${we.KORTIX_MASTER}`}function nC(e,t){return e.external_id?`${Oe()}/p/${e.external_id}/${t}`:null}async function rC(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function mh(e){let t=await He();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Ge())[0];if(!r)throw new Error("Create a project before starting a sandbox");let o=await We(r.project_id,{...e?.provider?{provider:e.provider}:{}}),s=(await Ee(r.project_id,o.session_id))?.sandbox??null;return{sandbox:Rp(r,o,s),created:!0}}async function oC(){return(await He().catch(()=>null))?.sandbox??null}async function sC(e){return{sandbox:(await mh(e)).sandbox}}async function iC(e){let t=pn(e);return t?(await He(t).catch(()=>null))?.sandbox??null:null}async function aC(e,t){throw await He(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function cC(e){let t=pn(e);return(await Ip().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function lC(){return null}async function uC(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await He(e);if(!t)throw new Error("Project session sandbox not found");await nn(t.project.project_id,t.session.session_id)}async function pC(e){if(!e)throw new Error("No sandbox selected to stop");let t=await He(e);if(!t)throw new Error("Project session sandbox not found");await rn(t.project.project_id,t.session.session_id)}async function dC(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function gC(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function Fd(e,t,n){let r=Ld(e),o=await j(`${le(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`Request failed (${o.status})`)}return await o.json()}async function mC(e,t){return Fd(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function fC(e,t,n,r="member"){await Fd(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function yC(e,t,n){await Fd(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var Nd="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function hC(e){throw F("getInvite",Nd)}async function bC(e){throw F("acceptInvite",Nd)}async function _C(e){throw F("declineInvite",Nd)}async function PC(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function xC(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function SC(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function wC(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function vC(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function AC(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var fh=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function kC(e){return fh.includes(e)}async function RC(e){return{phase:"idle",progress:0,message:"Sandbox image updates are managed by project-session provisioning.",targetVersion:null,previousVersion:null,currentVersion:e?.version??null,error:null,startedAt:null,updatedAt:null}}async function IC(e){let t=e?`?channel=${e}`:"",n=await fetch(`${Oe()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Version check failed: ${n.status}`);let r=await n.json();try{let o=await yh(e||"stable");r.changelog=o.find(s=>s.version===r.version)??o[0]??null}catch{r.changelog=null}return r}async function yh(e){let t=e?`?channel=${e}`:"",n=await fetch(`${Oe()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Changelog fetch failed: ${n.status}`);return(await n.json()).changelog}async function TC(){let e=await fetch(`${Oe()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`All versions fetch failed: ${e.status}`);return e.json()}async function CC(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function EC(e){}async function MC(e){}async function OC(e){return{serverTypes:[],location:e||"hel1"}}async function jC(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function DC(e){throw F("deleteInstance")}async function $C(e,t){}async function UC(){throw F("claimComputer")}async function LC(e){return null}function FC(e,t){throw F("getSandboxProvisionStreamUrl")}var Kn=class extends Error{constructor(n,r,o){super(n);this.status=r;this.body=o;this.name="HostBoundaryError"}status;body};function hh(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 bh(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function _h(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 H(e,t,n){let r=n?.body!==void 0,o=await fetch(`${dn(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:hh(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),s=await bh(o);if(!o.ok)throw new Kn(_h(o,s),o.status,s);return s}function NC(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 KC(e,t){return H(`/marketplace/items${NC(t)}`,e)}function qC(e){return H("/marketplace/marketplaces",e)}function GC(e,t){return H(`/marketplace/items/${encodeURIComponent(e)}`,t)}function BC(e,t,n){return H(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function WC(e,t){return H("/access/check-email",t,{method:"POST",body:{email:e}})}function HC(e,t){return H("/access/request-access",t,{method:"POST",body:e})}function VC(e){return H("/auth/logout",e,{method:"POST",body:{}})}function zC(e,t){return H(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function YC(e,t){return H("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function QC(e,t){return H(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function XC(e,t){return H(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function JC(e,t,n={}){return H(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function ZC(e,t){return H(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function eE(e,t,n,r){return H(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function tE(e,t){return H(`/p/public-share/${encodeURIComponent(e)}`,t)}function nE(e,t,n){return H(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function rE(e){return H("/system/maintenance",e)}function oE(e,t){return H("/system/maintenance",t,{method:"PUT",body:e})}function sE(e){return H("/user-roles",e)}function iE(e,t){return H("/system/demo-request",t,{method:"POST",body:e})}async function aE(e,t,n){let r=await fetch(`${dn(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${ut(t)}`,{headers:hh(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let o=await bh(r);throw new Kn(_h(r,o),r.status,o)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function cE(e,t){throw F("openStressTestStream")}function lE(e,t){throw F("buildPublicTemplateUrl")}async function uE(e,t,n){throw F("getPublicTemplate")}var pE="kortix:connect-link:";function Kd(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let o=e.charCodeAt(r);t=Math.imul(t^o,16777619)>>>0,n=Math.imul(n^o,1540483477)>>>0}return`${pE}${t.toString(36)}${n.toString(36)}`}function dE(e,{storage:t}={}){let n=new Map,r=new Map,o=i=>{if(t)try{let a=t.getItem(Kd(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(Kd(i));return}return c}catch{return}},s=(i,a)=>{if(t)try{t.setItem(Kd(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=o(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),s(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var Ph="Could not start the connect flow.";async function gE(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:Ph}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:Ph};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var xh=3e3,Sh=5e3,wh=5*6e4;function mE(e,t){let n=e===0?xh:Sh;return t+n>wh?null:n}function fE(e){let t=e.project_name?.trim();return{app:e.name?.trim()||e.app?.trim()||e.slug,project:t&&t!=="this project"?t:null}}async function yE(){let e=await l.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function hE(e={}){let t=await l.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function bE(e){let t=await l.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function _E(e){let t=await l.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function PE(){let e=await l.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var QK="1";var xE="kortix.query-cache";function Ah(e){return!!e&&typeof e.then=="function"}function vh(e){return Ah(e)?e:Promise.resolve()}function SE(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 wE(e){let{storage:t,userId:n,shouldPersist:r,version:o="1",maxAgeMs:s=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=xE,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),w=()=>{try{return vh(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},L=(x,_)=>{if(!_)return 0;let A;try{A=JSON.parse(_)}catch{return w(),0}if(!A||A.v!==o||A.user!==n||!Array.isArray(A.queries)||p()-A.at>s)return w(),0;let T=0;for(let C of A.queries){if(!C||!Array.isArray(C.k)||C.d===void 0||typeof C.t!="number"||p()-C.t>s||!r(C.k))continue;let E=x.getQueryState(C.k);E&&E.data!==void 0&&E.dataUpdatedAt>=C.t||(x.setQueryData(C.k,C.d,{updatedAt:C.t}),x.invalidateQueries?.({queryKey:C.k,exact:!0,refetchType:"none"}),T+=1)}return T},O=x=>x.getQueryCache().getAll().filter(_=>_.state.data!==void 0&&r(_.queryKey)).map(_=>({k:_.queryKey,d:_.state.data,t:_.state.dataUpdatedAt})).sort((_,A)=>A.t-_.t),D=(x,_)=>{let A=[],T=0;for(let C of x){let E=JSON.stringify(C).length+1;T+E>_||(A.push(C),T+=E)}return A},y=async x=>{let _=D(O(x),i);for(;;){let A={v:o,user:n,at:p(),queries:_};try{await vh(t.setItem(d,JSON.stringify(A)));return}catch{if(_.length===0)return;_=_.slice(0,Math.floor(_.length/2))}}},P=()=>{f!==null&&(clearTimeout(f),f=null)},v=()=>{P();let x=g;return!x||!m||(m=!1,h=h.then(()=>y(x)).catch(()=>{})),h},$=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,v()},a))};return{storageKey:d,restore(x){let _;try{_=t.getItem(d)}catch{return 0}return Ah(_)?_.then(A=>L(x,A)).catch(()=>0):L(x,_)},persist(x){g=x,m=!0;let _=x.getQueryCache().subscribe(A=>{A.type!=="updated"&&A.type!=="removed"&&A.type!=="added"||r(A.query.queryKey)&&$()});return()=>{_(),g===x&&(g=null,P())}},flush(){return v()},async clear(){P(),g=null,m=!1,await h,await w()}}}function vE(){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 kh="/kortix/part/";function Rh(e){return typeof e=="string"&&e.startsWith(kh)}async function AE(e){if(!Rh(e))throw new Error(`not an attachment part reference: ${e}`);let t=Ae();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 Ih(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 kE(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let s=new Set;if(t)try{s.add(new URL(t).origin)}catch{}return typeof window<"u"&&s.add(window.location.origin),s.has(n.origin)}catch{return!1}}function qd(e,t){return kE(e,t)?(t?Ih(t):null)??Ih(e):null}function qn(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 Gd(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var RE=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function IE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function TE(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 o=(t.slice(n+3).split("/")[0]??"").toLowerCase(),s=`${r}://${o}`.split("{port}").map(i=>i.split("{sandbox}").map(IE).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${s}$`).test(e)}function CE(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function Th(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function EE(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:RE.test(n.hostname)?t.backendUrls.some(r=>{let o=CE(r);return o!==null&&Th(o)===Th(n)}):t.templates.some(r=>TE(n.origin,r))}async function Ch(e,t={}){if(!qn(e))return!1;let n=k().backendUrl;n&&await mt(n).catch(()=>null);let r=[n,t.serverUrl].filter(o=>typeof o=="string"&&o.length>0);return EE(e,{templates:lm(),backendUrls:r})}async function Eh(e,t={}){let n=qd(e,t.serverUrl||k().backendUrl||void 0);if(!n)return!1;let r=await at();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 ME(e,t={}){if(qn(e)){if(!await Ch(e,t))return e;let n=await at();return n?Gd(e,n):e}return await Eh(e,t),e}var OE=3e3;function Mh(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 jE(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let o=setTimeout(r,t?.timeoutMs??3e3);try{let s=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return Mh(s.status)}catch{return"unknown"}finally{clearTimeout(o),t?.signal?.removeEventListener("abort",r)}}function DE(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function $E(e,t){throw F("buildPresentationTemplatePdfUrl")}function UE(e,t){throw F("buildPresentationTemplateImageUrl")}function Oh(e,t){return`${DE(e)}/presentation/convert-to-${t}`}async function LE(e,t,n,r){let o=Oh(t,e),s=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!1;for(;;){let p=await fetch(o,{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 L=setTimeout(h,s);r?.signal?.addEventListener("abort",()=>{clearTimeout(L),w(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 FE(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 NE(e){return e==="unreachable"}function KE(e){return!e||e.status===0?"unknown":e.ok&&Jp(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var jh=1e4,qE={connection:"unknown",faultSinceMs:null};function GE(e,t,n,r=jh){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let o=e.faultSinceMs??n;return n-o>=r?{connection:t,faultSinceMs:o}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:o}}function Dh({optimistic:e,abort:t,inbox:n,server:r,stream:o,activity:s,nowMs:i}){let a=!!e&&i-e.atMs<ho,c=!!t&&i-t.atMs<Po;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<=bo,streamFresh:!!o&&i-o.atMs<=jt,inboxFresh:!!n&&i-n.atMs<=_o,activityFresh:!!s&&i-s.atMs<=jt}}function Dt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Bd(e,t,n){if(!t)return!1;let r=Dt(e.started_at);if(r===null||r>=t.atMs)return!1;let o=n?.lastEnded,s=Dt(o?.ended_at);return!(o&&s!==null&&Math.abs(s-t.atMs)<=1e3&&o.turn_token!==e.turn_token)}function BE(e,t,n,r){let{activity:o,server:s}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||o.atMs>n.atMs)&&o.atMs>=a?{state:"working",source:"stream",turnId:i?s.turns.find(d=>d.state==="active"&&!Bd(d,n,s))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:r}:null}function WE(e,t,n,r){let{server:o,stream:s}=e,{serverFresh:i,abortFloor:a}=t,c=i?o.turns.filter(g=>!Bd(g,n,o)):[],p=c.find(g=>g.state==="active")??c[0],d=!!s&&!(s.type==="idle"&&s.origin==="local");return p&&o.atMs>=a&&(!d||o.atMs>=s.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:Dt(p.started_at)??o.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function HE(e,t,n){let{inbox:r,server:o,stream:s}=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&&s.type!=="idle"&&(!p||s.atMs>o.atMs)&&s.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&&o.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function VE(e,t,n,r){let{server:o,stream:s,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,w=c&&!n&&o.atMs>=p,L=d&&s.atMs>=g&&(s.type==="idle"||s.atMs>=m);if(w&&(!s||o.atMs>=s.atMs))return{state:"idle",source:"server",turnId:null,since:Dt(o.lastEnded?.ended_at)??o.atMs,serverOpenTurnToken:r};if(L)return{state:s.type==="idle"?"idle":"working",source:"stream",turnId:null,since:s.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let O=o&&s?o.atMs>=s.atMs?{source:"server",atMs:o.atMs}:{source:"stream",atMs:s.atMs}:o?{source:"server",atMs:o.atMs}:s?{source:"stream",atMs:s.atMs}:{source:"server",atMs:a};return{state:"idle",source:O.source,turnId:null,since:O.atMs,serverOpenTurnToken:r}}function $h(e){let t=Dh(e),{server:n,stream:r}=e,o=r&&r.type==="idle"&&r.origin!=="local"?r:null,s=n?.turns[0]?.turn_token??null,i=BE(e,t,o,s);if(i)return i;let{result:a,openTurn:c}=WE(e,t,o,s);return a??HE(e,t,s)??VE(e,t,c,s)}var ho=6e4,bo=45e3,jt=45e3,_o=1e4,zE=3e3,Po=15e3;function YE(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function QE(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 XE(e){return $h(e)}function JE(e){let{optimistic:t,abort:n,inbox:r,server:o,stream:s,activity:i,nowMs:a}=e,c=[null,t?t.atMs+ho:null,n?n.atMs+Po:null,r?r.atMs+_o:null,o?o.atMs+bo:null,s?s.atMs+jt:null,i?i.atMs+jt:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function Uh(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(s=>s.message_id===t),r=e.last_ended,o=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!o?.message||Un({name:o.name??void 0,message:o.message})?null:o}var ZE="SandboxMemoryGuard";function eM(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=Uh(e,t);if(r?.message){if(r.name!==ZE)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 o=e.recent_failures?.find(a=>a.message_id===t);if(!o)return null;let s=o.ended_at?Date.parse(o.ended_at):Number.NaN;return Number.isFinite(s)&&typeof e.atMs=="number"&&e.atMs-s<2500?null:{kind:"unexplained"}}var tM=6e4;function nM(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function rM(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var Lh=9e4;function oM(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+Lh}var sM=75e3,iM=2,aM=2e4;function Wd(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function cM(e){return e.filter(t=>t!=null).join("|")}function lM(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function uM(e,t,n={}){let r=n.noProgressMs??75e3,o=n.maxRestarts??2,s=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Wd(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Wd(),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<s)return g;let f=lM(e.attempts,o);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 pM={"retry-start":"retrying",restart:"restarting"};function dM(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${pM[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function gM(e){return e===1?"once":e===2?"twice":`${e} times`}function mM(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(o=>o.step==="restart").length,n=e.attempts.some(o=>o.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 ${gM(t)}`),`Tried: ${r.join(", then ")}.`}var fM={"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 Fh(e){return!!(e.metadata??{}).legacy_migration}function yM(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 Fh(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function hM(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 bM={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 _M(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function xo(e){return e.runtime_sessions??e.opencode_sessions??[]}function Nh(e){let t=xo(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 PM(e){let t=Nh(e);return t?xo(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 xM(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=>xo(r).some(o=>o.id===t))??null)}var SM=new Set;function Kh(e){for(let t of[...SM])try{t(e)}catch{}}var wM=12e4,So=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},vM=1e3,AM=15e3,qh=100,kM=50,RM=10;function Gh(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:o},s)=>{let i=new URLSearchParams({limit:String(r)});o&&i.set("before",o);let a=await e.getToken?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...s?{signal:s}:{}});if(!c.ok)throw c.status===503?new Fn(`session ${c.status}`):new b(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function Bh(e){return IM(Gh(e))}function Wh(e){return new Hd({...e,loadPage:Gh(e)})}async function IM(e){let t=[],n=new Set,r;do{let i=await e({limit:qh,...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 o=[],s=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])s.has(a.info.id)||(s.add(a.info.id),o.push(a));return o}var TM={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Hd=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;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??TM,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??wM,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"})}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 So;if(!r&&Un(n))return;if(r||this.update({freshness:Ot(n)?"loading":"error"}),n instanceof b&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(vM*2**this.retryAttempt,AM);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let o=this.scheduler.now();try{let s=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?kM:qh,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:s.messages.length,succeeded:!0}),s}catch(s){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:0,succeeded:!1}),s}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,o=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",o,{once:!0});let s,i=new Promise((c,p)=>{s=this.startTimer(()=>{let d=new So(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(s),n.removeEventListener("abort",o)})}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,o,s){let i=[...t.messages],a=new Set(this.knownUserMessageIds),c=new Set(o?[o]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<RM&&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 s?.({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,s?.({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)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 o,s=!1,i=()=>{s||(s=!0,this.cancelTimer(o),r())};o=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 Vd(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 wo=1,CM=12,EM=15e5,MM=3e5,OM=336*60*60*1e3,jM="kortix.saved-copy";function zd(e){return!!e&&typeof e.then=="function"}function DM(e,t){return zd(e)?e.then(t):t(e)}function $M(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 o=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)}})},s=o(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(s+a>t)break;s+=a,i+=1}for(;i>0;i-=1){let a=o(i);if(a.length<=t)return a}return null}function UM(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}function LM(e){let{storage:t,userId:n,maxSessions:r=CM,maxBytes:o=EM,maxEnvelopeBytes:s=MM,maxAgeMs:i=OM,namespace:a=jM,now:c=()=>Date.now()}=e,p=`${a}:${n}:`,d=`${p}index`,g=(x,_)=>`${p}${x}/${_}`,m=x=>{try{let _=t.getItem(x);return zd(_)?_.catch(()=>null):_}catch{return null}},f=x=>{try{let _=t.removeItem(x);zd(_)&&_.catch(()=>{})}catch{}},h=async x=>{try{await t.removeItem(x)}catch{}},w=x=>{if(!x)return[];try{let _=JSON.parse(x);return _?.v===wo&&Array.isArray(_.entries)?_.entries:[]}catch{return[]}},L=Promise.resolve(),O=x=>{let _=L.then(x,x);return L=_.catch(()=>{}),_},D=async x=>{try{await t.setItem(d,JSON.stringify({v:wo,entries:x}))}catch{}},y=async()=>w(await m(d)),P=async(x,_)=>{let A=[...x].sort((C,E)=>C.u-E.u),T=A.reduce((C,E)=>C+E.b,0);for(;A.length>r||T>o;){let C=A.findIndex(N=>N.s!==_);if(C===-1)break;let[E]=A.splice(C,1);T-=E.b,await h(`${p}${E.s}`)}return A},v=x=>{O(async()=>{let _=await y(),A=_.find(T=>T.s===x);A&&(A.u=c(),await D(_))})},$=x=>O(async()=>{await h(`${p}${x}`);let _=await y(),A=_.filter(T=>T.s!==x);A.length!==_.length&&await D(A)});return{keyFor:g,read(x,_){let A=`${x}/${_}`;return DM(m(g(x,_)),T=>{if(!T)return null;let C;try{C=JSON.parse(T)}catch{return f(g(x,_)),$(A),null}return!C||C.v!==wo||C.user!==n||c()-C.at>i||!Vd(C.e)?(f(g(x,_)),$(A),null):(v(A),C.e)})},write(x,_,A){let T=`${x}/${_}`;if(!Vd(A))return $(T);let C={v:wo,user:n,at:c(),e:A},E=$M(C,s);if(E===null)return $(T);let N=UM(A);return O(async()=>{let ee=await y(),Q=ee.find(V=>V.s===T);if(Q&&N>0&&Q.c>N)return;let ig=ee.filter(V=>V.s!==T),ag={s:T,b:E.length,u:c(),c:N},Ie=await P([...ig,ag],T),ie=g(x,_);try{await t.setItem(ie,E)}catch{let V=Ie.filter(te=>te.s!==T).sort((te,tt)=>te.u-tt.u)[0];V&&(await h(`${p}${V.s}`),Ie=Ie.filter(te=>te.s!==V.s));try{await t.setItem(ie,E)}catch{await h(ie),Ie=Ie.filter(te=>te.s!==T)}}await D(Ie)})},remove(x,_){return $(`${x}/${_}`)},clear(){return O(async()=>{let x=await y();for(let _ of x)await h(`${p}${_.s}`);await h(d)})}}}var Hh=null;function FM(e){Hh=e}function NM(){return Hh}function Vh(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 zh(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function KM(e){throw F("buildTunnelEventStreamUrl")}function qM(e){let{url:t,token:n,method:r="GET",body:o,onEvent:s,onOpen:i,onError:a,signal:c}=e,p=new Map,d=null,g=!1;function m(O,D){s?.(O,D);let y=p.get(O);if(y)for(let P of y)try{P(D)}catch{}}async function f(){if(g)return;d=new AbortController;let O=c?AbortSignal.any([d.signal,c]):d.signal;try{let D={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&o!==void 0&&(D["Content-Type"]="application/json");let y=await fetch(t,{method:r,headers:D,body:r!=="GET"&&o!==void 0?JSON.stringify(o):void 0,signal:O,credentials:"include"});if(!y.ok)throw new Error(`SSE connection failed: ${y.status} ${y.statusText}`);if(!y.body)throw new Error("SSE response has no body");i?.();let P=y.body.getReader(),v=new TextDecoder,$="",x="message",_="";for(;!g;){let{done:A,value:T}=await P.read();if(A)break;$+=v.decode(T,{stream:!0});let C=$.split(`
96
96
  `);$=C.pop()||"";for(let E of C)E===""?_&&(m(x,_.trimEnd()),x="message",_=""):E.startsWith("event: ")?x=E.slice(7).trim():E.startsWith("data: ")?_+=(_?`
97
97
  `:"")+E.slice(6):E.startsWith("data:")&&(_+=(_?`
98
- `:"")+E.slice(5))}}catch(D){if(g||D instanceof DOMException&&D.name==="AbortError")return;a?.(D instanceof Error?D:new Error(String(D)))}}function h(){g=!0,d?.abort(),d=null,p.clear()}function w(O,D){let y=p.get(O)??new Set;y.add(D),p.set(O,y)}function L(O,D){p.get(O)?.delete(D)}return{connect:f,close:h,addEventListener:w,removeEventListener:L}}function DM(e,t){return Yh({...t,url:zh(e)})}var Qh="/_kortix/viewer";var Lt=new Map;function Xh(){Lt.clear()}async function $M(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 Jd(e={}){let t=e.path??Qh,n=e.fetch??((s,i)=>fetch(s,i)),r=Lt.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let o=$M(t,n).then(s=>{let i=s?.expires_at?Date.parse(s.expires_at):Number.NaN,a=Number.isFinite(i)?i-6e4:Date.now()+6e4;return Lt.set(t,{session:s,expiresAt:a}),s});return Lt.set(t,{session:r?.session??null,expiresAt:0,inflight:o}),o}function Jh(e={}){let t=e.path??Qh;return Object.assign(async()=>(await Jd(e))?.access_token??null,{invalidate:n=>{let r=Lt.get(t);r&&!r.inflight&&r.session?.access_token===n&&Lt.delete(t)}})}function Zd(e){let t=e.agents.map(UM),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function UM(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function eg(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Ar(n?{...r,mode:null}:r))}function Zh(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let s=e.selectedAgent?.trim();return s?{selected:s,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=eg(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(s=>s.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let o=e.defaultAgent?.trim();return o&&n.some(s=>s.name===o)?{selected:o,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var eb=Zd;function tb(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function tg(e){return{providerID:"kortix",modelID:e}}function nb(e,t){let n=e.startsWith("kortix/")?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 tg(n)}var ng=[{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"v0",env:["V0_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"kimi-for-coding",env:["KIMI_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]}];function rg(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function FM(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function rb(e,t){let n=new Map;for(let r of e){let o=t(r),s=n.get(o);s?s.push(r):n.set(o,[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 ob(e){return e.reduce((t,n)=>{let r=rg(n)??0,o=rg(t)??0;return r!==o?r>o?n:t:se(n.id)>se(t.id)?n:t})}function og(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,o=new Set;for(let[,s]of rb(e,FM)){let a=[...rb(s,p=>p.family||p.id).values()].map(ob),l=a.filter(p=>{let d=rg(p);return d!==null&&Math.abs(n-d)<r});for(let p of l.length>0?l:[ob(a)])o.add(p.id)}return o}function ko(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 Gn(e){let t;for(let n of ko(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 NM={"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 sb(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var KM=(()=>{let e=new Map;for(let{id:n,env:r}of ng)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 o=[...r].sort((s,i)=>s.length-i.length||s.localeCompare(i));t.set(n,r.find(s=>sb(s)===n)??o[0])}return t})();function ib(e){let t=NM[e.id];if(t)return t;let n=e.env??[],r=n.length===1?KM.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[sb(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function ig(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var qM=["low","medium","high"];function ab(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:[...qM]}:void 0,o=e.temperature===!0,s=e.limit?.output,i=typeof s=="number"&&s>0?{ceiling:s}:void 0;return{reasoningEffort:r,temperature:o,topP:o,maxOutputTokens:i}}var cb=ng;var sg={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var Ro=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash",transport:"openrouter",morphModelId:"morph-dsv41flash",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"coreweave/fp8":{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["coreweave/fp8"],...sg,max_price:{prompt:.3,completion:1.2}}},{id:"glm-5.3-flash",name:"GLM 5.3 Flash",upstreamModelId:"z-ai/glm-5.3-flash",transport:"openrouter",morphModelId:"morph-glm53flash",morphPricing:{inputPerMillion:.1,cachedInputPerMillion:.02,outputPerMillion:.35},pricingRef:"openrouter/z-ai/glm-5.3-flash",pricing:{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5},openrouterEndpointPricing:{"decart/fp4":{inputPerMillion:.1275,cachedInputPerMillion:.0255,outputPerMillion:.425},"coreweave/nvfp4":{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5}},tier:"fast",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["low","high","max"]}],openrouterProvider:{only:["decart/fp4","coreweave/nvfp4"],...sg,max_price:{prompt:.15,completion:.5}}},{id:"kimi-k3",name:"Kimi K3 2.8T",upstreamModelId:"moonshotai/kimi-k3",transport:"openrouter",morphModelId:"morph-kimik3",morphPricing:{inputPerMillion:2.5,cachedInputPerMillion:.29,outputPerMillion:14},pricingRef:"openrouter/moonshotai/kimi-k3",pricing:{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5},openrouterEndpointPricing:{"fireworks/us":{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5}},tier:"flagship",vision:!0,limit:{context:1e6,output:65536},openrouterProvider:{only:["fireworks/us"],...sg,max_price:{prompt:3.3,completion:16.5}}}],eG=new Map(Ro.map(e=>[e.id,e]));var lb=Ro.map(e=>e.id),ub=(Ro.find(e=>e.tier==="flagship")??Ro[0]).id;var db=cb.map(e=>({id:e.id,authRequirement:ib(e)})),Bn=new Set(["kortix"]),ag=new Set(["kortix"]);function Ft(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,o=Array.isArray(r)?r:[];return o.length===0?{...e,all:[],connected:[]}:{...e,all:o,connected:o.map(s=>s.id)}}function GM(e){if(!e)return!1;let t=Ft(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(o=>r.includes(o.id)&&o.models&&Object.keys(o.models).length>0)}function BM(e){let t=Ft(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(o=>!ag.has(o.id)),connected:r.filter(o=>!ag.has(o))}}function WM(e,t,n){let r=Ft(e),o=Array.isArray(r.all)?r.all:[],s=new Set(o.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)s.has(a.id)&&ig(a.authRequirement,l=>t.has(l))&&i.add(a.id);return s.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var HM=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function VM(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 cg="opencode";function zM(e){return e.cost?.input===0&&e.cost?.output===0}function pb(e){return e===cg?Number.MAX_SAFE_INTEGER:HM.get(e)??Number.MAX_SAFE_INTEGER-1}function YM(e,t){let n=XM(t),r={},o=(e.providers??[]).map(s=>{let i=(s.models??[]).filter(a=>a.status!=="deprecated");return s.id===cg&&!n.has(cg)?{...s,models:i.filter(zM),keyless:!0}:{...s,models:i,keyless:!1}}).filter(s=>(s.keyless||n.has(s.id))&&!ag.has(s.id)&&(s.models?.length??0)>0).sort((s,i)=>pb(s.id)-pb(i.id)).map(s=>{let i=[...s.models].sort((l,p)=>(p.released??"").localeCompare(l.released??"")||se(p.id)-se(l.id)),a=Gn(i)?.id??i[0]?.id;return a&&(r[s.id]=a),{id:s.id,name:s.name,source:s.keyless?"api":"env",models:Object.fromEntries(i.map(l=>{let p=VM(l);return[l.id,{id:l.id,name:l.name,...l.released?{release_date:l.released}:{},...l.family?{family:l.family}:{},...l.reasoning!==void 0?{reasoning:l.reasoning}:{},...l.reasoning_options?{reasoning_options:l.reasoning_options}:{},...l.tool_call!==void 0?{tool_call:l.tool_call}:{},...l.attachment!==void 0?{attachment:l.attachment}:{},...l.modalities?{modalities:l.modalities}:{},...l.limit?{limit:l.limit}:{},...l.cost?{cost:l.cost}:{},...l.description?{description:l.description}:{},...l.open_weights!==void 0?{open_weights:l.open_weights}:{},...l.last_updated?{last_updated:l.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:o,connected:o.map(s=>s.id),default:r}}function QM(e,t){if(!e)return t;if(!t)return e;let n=Ft(e),r=Ft(t),o=new Map;for(let d of Array.isArray(r.all)?r.all:[])o.set(d.id,d);let s=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])s.push(o.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(s.push(d),i.add(d.id));let a=[],l=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])l.has(d)||(a.push(d),l.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=o.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:s,connected:a,default:p}}function XM(e){let t=new Set;for(let n of db)ig(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 JM(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,o])=>{if(o.variants&&Object.keys(o.variants).length>0)return[r,o];let s=ab({id:r,name:o.name,reasoning:o.reasoning,reasoning_options:o.reasoning_options}).reasoningEffort?.values;return s?.length?[r,{...o,variants:Object.fromEntries(s.map(i=>[i,{}]))}]:[r,o]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function ZM(e,t){return BM(WM(Ft(e),t,db))}function gb(e){if(e.gatewayEnabled)return e.modelPicker?JM(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?ZM(e.runtimeProviders,t):void 0;return QM(e.llmCatalogProviders?YM(e.llmCatalogProviders,t):void 0,GM(n)?n:void 0)}function eO(e){return"capabilities"in e&&e.capabilities!=null}function Io(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function mb(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],o=Array.isArray(e.connected)?e.connected:[],s=[];for(let i of r)if(o.includes(i.id)&&!(n==="gateway"?!Bn.has(i.id):Bn.has(i.id)))for(let[a,l]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(eO(l)){let d=l.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=l.modalities?.input;p={reasoning:l.reasoning??!1,vision:d?d.includes("image"):l.attachment,toolcall:l.tool_call??!1}}s.push({id:tb({providerID:i.id,modelID:a}),providerID:i.id,providerName:l.provider_name??i.name,modelID:a,modelName:(l.name||a).replace("(latest)","").trim(),variants:l.variants,capabilities:p,contextWindow:l.limit?.context,releaseDate:l.release_date,family:l.family,cost:l.cost?{input:l.cost.input??0,output:l.cost.output??0}:void 0,providerSource:i.source,provider:l.provider,reasoningOptions:l.reasoning_options,description:l.description,openWeights:l.open_weights,lastUpdated:l.last_updated,enabled:l.enabled,free:l.free===!0})}return s}function fb(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var tO=new Set([ub]),nO="kortix",yb="codex",rO=new Set(lb);function oO(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Nt(e){return tO.has(e.modelID)}function sO(e){return og(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function hb(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=sO(e.catalogModels),o=fb(e.catalogModels),s=new Map;for(let i of e.pins??[])s.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,l=s.get(a);if(l==="hide")return!1;if(i.providerID===nO){let d=oO(i.modelID,i.provider),g=d===yb?t?.has(yb)??!1:t?.has(d)??!1;if(rO.has(i.modelID))return!n;if(!g)return!1;if(l==="show"||r.has(a))return!0;let m=o.get(a);if(!m?.releaseDate)return Nt(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Nt(i)}catch{return Nt(i)}return!1}if(l==="show"||r.has(a))return!0;let p=o.get(a);if(!p?.releaseDate)return Nt(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Nt(i)}catch{return Nt(i)}return!1}}function bb(e,t){return t.search.trim().length>0||e.providerID==="kortix"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function _b(e,t){if(!e||Bn.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,s=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??Gn(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!s||s===e.modelID?e:{...e,modelID:s}}function Pb(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??(e?.freeTier?void 0:e?.platformDefault);return n?tg(n):void 0}function xb(e){let{models:t,providers:n}=e,r=l=>Io(t,l),o=l=>l.find(p=>!!p&&r(p)),s=(()=>{if(e.configModel){let l=e.configModel.split("/");if(l.length>=2){let[p,...d]=l,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let l of e.recent??[])if(r(l))return l;if(n){let l=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=l[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of ko(Object.keys(m.models).map(w=>({id:w})))){let w={providerID:m.id,modelID:h.id};if(r(w))return w}}}})(),i=o(e.picks??[]),a=i??o([e.serverDefault,e.globalDefault,e.agentModel,s]);return{model:_b(a,t),explicit:i,fallback:s}}return Ib(iO);})();
98
+ `:"")+E.slice(5))}}catch(D){if(g||D instanceof DOMException&&D.name==="AbortError")return;a?.(D instanceof Error?D:new Error(String(D)))}}function h(){g=!0,d?.abort(),d=null,p.clear()}function w(O,D){let y=p.get(O)??new Set;y.add(D),p.set(O,y)}function L(O,D){p.get(O)?.delete(D)}return{connect:f,close:h,addEventListener:w,removeEventListener:L}}function GM(e,t){throw F("createTunnelEventStream")}var Yh="/_kortix/viewer";var $t=new Map;function Qh(){$t.clear()}async function BM(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 Yd(e={}){let t=e.path??Yh,n=e.fetch??((s,i)=>fetch(s,i)),r=$t.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let o=BM(t,n).then(s=>{let i=s?.expires_at?Date.parse(s.expires_at):Number.NaN,a=Number.isFinite(i)?i-6e4:Date.now()+6e4;return $t.set(t,{session:s,expiresAt:a}),s});return $t.set(t,{session:r?.session??null,expiresAt:0,inflight:o}),o}function Xh(e={}){let t=e.path??Yh;return Object.assign(async()=>(await Yd(e))?.access_token??null,{invalidate:n=>{let r=$t.get(t);r&&!r.inflight&&r.session?.access_token===n&&$t.delete(t)}})}function Qd(e){let t=e.agents.map(WM),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function WM(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function Xd(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Ar(n?{...r,mode:null}:r))}function Jh(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let s=e.selectedAgent?.trim();return s?{selected:s,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=Xd(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(s=>s.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let o=e.defaultAgent?.trim();return o&&n.some(s=>s.name===o)?{selected:o,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var Zh=Qd;function eb(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Jd(e){return{providerID:"kortix",modelID:e}}function tb(e,t){let n=e.startsWith("kortix/")?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 Jd(n)}var Zd=[{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"v0",env:["V0_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"kimi-for-coding",env:["KIMI_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]}];function eg(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function VM(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function nb(e,t){let n=new Map;for(let r of e){let o=t(r),s=n.get(o);s?s.push(r):n.set(o,[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 rb(e){return e.reduce((t,n)=>{let r=eg(n)??0,o=eg(t)??0;return r!==o?r>o?n:t:se(n.id)>se(t.id)?n:t})}function tg(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,o=new Set;for(let[,s]of nb(e,VM)){let a=[...nb(s,p=>p.family||p.id).values()].map(rb),c=a.filter(p=>{let d=eg(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[rb(a)])o.add(p.id)}return o}function vo(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 Gn(e){let t;for(let n of vo(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 zM={"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 ob(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var YM=(()=>{let e=new Map;for(let{id:n,env:r}of Zd)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 o=[...r].sort((s,i)=>s.length-i.length||s.localeCompare(i));t.set(n,r.find(s=>ob(s)===n)??o[0])}return t})();function sb(e){let t=zM[e.id];if(t)return t;let n=e.env??[],r=n.length===1?YM.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[ob(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function rg(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var QM=["low","medium","high"];function ib(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:[...QM]}:void 0,o=e.temperature===!0,s=e.limit?.output,i=typeof s=="number"&&s>0?{ceiling:s}:void 0;return{reasoningEffort:r,temperature:o,topP:o,maxOutputTokens:i}}var ab=Zd;var ng={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var Ao=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash",transport:"openrouter",morphModelId:"morph-dsv41flash",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"coreweave/fp8":{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["coreweave/fp8"],...ng,max_price:{prompt:.3,completion:1.2}}},{id:"glm-5.3-flash",name:"GLM 5.3 Flash",upstreamModelId:"z-ai/glm-5.3-flash",transport:"openrouter",morphModelId:"morph-glm53flash",morphPricing:{inputPerMillion:.1,cachedInputPerMillion:.02,outputPerMillion:.35},pricingRef:"openrouter/z-ai/glm-5.3-flash",pricing:{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5},openrouterEndpointPricing:{"decart/fp4":{inputPerMillion:.1275,cachedInputPerMillion:.0255,outputPerMillion:.425},"coreweave/nvfp4":{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5}},tier:"fast",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["low","high","max"]}],openrouterProvider:{only:["decart/fp4","coreweave/nvfp4"],...ng,max_price:{prompt:.15,completion:.5}}},{id:"kimi-k3",name:"Kimi K3 2.8T",upstreamModelId:"moonshotai/kimi-k3",transport:"openrouter",morphModelId:"morph-kimik3",morphPricing:{inputPerMillion:2.5,cachedInputPerMillion:.29,outputPerMillion:14},pricingRef:"openrouter/moonshotai/kimi-k3",pricing:{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5},openrouterEndpointPricing:{"fireworks/us":{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5}},tier:"flagship",vision:!0,limit:{context:1e6,output:65536},openrouterProvider:{only:["fireworks/us"],...ng,max_price:{prompt:3.3,completion:16.5}}}],dG=new Map(Ao.map(e=>[e.id,e]));var cb=Ao.map(e=>e.id),lb=(Ao.find(e=>e.tier==="flagship")??Ao[0]).id;var pb=ab.map(e=>({id:e.id,authRequirement:sb(e)})),Bn=new Set(["kortix"]),og=new Set(["kortix"]);function Ut(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,o=Array.isArray(r)?r:[];return o.length===0?{...e,all:[],connected:[]}:{...e,all:o,connected:o.map(s=>s.id)}}function XM(e){if(!e)return!1;let t=Ut(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(o=>r.includes(o.id)&&o.models&&Object.keys(o.models).length>0)}function JM(e){let t=Ut(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(o=>!og.has(o.id)),connected:r.filter(o=>!og.has(o))}}function ZM(e,t,n){let r=Ut(e),o=Array.isArray(r.all)?r.all:[],s=new Set(o.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)s.has(a.id)&&rg(a.authRequirement,c=>t.has(c))&&i.add(a.id);return s.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var eO=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function tO(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 sg="opencode";function nO(e){return e.cost?.input===0&&e.cost?.output===0}function ub(e){return e===sg?Number.MAX_SAFE_INTEGER:eO.get(e)??Number.MAX_SAFE_INTEGER-1}function rO(e,t){let n=sO(t),r={},o=(e.providers??[]).map(s=>{let i=(s.models??[]).filter(a=>a.status!=="deprecated");return s.id===sg&&!n.has(sg)?{...s,models:i.filter(nO),keyless:!0}:{...s,models:i,keyless:!1}}).filter(s=>(s.keyless||n.has(s.id))&&!og.has(s.id)&&(s.models?.length??0)>0).sort((s,i)=>ub(s.id)-ub(i.id)).map(s=>{let i=[...s.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||se(p.id)-se(c.id)),a=Gn(i)?.id??i[0]?.id;return a&&(r[s.id]=a),{id:s.id,name:s.name,source:s.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=tO(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:o,connected:o.map(s=>s.id),default:r}}function oO(e,t){if(!e)return t;if(!t)return e;let n=Ut(e),r=Ut(t),o=new Map;for(let d of Array.isArray(r.all)?r.all:[])o.set(d.id,d);let s=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])s.push(o.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(s.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=o.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:s,connected:a,default:p}}function sO(e){let t=new Set;for(let n of pb)rg(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 iO(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,o])=>{if(o.variants&&Object.keys(o.variants).length>0)return[r,o];let s=ib({id:r,name:o.name,reasoning:o.reasoning,reasoning_options:o.reasoning_options}).reasoningEffort?.values;return s?.length?[r,{...o,variants:Object.fromEntries(s.map(i=>[i,{}]))}]:[r,o]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function aO(e,t){return JM(ZM(Ut(e),t,pb))}function db(e){if(e.gatewayEnabled)return e.modelPicker?iO(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?aO(e.runtimeProviders,t):void 0;return oO(e.llmCatalogProviders?rO(e.llmCatalogProviders,t):void 0,XM(n)?n:void 0)}function cO(e){return"capabilities"in e&&e.capabilities!=null}function ko(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function gb(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],o=Array.isArray(e.connected)?e.connected:[],s=[];for(let i of r)if(o.includes(i.id)&&!(n==="gateway"?!Bn.has(i.id):Bn.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(cO(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}}s.push({id:eb({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 s}function mb(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var lO=new Set([lb]),uO="kortix",fb="codex",pO=new Set(cb);function dO(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Lt(e){return lO.has(e.modelID)}function gO(e){return tg(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function yb(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=gO(e.catalogModels),o=mb(e.catalogModels),s=new Map;for(let i of e.pins??[])s.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,c=s.get(a);if(c==="hide")return!1;if(i.providerID===uO){let d=dO(i.modelID,i.provider),g=d===fb?t?.has(fb)??!1:t?.has(d)??!1;if(pO.has(i.modelID))return!n;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=o.get(a);if(!m?.releaseDate)return Lt(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Lt(i)}catch{return Lt(i)}return!1}if(c==="show"||r.has(a))return!0;let p=o.get(a);if(!p?.releaseDate)return Lt(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Lt(i)}catch{return Lt(i)}return!1}}function hb(e,t){return t.search.trim().length>0||e.providerID==="kortix"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function bb(e,t){if(!e||Bn.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,s=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??Gn(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!s||s===e.modelID?e:{...e,modelID:s}}function _b(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??(e?.freeTier?void 0:e?.platformDefault);return n?Jd(n):void 0}function Pb(e){let{models:t,providers:n}=e,r=c=>ko(t,c),o=c=>c.find(p=>!!p&&r(p)),s=(()=>{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 vo(Object.keys(m.models).map(w=>({id:w})))){let w={providerID:m.id,modelID:h.id};if(r(w))return w}}}})(),i=o(e.picks??[]),a=i??o([e.serverDefault,e.globalDefault,e.agentModel,s]);return{model:bb(a,t),explicit:i,fallback:s}}return Rb(mO);})();