@kortix/sdk 0.13.54 → 0.13.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -9
- package/dist/browser/stores/sync-store.d.ts +20 -0
- package/dist/browser/stores/sync-store.d.ts.map +1 -1
- package/dist/browser/stores/sync-store.js +65 -23
- package/dist/browser/stores/sync-store.js.map +1 -1
- package/dist/core/auth/app-viewer.d.ts +1 -1
- package/dist/core/auth/app-viewer.js +1 -1
- package/dist/core/client/kortix.d.ts +3 -0
- package/dist/core/client/kortix.d.ts.map +1 -1
- package/dist/core/client/kortix.js +3 -0
- package/dist/core/client/kortix.js.map +1 -1
- package/dist/core/client/project-access-resources.d.ts +1 -1
- package/dist/core/client/project-access-resources.d.ts.map +1 -1
- package/dist/core/client/project-access-resources.js +1 -1
- package/dist/core/client/project-access-resources.js.map +1 -1
- package/dist/core/client/project-core.d.ts.map +1 -1
- package/dist/core/rest/platform-client/client-policy.d.ts +21 -0
- package/dist/core/rest/platform-client/client-policy.d.ts.map +1 -0
- package/dist/core/rest/platform-client/client-policy.js +49 -0
- package/dist/core/rest/platform-client/client-policy.js.map +1 -0
- package/dist/core/rest/platform-client/index.d.ts +1 -0
- package/dist/core/rest/platform-client/index.d.ts.map +1 -1
- package/dist/core/rest/platform-client/index.js +1 -0
- package/dist/core/rest/platform-client/index.js.map +1 -1
- package/dist/core/rest/projects-client/apps-fleet.js +1 -1
- package/dist/core/rest/projects-client/apps.d.ts +18 -2
- package/dist/core/rest/projects-client/apps.d.ts.map +1 -1
- package/dist/core/rest/projects-client/apps.js.map +1 -1
- package/dist/core/rest/projects-client/projects.d.ts +6 -1
- package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
- package/dist/core/rest/projects-client/projects.js +3 -0
- package/dist/core/rest/projects-client/projects.js.map +1 -1
- package/dist/core/session/control-stream.d.ts +12 -0
- package/dist/core/session/control-stream.d.ts.map +1 -1
- package/dist/core/session/control-stream.js +22 -1
- package/dist/core/session/control-stream.js.map +1 -1
- package/dist/core/session-log/guard.d.ts +18 -0
- package/dist/core/session-log/guard.d.ts.map +1 -0
- package/dist/core/session-log/guard.js +114 -0
- package/dist/core/session-log/guard.js.map +1 -0
- package/dist/core/session-log/index.d.ts +16 -0
- package/dist/core/session-log/index.d.ts.map +1 -0
- package/dist/core/session-log/index.js +15 -0
- package/dist/core/session-log/index.js.map +1 -0
- package/dist/core/session-log/saved-log.d.ts +23 -0
- package/dist/core/session-log/saved-log.d.ts.map +1 -0
- package/dist/core/session-log/saved-log.js +34 -0
- package/dist/core/session-log/saved-log.js.map +1 -0
- package/dist/core/session-log/source.d.ts +36 -0
- package/dist/core/session-log/source.d.ts.map +1 -0
- package/dist/core/session-log/source.js +52 -0
- package/dist/core/session-log/source.js.map +1 -0
- package/dist/core/session-log/store.d.ts +25 -0
- package/dist/core/session-log/store.d.ts.map +1 -0
- package/dist/core/session-log/store.js +170 -0
- package/dist/core/session-log/store.js.map +1 -0
- package/dist/core/session-log/types.d.ts +371 -0
- package/dist/core/session-log/types.d.ts.map +1 -0
- package/dist/core/session-log/types.js +24 -0
- package/dist/core/session-log/types.js.map +1 -0
- package/dist/core/session-log/v1-view.d.ts +30 -0
- package/dist/core/session-log/v1-view.d.ts.map +1 -0
- package/dist/core/session-log/v1-view.js +106 -0
- package/dist/core/session-log/v1-view.js.map +1 -0
- package/dist/core/session-log/v1.d.ts +107 -0
- package/dist/core/session-log/v1.d.ts.map +1 -0
- package/dist/core/session-log/v1.js +495 -0
- package/dist/core/session-log/v1.js.map +1 -0
- package/dist/core/session-sync/copy-store-types.d.ts +29 -0
- package/dist/core/session-sync/copy-store-types.d.ts.map +1 -0
- package/dist/core/session-sync/copy-store-types.js +2 -0
- package/dist/core/session-sync/copy-store-types.js.map +1 -0
- package/dist/core/session-sync/saved-copy-store.d.ts +5 -0
- package/dist/core/session-sync/saved-copy-store.d.ts.map +1 -1
- package/dist/core/session-sync/saved-copy-store.js +30 -4
- package/dist/core/session-sync/saved-copy-store.js.map +1 -1
- package/dist/core/turns/segments/index.d.ts +1 -0
- package/dist/core/turns/segments/index.d.ts.map +1 -1
- package/dist/core/turns/segments/index.js +1 -0
- package/dist/core/turns/segments/index.js.map +1 -1
- package/dist/core/turns/segments/work-split.d.ts +16 -0
- package/dist/core/turns/segments/work-split.d.ts.map +1 -0
- package/dist/core/turns/segments/work-split.js +59 -0
- package/dist/core/turns/segments/work-split.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/kortix.esm.min.js +33 -33
- package/dist/kortix.global.js +34 -34
- package/dist/react/opencode.d.ts +1 -0
- package/dist/react/opencode.d.ts.map +1 -1
- package/dist/react/opencode.js +2 -0
- package/dist/react/opencode.js.map +1 -1
- package/dist/react/session-transcript-subscription.d.ts +5 -1
- package/dist/react/session-transcript-subscription.d.ts.map +1 -1
- package/dist/react/session-transcript-subscription.js +8 -2
- package/dist/react/session-transcript-subscription.js.map +1 -1
- package/dist/react/sign-in-with-kortix.d.ts +1 -1
- package/dist/react/use-opencode-events/handle-event.d.ts +6 -0
- package/dist/react/use-opencode-events/handle-event.d.ts.map +1 -1
- package/dist/react/use-opencode-events/handle-event.js +5 -0
- package/dist/react/use-opencode-events/handle-event.js.map +1 -1
- package/dist/react/use-opencode-events/index.d.ts.map +1 -1
- package/dist/react/use-opencode-events/index.js +1 -0
- package/dist/react/use-opencode-events/index.js.map +1 -1
- package/dist/react/use-session-log.d.ts +52 -0
- package/dist/react/use-session-log.d.ts.map +1 -0
- package/dist/react/use-session-log.js +166 -0
- package/dist/react/use-session-log.js.map +1 -0
- package/dist/react/use-session.d.ts.map +1 -1
- package/dist/react/use-session.js +4 -0
- package/dist/react/use-session.js.map +1 -1
- package/package.json +2 -2
package/dist/kortix.global.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
"use strict";var Kortix=(()=>{var os=Object.defineProperty;var lP=Object.getOwnPropertyDescriptor;var uP=Object.getOwnPropertyNames;var pP=Object.prototype.hasOwnProperty;var dP=(e,t)=>{for(var n in t)os(e,n,{get:t[n],enumerable:!0})},gP=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of uP(t))!pP.call(e,o)&&o!==n&&os(e,o,{get:()=>t[o],enumerable:!(r=lP(t,o))||r.enumerable});return e};var mP=e=>gP(os({},"__esModule",{value:!0}),e);var t$={};dP(t$,{ABORT_REASONS:()=>Fb,ABORT_REASONS_NOT_YET_EMITTED:()=>RM,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>fs,ACTIVE_INSTANCE_COOKIE:()=>rr,ANALYTICS_UNAVAILABLE_CODE:()=>ms,ATTACHMENT_PART_REF_PREFIX:()=>s_,ApiError:()=>b,AuthError:()=>Q,BillingError:()=>$e,CONNECTION_FAULT_GRACE_MS:()=>g_,CONNECTOR_POLL_FIRST_DELAY_MS:()=>e_,CONNECTOR_POLL_INTERVAL_MS:()=>t_,CONNECTOR_POLL_WINDOW_MS:()=>n_,CONTEXT_TOOLS:()=>Bh,COST_MARKUP:()=>Qg,ConnectorApprovalPendingError:()=>$r,ConnectorCallError:()=>pn,ConnectorPageLimitError:()=>Ur,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>Wh,DEFAULT_NOTIFICATION_PREFERENCES:()=>eA,DEFAULT_TRANSCRIPT_OPTIONS:()=>Sg,DESTRUCTIVE_PHASES:()=>zb,FEATURE_DISABLED_CODE:()=>hr,FEATURE_FLAG_KEYS:()=>WP,FEATURE_NOT_SUPPORTED_CODE:()=>ps,FILE_VERBS:()=>Qe,FileExistsError:()=>$t,HeadlessAuthError:()=>It,HostBoundaryError:()=>ir,IMPERSONATION_HEADER:()=>Tm,INBOX_NOTIFICATION_KINDS:()=>Zv,INBOX_OBSERVATION_MAX_MS:()=>zo,INITIAL_SETTLED_CONNECTION:()=>TD,INSTANCE_SCOPED_ROUTES:()=>Lb,KORTIX_TRANSCRIPT_SCHEMA:()=>OA,KortixMemberError:()=>Xe,MAX_PROMPT_ATTACHMENTS_BYTES:()=>Lx,MAX_PROMPT_ATTACHMENT_BYTES:()=>ic,MAX_PROMPT_ATTACHMENT_FILES:()=>Vm,MEMORY_VERBS:()=>LE,MODEL_NOT_SERVABLE_CODE:()=>ds,NO_GROUP_ACTIVITY_TOOLS:()=>Rf,OPTIMISTIC_ABORT_MAX_MS:()=>Yo,OPTIMISTIC_COMPACTION_MAX_MS:()=>GD,OPTIMISTIC_RECEIPT_MAX_MS:()=>Ho,PERSISTED_QUERY_CACHE_VERSION:()=>b1,PLUMBING_TOOLS:()=>ab,PREVIEW_PROBE_TIMEOUT_MS:()=>xD,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>gS,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>dS,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>tf,PROVISION_IN_FLIGHT_CODE:()=>gs,PublicSessionShareError:()=>zr,RUNTIME_NOT_READY_MARKERS:()=>LM,RUNTIME_PERMISSION_CAPABILITIES:()=>$A,RUNTIME_PERMISSION_REPLIES:()=>jA,RequestTooLargeError:()=>tt,RuntimeNotReadyError:()=>Dt,SANDBOX_FS_ROOTS:()=>ko,SANDBOX_PORTS:()=>Te,SERVER_COMPACTION_REVALIDATE_MS:()=>h_,SERVER_OBSERVATION_MAX_MS:()=>Vo,SESSION_LIST_STATUS:()=>rj,SESSION_NOTICE:()=>ij,STANDALONE_TOOLS:()=>If,STREAM_OBSERVATION_MAX_MS:()=>Yt,SandboxNotReadyError:()=>or,SessionNotReadyError:()=>lt,SessionStartError:()=>Gr,TURN_END_LEDGER_LAG_MS:()=>$D,TURN_ERROR_CODES:()=>oy,WAKE_ESCALATION_COOLDOWN_MS:()=>YD,WAKE_MAX_RESTARTS:()=>zD,WAKE_NO_PROGRESS_MS:()=>VD,WIRE_ID_BACKDATE_MS:()=>bo,WIRE_ID_CLOCK_TOLERANCE:()=>Be,WIRE_ID_TIME_MASK:()=>Ee,WIRE_ID_TIME_SCALE:()=>Et,WIRE_MESSAGE_ID:()=>Jf,__getConfigResolver:()=>hP,__setConfigResolver:()=>yP,abortErrorReason:()=>IM,acceptAccountInvite:()=>Gs,acceptInvite:()=>iO,actReviewItem:()=>rp,activateConnection:()=>fa,addComputerToProject:()=>ba,addGroupMembers:()=>Eu,addMarketplaceSource:()=>Np,advanceWakeEscalation:()=>JD,allDescendantIds:()=>rb,appendPreviewToken:()=>am,approveProjectAccessRequest:()=>xi,approveTask:()=>HA,archiveProject:()=>un,assignTicket:()=>ek,attachGroupToProject:()=>Ei,authMfa:()=>fo,authUser:()=>po,authenticatedFetch:()=>E,authenticatedRequest:()=>gn,authorizePreviewUrl:()=>PD,backendApi:()=>l,bindSlackIdentity:()=>qS,bindTeamsIdentity:()=>GS,brokerProjectSecretRequest:()=>Gi,browserKeyValueStorage:()=>dD,buildInstancePath:()=>Kb,buildPresentationTemplateImageUrl:()=>AD,buildPresentationTemplatePdfUrl:()=>vD,buildPreviewAuthEndpoint:()=>im,buildPublicTemplateUrl:()=>XO,buildRuntimePresentationConversionUrl:()=>d_,buildSandboxTemplate:()=>Ja,buildScrapeFailureResults:()=>ub,buildStaticFileHealthPreviewUrl:()=>QR,buildStaticFileLocalUrl:()=>YR,buildStaticFilePreviewUrl:()=>zR,buildStaticFileServicePath:()=>Gy,buildTunnelEventStreamUrl:()=>Aj,buildWebProxyUrl:()=>tI,bulkActReviewItems:()=>op,bulkDeletePolicies:()=>pw,bulkImportPolicies:()=>dw,burstSummary:()=>oT,burstSummaryLabel:()=>sT,callConnector:()=>st,cancelAccountDeletion:()=>Xw,cancelAccountInvite:()=>Ls,cancelSandbox:()=>eO,cancelSandboxUpdate:()=>PO,cancelScheduledChange:()=>Ul,cancelSubscription:()=>Dl,checkAccessEmail:()=>OO,childMapByParent:()=>WC,claimComputer:()=>AO,claimNext:()=>fh,claimPerSeatBilling:()=>US,claimWarmProjectSession:()=>Lc,classifyPart:()=>$g,classifyPreviewProbeStatus:()=>p_,classifyPtyClose:()=>cy,classifyTurn:()=>Xh,cleanErrorMessage:()=>ZC,cleanResultSnippet:()=>lT,cleanWorkerOutput:()=>OE,clearImpersonationSession:()=>_s,clearKortixAppViewerCache:()=>T_,clearModelDefault:()=>_l,clearSessionFresh:()=>Zx,closeChangeRequest:()=>Pc,closeMilestone:()=>Ik,collectTurnParts:()=>KC,commentTicket:()=>nk,commitSessionChanges:()=>wc,compactionExpiryAtMs:()=>WD,compactionTurnInfo:()=>iT,compareMessagesForDisplay:()=>$C,completeInFlight:()=>yh,completeSlackInstall:()=>Yl,completeTeamsInstall:()=>Ql,composerSelectableAgents:()=>fm,computeStatusFromPart:()=>Yg,configureAutoTopup:()=>Kl,configureKortix:()=>gr,confirmCheckoutSession:()=>Ml,connectEmail:()=>ou,connectSlack:()=>Vl,connectionFromHealth:()=>CD,connectionIsFaulted:()=>ID,connectionSharedWithEveryone:()=>fx,connectorConnect:()=>Bm,connectorFinalize:()=>Wm,connectorHeadline:()=>rD,contextLabelForTool:()=>bT,contextToolSummary:()=>LI,contextToolTrigger:()=>NI,convertPresentationToGoogleSlides:()=>uv,convertRuntimePresentation:()=>kD,copyFile:()=>Kn,costExportUrl:()=>Gl,countLiveInboxPrompts:()=>FD,countReviewItemsBySegment:()=>dv,createAccount:()=>Is,createAccountAuditWebhook:()=>Cp,createAccountSecretResource:()=>Ji,createAccountToken:()=>hp,createApp:()=>Gp,createAppAccessSession:()=>Xp,createAppDeployment:()=>Zp,createAppToken:()=>Hp,createAppVolume:()=>yd,createAppVolumeSnapshot:()=>Pd,createArtifactKind:()=>NT,createAssignment:()=>Xu,createAuditWebhook:()=>qw,createBackup:()=>lO,createCheckoutSession:()=>El,createConnector:()=>Ma,createConnectorLinkInfoCache:()=>eD,createFile:()=>Nn,createGatewayKey:()=>Su,createGroup:()=>Ru,createHttpSessionSyncController:()=>k_,createInstance:()=>SO,createKortix:()=>ph,createKortixPty:()=>og,createKortixSession:()=>ho,createMarketplaceInstallSession:()=>Tv,createMilestone:()=>kk,createModelVisibility:()=>rP,createOAuthClient:()=>Hu,createPerSeatCheckout:()=>$S,createPersistedQueryCache:()=>pD,createPolicy:()=>cw,createPortalSession:()=>Ol,createProject:()=>Zs,createProjectAgent:()=>dk,createProjectCliToken:()=>Sp,createProjectRepo:()=>ei,createProjectResourceGrant:()=>ji,createProjectSession:()=>at,createProjectSkill:()=>ii,createProjectTrigger:()=>cl,createPromptAttachmentController:()=>xg,createRole:()=>Fu,createSSEStream:()=>kj,createSandbox:()=>VM,createSandboxShare:()=>lp,createSandboxTemplate:()=>Ya,createSavedCopyStore:()=>cS,createScimToken:()=>yw,createServiceAccountApi:()=>Fw,createSessionPrompt:()=>_n,createSessionPublicShare:()=>$c,createSessionQueue:()=>gh,createSessionReminder:()=>dp,createSsoGroupMapping:()=>Cw,createTask:()=>GA,createTicket:()=>XA,createTunnelEventStream:()=>Rj,createWarmSessionPool:()=>hj,currentSavedCopyStore:()=>Ic,declineAccountInvite:()=>Bs,declineInvite:()=>aO,deleteAccountImmediately:()=>Jw,deleteAccountSecretResource:()=>ta,deleteApp:()=>Wp,deleteAppDeployment:()=>sd,deleteAuditWebhook:()=>Bw,deleteBackup:()=>pO,deleteConnector:()=>Da,deleteConnectorCredential:()=>Na,deleteCredential:()=>jk,deleteDriveFile:()=>zv,deleteEnv:()=>tg,deleteFile:()=>gt,deleteGatewayBudget:()=>Pu,deleteGitHubInstallation:()=>hi,deleteGroup:()=>Cu,deleteInstance:()=>wO,deleteKortixProject:()=>xk,deleteMilestone:()=>Tk,deleteOAuthClient:()=>Yu,deletePersonalProjectSecret:()=>Yi,deletePolicy:()=>uw,deleteProjectAgent:()=>mk,deleteProjectProviderOAuth:()=>Wi,deleteProjectResourceGrant:()=>$i,deleteProjectSecret:()=>Vi,deleteProjectSession:()=>Xc,deleteProjectTrigger:()=>ul,deletePromptAttachment:()=>vt,deleteRole:()=>Ku,deleteSandboxTemplate:()=>Xa,deleteServiceAccountApi:()=>Nw,deleteSessionPrompt:()=>Wc,deleteSessionReminder:()=>Qr,deleteSessionReminders:()=>mp,deleteSsoGroupMapping:()=>Tw,deleteSsoProvider:()=>Rw,deleteTask:()=>VA,deleteTicket:()=>rk,describeAccountInvite:()=>qs,describeConnectorTool:()=>Er,destroyAppMachine:()=>dd,destroyAppVolume:()=>bd,detachGroupFromProject:()=>Oi,detectLocalhostUrls:()=>Ly,directSubsessions:()=>cj,disableServiceAccountApi:()=>Lw,disconnectEmail:()=>su,disconnectGitHubApp:()=>cD,disconnectSlack:()=>Jl,discoverConnectionOAuth2:()=>_x,discoverConnectionOAuth2Resource:()=>Px,discoverConnectorAuth:()=>Oa,discoverLocalSandbox:()=>XM,dismissDriveConflict:()=>Kv,downloadAccountAudit:()=>YO,downloadDriveFile:()=>Gv,dropClientForUrl:()=>Wk,dropPublicClientForUrl:()=>zk,editQueued:()=>Ph,editSessionPrompt:()=>Hc,enqueue:()=>mh,ensurePmSession:()=>uk,ensurePreviewSessionCookie:()=>u_,ensureProjectConnectorConnection:()=>yx,ensureSandbox:()=>Vb,ensureWarmProjectSession:()=>Fc,env:()=>iy,exchangeCode:()=>co,execInApp:()=>md,exportAccountAudit:()=>Rp,extractGatewayErrorDetails:()=>ge,extractInstanceRoute:()=>Vt,extractSkillBaseDir:()=>Mb,extractSkillContent:()=>VE,extractSkillFiles:()=>Eb,extractWorkerPreview:()=>jE,failInFlight:()=>hh,fallbackBusyRowAfterTurnId:()=>pE,familyForTool:()=>qo,featureDisabledKey:()=>cs,featureFlags:()=>Gd,fetchAccountStateWithToken:()=>OS,fetchAccountsWithToken:()=>BP,fetchAttachmentPart:()=>gD,fetchCostExportCsv:()=>KS,fetchKortixAppViewer:()=>pm,fetchProjectArchive:()=>oc,fetchProjectFileRaw:()=>Fx,fetchProjectsForAccountWithToken:()=>ex,fetchSessionAttachment:()=>Kd,fileDownloadRequest:()=>Sy,filePhase:()=>FE,fileVerb:()=>UE,files:()=>Cy,finalizeAppArtifact:()=>Zr,finalizeConnectorSetupLink:()=>NO,findActiveTranscriptShare:()=>fS,findFiles:()=>Fn,findLastTextPart:()=>qC,findSessionAttachments:()=>fA,findText:()=>Ln,fireProjectTrigger:()=>dl,fixSandboxWithAgent:()=>za,flattenModels:()=>eP,flattenThought:()=>zT,forkAppVolume:()=>Sd,formatBillingErrorForUI:()=>us,formatCost:()=>IE,formatDuration:()=>AE,formatJsonFailureOutput:()=>eT,formatMessageDay:()=>eE,formatMessageExact:()=>tE,formatOpenCodeRuntimeError:()=>GM,formatRawOutput:()=>cT,formatRuntimeError:()=>Hb,formatTokens:()=>CE,formatTranscript:()=>Sh,freshSendHint:()=>fE,generateSessionId:()=>dh,getAccount:()=>Cs,getAccountBranding:()=>Es,getAccountDeletionStatus:()=>Yw,getAccountState:()=>vl,getAccountStateMinimal:()=>Al,getActiveInstanceIdFromCookie:()=>Gb,getAdminBootModes:()=>av,getAdminProviderAnalytics:()=>rv,getAdminProviderDistribution:()=>ev,getAdminProviderFallback:()=>sv,getAdminRole:()=>Zw,getAgentCardLabel:()=>Yh,getAgentConfig:()=>IS,getAgentPersona:()=>fk,getAllVersions:()=>hO,getAnsweredQuestionParts:()=>BC,getApp:()=>Xr,getAppAccess:()=>zp,getAppAuthEnv:()=>Vp,getAppDeployment:()=>td,getAppDeploymentLogs:()=>nd,getApprovalLink:()=>Cv,getAuthToken:()=>St,getAuthTokenWithRetry:()=>ux,getAutoTopupSettings:()=>Nl,getAutoTopupSetupStatus:()=>jS,getBillingCreditBreakdown:()=>Il,getBillingTierConfigurations:()=>Tl,getBillingTransactionsSummary:()=>Rl,getBillingUsageHistory:()=>Cl,getChangeRequest:()=>fc,getChangeRequestDiff:()=>yc,getChangeRequestMergePreview:()=>hc,getChildSessionError:()=>eC,getChildSessionId:()=>Mg,getChildSessionToolParts:()=>tC,getClient:()=>He,getClientForUrl:()=>be,getConnectStatus:()=>Fa,getConnectionOAuth2Application:()=>bx,getConnectionOAuth2Status:()=>Ax,getConnectionPolicies:()=>kx,getConnectorCatalog:()=>wt,getConnectorConfig:()=>Ca,getConnectorPolicies:()=>Ra,getConnectorSetupLink:()=>FO,getCostSummary:()=>NS,getCurrentInstanceIdFromPathname:()=>qb,getCurrentInstanceIdFromWindow:()=>EM,getCurrentProject:()=>dg,getDefaultAccountState:()=>wl,getDiagnostics:()=>sC,getDirectory:()=>zh,getDiscoverConnector:()=>jr,getDiscoverIntegration:()=>Mx,getDriveFileUrl:()=>wd,getEmailInstallation:()=>nu,getEmailMode:()=>ru,getEnterpriseDemo:()=>Hw,getFileStatus:()=>Un,getFileWithDir:()=>Tg,getFilename:()=>Vh,getFolderAccess:()=>$v,getFullChangelog:()=>Yb,getGatewayBreakdown:()=>fu,getGatewayBudgets:()=>bu,getGatewayErrors:()=>hu,getGatewayKeys:()=>xu,getGatewayLog:()=>du,getGatewayOverview:()=>gu,getGatewayRoutingPolicy:()=>au,getGatewaySeries:()=>mu,getGatewaySessions:()=>yu,getGitHubAppStatus:()=>oD,getGitHubInstallation:()=>li,getGoogleAuthUrl:()=>lv,getGroup:()=>ku,getHiddenToolParts:()=>YI,getImpersonationSession:()=>Om,getInvite:()=>sO,getJustavpsServerTypes:()=>xO,getKortixProject:()=>bk,getKortixProjectBySession:()=>_k,getKortixPtyWebSocketUrl:()=>ag,getLatestSandboxVersion:()=>yO,getMaintenanceConfig:()=>WO,getManagedGitBackend:()=>bi,getManagedGitStatus:()=>QP,getMarketplaceCatalogItem:()=>Up,getMarketplaceCatalogItemFile:()=>Fp,getMfaRequired:()=>bw,getMilestone:()=>vk,getModelDefaults:()=>hl,getNotificationPreferences:()=>Id,getOAuthClient:()=>Wu,getOAuthConsentRequest:()=>$O,getOpenCodeConfigInvalidError:()=>$M,getPartText:()=>HI,getPatPolicy:()=>jw,getPermissionForTool:()=>iC,getProject:()=>on,getProjectActivity:()=>yk,getProjectCommit:()=>uc,getProjectCommitDiff:()=>pc,getProjectDetail:()=>sn,getProjectDrive:()=>jv,getProjectFileHistory:()=>dc,getProjectGitToken:()=>Js,getProjectLlmCatalog:()=>an,getProjectLlmCatalogProviders:()=>VP,getProjectModelAccess:()=>vn,getProjectModelPicker:()=>cn,getProjectSandboxHealth:()=>dn,getProjectSandboxProviderTransition:()=>XP,getProjectSession:()=>bn,getProjectSessionConfigState:()=>Jc,getProjectSessionScope:()=>tl,getProrationPreview:()=>Fl,getProviders:()=>WM,getProxyBaseUrl:()=>XR,getPublicClientForUrl:()=>Vk,getPublicMarketplaceItem:()=>EO,getPublicMarketplaceItemFile:()=>MO,getPublicSessionShare:()=>vv,getPublicSessionShareMessages:()=>Av,getPublicShareByToken:()=>GO,getPublicTemplate:()=>JO,getQuestionForTool:()=>aC,getReferralCode:()=>XS,getReferralStats:()=>ew,getRetryInfo:()=>TE,getRetryMessage:()=>EE,getReviewItem:()=>tp,getRolePermissions:()=>$u,getRoleUsage:()=>Uu,getRuntimeConfigInvalidError:()=>Wo,getSSHConnection:()=>gO,getSandbox:()=>HM,getSandboxById:()=>zM,getSandboxPortUrl:()=>BM,getSandboxProvisionStatus:()=>kO,getSandboxProvisionStreamUrl:()=>RO,getSandboxUpdateStatus:()=>fO,getSandboxUrl:()=>nm,getSandboxUrlForExternalId:()=>Fe,getSecretSetupLink:()=>KO,getServerHealth:()=>Ro,getServiceLogs:()=>Nk,getSessionAudit:()=>Nc,getSessionCost:()=>RE,getSessionCostRecord:()=>wn,getSessionDrives:()=>Af,getSessionHealth:()=>yg,getSessionMessageAuthors:()=>sl,getSessionModelUsage:()=>il,getSessionOpenBundle:()=>yS,getSessionOversight:()=>xw,getSessionParticipants:()=>Ec,getSessionPolicy:()=>Ew,getSessionPreviewCandidates:()=>Dc,getSessionProviderSecretPool:()=>sa,getSessionTranscript:()=>Kc,getSessionTranscriptSync:()=>qc,getSessionTurn:()=>Gc,getSessionWatch:()=>Mc,getShellModePart:()=>hE,getSlackChannelFile:()=>Zl,getSlackInstallation:()=>Hl,getSlackManifest:()=>Xl,getSlackMode:()=>zl,getSsoProvider:()=>ww,getStaticFileHealthPath:()=>By,getSupabaseAccessToken:()=>Rr,getSupabaseAccessTokenWithRetry:()=>Gm,getTask:()=>NA,getTaskStatus:()=>qA,getTemplate:()=>Ev,getTicket:()=>YA,getToolInfo:()=>nC,getToolPrimaryArg:()=>Oo,getTranscriptFilename:()=>wh,getTurnCost:()=>kE,getTurnError:()=>xE,getTurnErrorDetails:()=>wE,getTurnErrorRawText:()=>SE,getTurnStatus:()=>vE,getUsageRollup:()=>ql,getUserRolesWithToken:()=>VO,getVersionDiff:()=>gc,getWebPushPublicKey:()=>Td,getWorkingState:()=>_E,grantAccountSecretResource:()=>na,grantSandboxProjectAccess:()=>rO,grantSecretToAgent:()=>TS,groupMessagesIntoTurns:()=>FC,groupShowSegments:()=>oE,groupSteps:()=>Vg,hasDiffs:()=>ME,hasLocalhostUrls:()=>WR,hasPreviewTarget:()=>qy,hasRetryingAssistantTurn:()=>VC,heartbeatGapEvent:()=>gy,holdSessionPrompts:()=>Yc,humanizeReviewActionPath:()=>ap,humanizeSearchQuery:()=>Hn,humanizeToolName:()=>Dg,impersonationHeaders:()=>Ps,importSsoProviderFromMetadata:()=>Aw,inboxObservationSupersedes:()=>UD,initialWakeEscalationState:()=>lm,inputPath:()=>De,installTemplate:()=>Mv,interruptSessionPrompt:()=>Vc,invalidateTokenCache:()=>Ir,inviteAccountMember:()=>Us,inviteProjectMember:()=>ki,inviteRepoCollaborator:()=>Qs,isAbortError:()=>nr,isAdminBypassEnabled:()=>Um,isAgentPart:()=>KI,isAppRouteUrl:()=>Fy,isAttachment:()=>VI,isAttachmentPartRef:()=>i_,isAuthFailure:()=>_t,isBillingError:()=>ls,isCompactionPart:()=>qI,isConfigured:()=>mr,isContextTool:()=>FI,isDestructivePhase:()=>mO,isEmptyConversation:()=>I_,isEmptyShowPart:()=>eo,isErrorOutput:()=>zC,isExternalUrl:()=>oI,isFeatureDisabledError:()=>as,isFilePart:()=>Eg,isImpersonationSessionLive:()=>Em,isInstanceDetailPath:()=>CM,isInstanceScopedAppPath:()=>Nb,isInternalLocalhostUrl:()=>eI,isInvisibleActivityPart:()=>jd,isInviteSent:()=>rx,isLastUserMessage:()=>bE,isLegacyMigratedSession:()=>b_,isManagedGithubProject:()=>HP,isNoGroupActivityTool:()=>Dd,isOfferedModel:()=>ns,isOpenCodeConfigInvalidError:()=>UM,isPaintableSavedCopy:()=>kc,isPatchPart:()=>BI,isPersistableQueryKey:()=>uD,isPreviewUrl:()=>ZR,isProxiableLocalhostUrl:()=>Wy,isQuestionTool:()=>oA,isReasoningPart:()=>Pe,isRetryableTurnError:()=>ob,isRuntimeConfigInvalidError:()=>Bb,isRuntimeNotReadyResponse:()=>Wb,isRuntimeReady:()=>fg,isRuntimeStartingError:()=>qM,isSandboxNotReadyError:()=>zt,isSelectableAgent:()=>no,isServerReachable:()=>gg,isSessionAttachmentRef:()=>lA,isSessionFresh:()=>Ac,isSessionStartError:()=>wS,isShellActivityTool:()=>rA,isShellMode:()=>vb,isShortOutput:()=>DE,isShowContentUnavailable:()=>tA,isShowPayloadEmpty:()=>kn,isSnapshotPart:()=>GI,isStandaloneActivityTool:()=>$d,isStepPart:()=>WI,isSubdomainPreviewUrl:()=>ar,isTextPart:()=>_e,isToolPart:()=>J,isToolPartHidden:()=>QI,isTurnErrorCode:()=>DA,isUnderSandboxRoot:()=>ug,isWebProxyUrl:()=>rI,isWireIdAheadOf:()=>ey,kortixAppViewerToken:()=>E_,kortixBinding:()=>M_,kortixPty:()=>py,kortixToken:()=>dm,leaveAccount:()=>Vs,linkGitHubInstallation:()=>fi,linkRepository:()=>ai,listAccountAudit:()=>Ap,listAccountAuditWebhooks:()=>Ip,listAccountInvites:()=>Fs,listAccountMembers:()=>$s,listAccountResourceGrants:()=>iw,listAccountSecretResources:()=>Xi,listAccountSessions:()=>Ow,listAccountTokens:()=>yp,listAccounts:()=>Rs,listActions:()=>gw,listAdminSandboxes:()=>tv,listAgentIdentities:()=>Du,listAllConnections:()=>ua,listAppAgents:()=>Yp,listAppDeployments:()=>ed,listAppMachines:()=>ad,listAppVolumeSnapshots:()=>_d,listAppVolumes:()=>fd,listApps:()=>qp,listAssignments:()=>Qu,listAuditEvents:()=>Ww,listAuditWebhooks:()=>Kw,listBackups:()=>cO,listBillingTransactions:()=>kl,listChangeRequests:()=>mc,listChannelBindings:()=>zS,listColumns:()=>ok,listConnectSections:()=>Tx,listConnectToolkits:()=>Cx,listConnections:()=>la,listConnectorAccounts:()=>Mr,listConnectorTools:()=>Tr,listConnectors:()=>Sa,listCostByProject:()=>LS,listCredentialEvents:()=>Mk,listCredentials:()=>Ek,listDiscoverConnectors:()=>Dr,listDiscoverIntegrations:()=>Ex,listDiscoverSections:()=>Ua,listDriveConflicts:()=>Nv,listDriveFiles:()=>qv,listDriveFolder:()=>vf,listDriveVersions:()=>Yv,listEnv:()=>Zd,listFeaturedMarketplaces:()=>$p,listFields:()=>ik,listFiles:()=>Lt,listFolderPrincipals:()=>Lv,listGatewayLogs:()=>pu,listGitHubInstallations:()=>ui,listGitHubRepositories:()=>di,listGitHubRepositoryBranches:()=>gi,listGroupMembers:()=>Tu,listGroupProjectGrants:()=>rw,listGroups:()=>Au,listKortixProjectSessions:()=>Pk,listKortixProjects:()=>hk,listKortixPty:()=>rg,listLinkableGitHubInstallations:()=>pi,listManagedGitRepositories:()=>_i,listMarketplaceCatalogItems:()=>Dp,listMarketplaceSources:()=>Lp,listMarketplaces:()=>jp,listMemberGroups:()=>ow,listMemberProjectAccess:()=>sw,listMilestoneEvents:()=>Ak,listMilestones:()=>wk,listMyAccountInvites:()=>Ks,listNotifications:()=>kd,listOAuthClients:()=>Bu,listOAuthGrants:()=>_p,listPendingApprovals:()=>Ui,listPendingProjectInvites:()=>Ri,listPermissions:()=>Zu,listPipedreamApps:()=>ja,listPipedreamSections:()=>$a,listPolicies:()=>aw,listProjectAccess:()=>wi,listProjectAccessRequests:()=>Pi,listProjectAgentIdentities:()=>ju,listProjectAgents:()=>pk,listProjectAudit:()=>kp,listProjectBranches:()=>cc,listProjectCliTokens:()=>xp,listProjectCommits:()=>lc,listProjectDirectory:()=>tc,listProjectFiles:()=>ec,listProjectGroupGrants:()=>Ti,listProjectPolicies:()=>Ga,listProjectProviderOAuth:()=>Bi,listProjectReminders:()=>fp,listProjectResourceGrants:()=>Di,listProjectSandboxTemplates:()=>Wa,listProjectSandboxes:()=>Za,listProjectSecrets:()=>Ni,listProjectSessions:()=>it,listProjectSessionsPage:()=>Cc,listProjectSnapshots:()=>Ha,listProjectTriggerEventApps:()=>ml,listProjectTriggerEventTypes:()=>gl,listProjectTriggers:()=>al,listProjects:()=>ot,listProjectsForAccount:()=>Ys,listPublicMarketplaceItems:()=>CO,listPublicMarketplaces:()=>TO,listReferrals:()=>tw,listReviewItems:()=>ep,listRoles:()=>Ou,listSandboxProjectMembers:()=>nO,listSandboxShares:()=>cp,listSandboxes:()=>QM,listScimTokens:()=>fw,listServiceAccountsApi:()=>Uw,listServiceTemplates:()=>Lk,listServices:()=>Fk,listSessionConnectRequests:()=>Ix,listSessionCosts:()=>Wl,listSessionDrives:()=>Jv,listSessionPrompts:()=>Bc,listSessionProviderSecretPools:()=>ia,listSessionPublicShares:()=>jc,listSessionReminders:()=>pp,listSessionsNeedingInput:()=>Fi,listSignedInDevices:()=>Rv,listSsoGroupMappings:()=>Iw,listTaskEvents:()=>KA,listTasks:()=>LA,listTemplates:()=>ck,listTicketEvents:()=>QA,listTickets:()=>zA,loadHttpSessionHistory:()=>A_,loadPreviewUrlTemplate:()=>Ge,looksLikeError:()=>Lg,looksLikeHtml:()=>gT,looksLikeJsonPayload:()=>aT,makeDriveFolder:()=>Hv,mapApiReviewItem:()=>wv,markInstanceError:()=>vO,markNotificationsRead:()=>Rd,markSessionFresh:()=>hn,maxWireIdClock:()=>Yd,memoryRelPath:()=>NE,mergeBurstSteps:()=>WT,mergeChangeRequest:()=>_c,messageCreatedAt:()=>YT,messageTime:()=>xb,migrateAdminSandboxProvider:()=>ov,mintWireMessageId:()=>_o,mintWireMessageIdAbove:()=>Qd,mkdir:()=>Gt,modelInDefaultView:()=>oP,modelRefToKey:()=>K_,moveDriveFile:()=>Vv,narrateFailedStep:()=>Hg,narrateStep:()=>Wg,narrationToolName:()=>er,narrowChatEvent:()=>my,newestWireIdClock:()=>ty,nextConnectorPollDelay:()=>nD,normalizeActivityToolName:()=>ue,normalizeAppPathname:()=>DM,normalizeExternalInput:()=>sI,normalizeName:()=>V,normalizeToolName:()=>Og,notifyHostSignal:()=>P_,openChangeRequest:()=>bc,openEventStream:()=>wo,openStressTestStream:()=>QO,paginateConnector:()=>qa,parseBillingError:()=>tn,parseEmbeddedFailure:()=>uT,parseFlagOverride:()=>hA,parseJsonFailure:()=>ib,parseLocalhostUrl:()=>Wn,parseMemoryView:()=>KE,parseOpenCodeErrorPayload:()=>jM,parsePresentationOutput:()=>BE,parseProxyHop:()=>mg,parseQuestionAnswersFromOutput:()=>WE,parseReadOutput:()=>HE,parseRuntimeErrorPayload:()=>tm,parseScrapeInputUrls:()=>lb,parseScrapeOutput:()=>pb,parseSubdomainUrl:()=>bg,parseTaskRows:()=>$E,parseWebProxyUrl:()=>nI,parseWebSearchOutput:()=>Gg,partOutcome:()=>Ng,patchKortixProject:()=>Sk,patchVerb:()=>GE,pickerProviderList:()=>Z_,pipedreamConnect:()=>Ea,pipedreamConnectConnection:()=>Pa,pipedreamFinalize:()=>Ka,pipedreamFinalizeConnection:()=>xa,platformConfig:()=>k,pollConnectionOAuth2DeviceAuthorization:()=>vx,pollProjectProviderOAuth:()=>kr,previewGatewayRoute:()=>uu,previewMfaRequired:()=>_w,previewSlackIdentity:()=>BS,previewTeamsIdentity:()=>WS,probeEffectivePermission:()=>qu,probeEffectivePermissions:()=>Gu,probePreviewPort:()=>SD,projectArchiveRequest:()=>sc,projectCompacting:()=>BD,projectConfigAgentsToOpenCodeAgents:()=>L_,projectConfigAgentsToRuntimeAgents:()=>mm,projectSessionConnection:()=>RD,projectSessionForRuntimeId:()=>lj,projectSessionStartSeed:()=>SS,projectWorking:()=>LD,provisionProject:()=>ti,provisionProjectStream:()=>YP,provisionProjectWithToken:()=>tx,proxyLocalhostUrl:()=>hg,proxyUrlToInternal:()=>JR,purchaseCredits:()=>Ll,putConnectionOAuth2Application:()=>hx,rawErrorText:()=>Ag,reactivateSandbox:()=>tO,reactivateSubscription:()=>jl,readBlob:()=>Kt,readDriveFile:()=>Bv,readFile:()=>Nt,readKortixMember:()=>Zo,readProjectFile:()=>rc,reasoningIsRunning:()=>yb,rebuildProjectSnapshot:()=>Va,reconcileConnection:()=>pa,reconcileMemberConnection:()=>da,reconcileServices:()=>qk,recordPlatformLogout:()=>jO,recoverLinkResults:()=>Lo,refreshReferralCode:()=>JS,refreshSession:()=>Ct,registerAppArtifact:()=>Jr,registerConnectionOAuth2Client:()=>xx,registerDeviceToken:()=>vd,registerService:()=>Gk,registerWebPushSubscription:()=>Ed,rejectProjectAccessRequest:()=>Si,relativizePath:()=>oC,reloadProjectSessionConfig:()=>Zc,reloadProjectSessionConfigStream:()=>el,removeAccountAuditWebhook:()=>Ep,removeAccountBrandingAsset:()=>Ds,removeAccountMember:()=>Ws,removeGroupMember:()=>Mu,removeKortixPty:()=>ig,removeMarketplaceSource:()=>Kp,removeQueued:()=>_h,renameConnection:()=>ha,renameFile:()=>Gn,renameSandbox:()=>YM,reopenChangeRequest:()=>xc,reopenMilestone:()=>Ck,reorderQueued:()=>xh,replaceColumns:()=>sk,replaceFields:()=>ak,replaceProjectRepository:()=>ci,replaceTemplates:()=>lk,requestAccountDeletion:()=>Qw,requestChangesOnChangeRequest:()=>Sc,requestProjectAccess:()=>nx,requestProjectConnector:()=>Op,requestProjectSecret:()=>Mp,requestTopUp:()=>DS,requireKortixMember:()=>j_,resendAccountInvite:()=>Ns,resendPendingProjectInvite:()=>Ci,resetAccountBranding:()=>js,resetClient:()=>Hk,resetGatewayRoutingPolicy:()=>lu,resetPassword:()=>lo,resetPublicClient:()=>Yk,resetSandboxUpdateStatus:()=>_O,resolveApproval:()=>Li,resolveComposerAgent:()=>F_,resolveComposerModel:()=>aP,resolveConnectorStart:()=>tD,resolveModelDefault:()=>iP,resolvePublicShareUrl:()=>mS,resolveScrapeResults:()=>mT,resolveWorkingTurn:()=>yE,resolvedPlan:()=>MS,restartAppMachine:()=>pd,restartProjectSession:()=>Pn,restartSandbox:()=>JM,restoreAppVolume:()=>xd,restoreBackup:()=>uO,restoreDriveVersion:()=>Qv,retryAccountSecretResource:()=>ea,retryFailed:()=>bh,retrySessionPrompt:()=>zc,revealCredential:()=>Dk,reviewItemTarget:()=>pv,reviewSegmentForStatus:()=>Pf,reviewVerdictForStatus:()=>gv,revokeAccountSecretResourceGrant:()=>ra,revokeAccountSession:()=>Dw,revokeAccountToken:()=>bp,revokeAssignment:()=>Ju,revokeConnection:()=>ma,revokeGatewayKey:()=>wu,revokeOAuthGrant:()=>Pp,revokePendingProjectInvite:()=>Ii,revokeProjectAccess:()=>Ai,revokeProjectCliToken:()=>wp,revokeSandboxProjectAccess:()=>oO,revokeSandboxShare:()=>up,revokeScimToken:()=>hw,revokeSessionPublicShare:()=>Uc,rewriteLocalhostUrl:()=>Ye,rollbackApp:()=>id,rootRuntimeSession:()=>__,rotateAccountSecretResource:()=>Zi,rotateOAuthClientSecret:()=>zu,runConnector:()=>Fr,runGatewayPlayground:()=>vu,runProjectProviderOAuthFlow:()=>ax,runtimeSessionsOf:()=>Qo,runtimeSupports:()=>Oy,sanitizePtyChunk:()=>uy,saveGitHubInstallation:()=>mi,savedCopyEmptyRoot:()=>R_,scaleApp:()=>gd,scheduleDowngrade:()=>$l,searchConnectorTools:()=>ca,searchProjectFiles:()=>nc,segmentTurn:()=>nE,selectableProjectAgents:()=>_A,sendMagicLink:()=>so,sendReferralEmails:()=>nw,serverCompactionRevalidateAtMs:()=>HD,serviceAction:()=>Kk,sessionConnectionLabel:()=>sj,sessionListStatus:()=>oj,sessionModelPin:()=>ol,sessionParentId:()=>pS,sessionPromptActions:()=>_S,sessionStartKey:()=>AS,setAccountSecretResourceAccess:()=>oa,setActiveInstanceCookie:()=>MM,setAdminBootModes:()=>cv,setAdminBypass:()=>$m,setAdminProviderDistribution:()=>nv,setAdminProviderFallback:()=>iv,setAgentScope:()=>Pl,setBootstrapAuthToken:()=>lx,setCachedAuthToken:()=>cx,setConnectionPolicies:()=>Rx,setConnectorAuthorizationStrategy:()=>Aa,setConnectorCredential:()=>La,setConnectorCredentialMode:()=>va,setConnectorName:()=>Ta,setConnectorPolicies:()=>Ia,setConnectorSecretBinding:()=>Ox,setConnectorSensitive:()=>ka,setDefaultConnection:()=>ya,setEnterpriseDemo:()=>Vw,setEnv:()=>eg,setGatewayBudget:()=>_u,setGatewayRoutingPolicy:()=>cu,setGitHubAppFromExisting:()=>iD,setGitHubAppPat:()=>aD,setImpersonationSession:()=>IP,setMaintenanceConfig:()=>HO,setMemberSuperAdmin:()=>mw,setMfaRequired:()=>Pw,setModelDefault:()=>bl,setPersonalProjectSecret:()=>zi,setProjectModelAccess:()=>An,setProjectModelEnablement:()=>kS,setProjectOnboardingComplete:()=>si,setProjectOnboardingProfile:()=>ZP,setProjectPolicies:()=>Ba,setProjectSecretStrategy:()=>qi,setProjectSessionModel:()=>rl,setProjectSessionScope:()=>nl,setProjectSessionSharing:()=>Tc,setProjectTriggersActivation:()=>pl,setSavedCopyStore:()=>lS,setSessionOversight:()=>Sw,setSessionProviderSecretPool:()=>aa,setSessionWatch:()=>Oc,settleSessionConnection:()=>ED,setupSSH:()=>dO,shareConnection:()=>_a,shareFolder:()=>Uv,shellActivityGroupLabel:()=>sA,shellExitCode:()=>Zg,shouldAttachImpersonation:()=>Dm,shouldHideResponsePart:()=>PE,shouldShowToolPart:()=>Hh,shouldSuppressWorkingTurnBusy:()=>lE,showGroupItems:()=>aE,showTurnBusyIndicator:()=>zg,signInWithPassword:()=>oo,signInWithProvider:()=>ao,signInWithSso:()=>mo,signOut:()=>yo,signOutDevice:()=>Iv,signUp:()=>ro,skillDocumentPath:()=>ZE,skillInputDir:()=>QE,sortSessions:()=>HC,splitUserParts:()=>zI,startApp:()=>rd,startAppMachine:()=>ld,startConnectionOAuth2Authorization:()=>Sx,startConnectionOAuth2DeviceAuthorization:()=>wx,startConnectorSetupLink:()=>LO,startGitHubAppManifest:()=>sD,startProjectProviderOAuth:()=>Ar,startProjectSession:()=>Le,startProjectSessionOrThrow:()=>yl,startSessionWithToken:()=>BO,startTask:()=>WA,stepLabel:()=>Kg,stopApp:()=>od,stopAppMachine:()=>ud,stopProjectSession:()=>xn,stopSandbox:()=>ZM,storeGitHubUserToken:()=>yi,stripAnsi:()=>lC,stripInstancePrefix:()=>TM,stripTrailingSlashes:()=>ee,submitAccessRequest:()=>DO,submitDemoRequest:()=>zO,submitOAuthConsent:()=>UO,submitReviewItem:()=>np,submitSecretSetupLink:()=>qO,subscribeToImpersonation:()=>CP,supabaseClient:()=>qP,syncConnectors:()=>wa,syncSubscription:()=>FS,systemReload:()=>Xk,toDaemonPath:()=>ze,toInstanceAwarePath:()=>OM,toInternalUrl:()=>Hy,toSandboxAbsolutePath:()=>Ft,toToolView:()=>xC,toWorkspaceRelative:()=>pg,toolInfo:()=>Do,toolKind:()=>te,toolViewModel:()=>$b,triggerSandboxUpdate:()=>bO,triggersRequest:()=>ay,turnEndCause:()=>y_,turnEndNotice:()=>qD,turnHasSteps:()=>GC,turnIsConfirmedActive:()=>dE,turnRendersQueued:()=>gE,turnRetryLabel:()=>aj,unassignTicket:()=>tk,unregisterDeviceToken:()=>Ad,unregisterWebPushSubscription:()=>Md,unshareFolder:()=>Fv,unwrapError:()=>pe,updateAccountAuditWebhook:()=>Tp,updateAccountBranding:()=>Ms,updateAccountMemberRole:()=>Hs,updateAccountName:()=>Ts,updateAgentConfig:()=>CS,updateApp:()=>Bp,updateAppAccess:()=>Qp,updateAppVolume:()=>hd,updateAuditWebhook:()=>Gw,updateChangeRequest:()=>vc,updateChannelBinding:()=>YS,updateConnectionCredential:()=>ga,updateEmailPolicy:()=>iu,updateExperimentalFeature:()=>ri,updateFeatureFlag:()=>ni,updateGroup:()=>Iu,updateKortixPty:()=>sg,updateMilestone:()=>Rk,updateNotificationPreferences:()=>Cd,updateOAuthClient:()=>Vu,updatePassword:()=>uo,updatePatPolicy:()=>$w,updatePolicy:()=>lw,updateProject:()=>ln,updateProjectAccess:()=>vi,updateProjectAgent:()=>gk,updateProjectDefaultAgent:()=>Sl,updateProjectGroupGrant:()=>Mi,updateProjectSandboxProvider:()=>oi,updateProjectSession:()=>Qc,updateProjectTrigger:()=>ll,updateRole:()=>Lu,updateRolePermissions:()=>Nu,updateSandboxTemplate:()=>Qa,updateSessionPolicy:()=>Mw,updateSessionReminder:()=>Yr,updateSessionReminders:()=>gp,updateTask:()=>BA,updateTemplateWarmPool:()=>JP,updateTicket:()=>JA,updateTicketStatus:()=>ZA,updateUserMetadata:()=>go,uploadAccountBrandingAsset:()=>Os,uploadAppArtifactArchive:()=>Jp,uploadConnectorAttachment:()=>Or,uploadDriveFile:()=>Wv,uploadFile:()=>qt,uploadNativeFile:()=>vy,uploadPromptAttachment:()=>yn,uploadSessionAttachment:()=>Nd,uploadSlackChannelFile:()=>eu,uploadTimeoutMsForBytes:()=>jt,upsertCredential:()=>Ok,upsertProjectGitCredential:()=>Hi,upsertProjectSecret:()=>Ki,upsertSsoProvider:()=>vw,validateProjectManifest:()=>Xs,validateReferralCode:()=>ZS,validateToken:()=>zs,verifyGatewayProvider:()=>QS,verifyKortixToken:()=>U_,verifyOtp:()=>io,verifySsoDomain:()=>kw,wakeEscalationAttemptSummary:()=>nj,wakeEscalationNote:()=>ej,wakeProgressFingerprint:()=>QD,wireIdClock:()=>pt,wireIdClockAt:()=>Mt,wireIdClockDelta:()=>dt,workingExpiryAtMs:()=>ND,workingTurnDrawsBusyRow:()=>mE,writeActivityGroupLabel:()=>iA,writeFile:()=>qn,wsDomain:()=>Ko,wsFavicon:()=>dT,wsRootDomain:()=>pT});var fP={backendUrl:"",getToken:async()=>null},ss=null,dr=null;function yP(e){dr=e}function hP(){return dr}function gr(e,t){t?.global!==!1&&(ss=e)}function k(){return dr?.()??ss??fP}function mr(){return ss!==null||dr?.()!==void 0}function bP(e){return new Promise(t=>setTimeout(t,e))}async function fr(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 bP(o)),i=await e(),i)return i;return i}var is=12e4;function _P(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Am(e,t,n=is){let r=e instanceof Request?e.signal:t?.signal;if(_P(e))return r??void 0;let o=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,o]):r:o}function yr(){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)}},Q=class extends b{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},$e=class extends b{constructor(t,n,r,o={}){super(r||n.message||`Billing Error: ${t}`,{...o,status:t,detail:n}),this.name="BillingError"}},tt=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"}},PP="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:PP})}var hr="feature_disabled";function km(e){if(!(e instanceof b)||e.status!==403||e.code!==hr)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function as(e){let t=km(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function cs(e){let t=km(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function tn(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new $e(t,{message:r?.message||e.message||"Billing error",...r},void 0,{code:e.code,details:e.details,data:e.data,response:e.response,url:e.url,endpoint:e.endpoint})}function ls(e){return e instanceof $e}function _t(e){if(e instanceof Q)return!0;let t=e?.status;return t===401||t===403}function us(e){if(!(e instanceof $e))return null;let t=e.detail?.message?.toLowerCase()||"";return t.includes("credit")||t.includes("balance")||t.includes("insufficient")?{alertTitle:"You ran out of credits",alertSubtitle:"Upgrade your plan to get more credits and continue using the AI assistant."}:{alertTitle:"Billing check failed",alertSubtitle:e.detail?.message||"Please upgrade to continue."}}function me(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function fe(e,t){return new Promise((n,r)=>{let o=()=>{t.removeEventListener("abort",o),r(me())};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o)),t.aborted&&o()})}function br(e,t){return new Promise((n,r)=>{let o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),r(me())},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.aborted?o():t?.addEventListener("abort",o,{once:!0})})}var Rm="request_deadline",xP=/^Request exceeded the \d+s server processing deadline$/,Im=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Rm||xP.test(n),SP="git_mirror_unavailable",wP=/^git mirror is temporarily unavailable$/,vP=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===SP||wP.test(n);async function AP(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await fe(e.json(),t),typeof r.message=="string"?n=r.message:r.error&&typeof r.error=="string"?n=r.error:typeof r.detail=="string"?n=r.detail:typeof r.detail?.message=="string"?n=r.detail.message:typeof r.reason=="string"&&(n=r.reason)}catch{}if(t.aborted)throw me();return{message:n,data:r}}function kP(e,t,n){return Im(e,t,n)||vP(e,t,n)||e===501&&t?.code===ps||e===409&&(t?.code===ds||t?.code===gs)||e===503&&(t?.code===ms||t?.code===fs)}async function Cm(e,t,n,r){let{message:o,data:s}=await AP(e,t),i=new b(o,{status:e.status,response:e,details:s||void 0,data:s,detail:s?.detail,code:Im(e.status,s,o)?Rm:s?.code||s?.error_code||s?.detail?.error_code||e.status.toString()});e.status===402&&(i=tn(i));let a=e.status!==403?null:s?.code==="account_mfa_required"?"kortix:mfa-required":s?.code==="sso_required"?"kortix:sso-required":null;if(a&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a))}catch{}return e.status===431&&(i=new tt(431,{message:"Request is too large to process",suggestion:"Try uploading files one at a time, or reduce the number of files attached to your message."})),n&&!kP(e.status,s,o)&&k().onError?.(i,r),{error:i,success:!1}}var Tm="X-Kortix-Impersonate",hs="kortix.impersonation",nt=null,_r=!1,ys=new Set;function bs(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function Em(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 RP(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 Mm(){for(let e of ys)try{e()}catch{}}function Om(){return _r||(_r=!0,nt=RP(bs()?.getItem(hs)??null)),nt&&!Em(nt)?(_s(),null):nt}function IP(e){if(_r=!0,!e){_s();return}nt=e;try{bs()?.setItem(hs,JSON.stringify(e))}catch{}Mm()}function _s(){_r=!0;let e=nt!==null;nt=null;try{bs()?.removeItem(hs)}catch{}e&&Mm()}function CP(e){return ys.add(e),()=>{ys.delete(e)}}var TP=/(^|\/)admin\/(api|analytics)(\/|$)/;function Dm(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!TP.test(t)}function Ps(e){if(e!==void 0&&!Dm(e))return{};let t=Om();return t?{[Tm]:t.grantId}:{}}var vs=!1;function $m(e){vs=e}function Um(){return vs}function EP(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function Ss(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function nn(e,t,n){let r=t.toLowerCase();for(let o of Object.keys(e))o.toLowerCase()===r&&delete e[o];e[t]=n}function Pr(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[o,s]of r.flatMap(EP))nn(n,o,s);return n}function ws(e,t,n){let r={...t},o=k().clientVersion?.trim();o&&!Ss(r,"x-kortix-client-version")&&nn(r,"X-Kortix-Client-Version",o),vs&&nn(r,"x-kortix-admin-bypass","1");for(let[s,i]of Object.entries(Ps(e)))nn(r,s,i);return Ss(r,"authorization")||nn(r,"Authorization",`Bearer ${n}`),r}async function Sr(e,t){let n=await xr();if(!n)throw new Q;return{headers:new Headers(ws(e,Pr(e,{headers:t}),n)),rejected:()=>rn(n)}}function MP(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function jm(e,t,n,r,o){if(t instanceof Request){let c=new Headers(ws(t.url,Pr(t,n),r));return e(new Request(t,{headers:c,...o?{signal:o}:{}}))}let s=String(t),i=ws(s,Pr(t,n),r),a=s.startsWith("/")&&!s.startsWith("//");return e(s,{...n,headers:i,...a?{credentials:"same-origin"}:{},...o?{signal:o}:{}})}var Fm=null;async function As(e){let t=await fr(()=>k().getToken(),e);return t&&(Fm=t),t}var xr=As;function rn(e=Fm){e&&k().getToken.invalidate?.(e)}var xs=new Map;function OP(e){let t=xs.get(e);if(t)return t;let n=(async()=>(rn(e),xr({attempts:2,baseDelayMs:200})))().finally(()=>xs.delete(e));return xs.set(e,n),n}async function rt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:o=is}=n,s=n.fetch??k().fetch??fetch,i=o===null?(e instanceof Request?e.signal:t.signal)??void 0:Am(e,t,o);if(i?.aborted)throw me();let a=await(i?fe(xr(),i):xr());if(!a)throw new Q;let c=r&&!MP(t)&&!Ss(Pr(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await jm(s,e,t,a,i);if(d.status!==401||!c)return d;let g=await OP(a);return!g||g===a?d:jm(s,p,t,g,i)}async function ke(e,t,n,r){let o=await rt(e,t,n);if(o.ok)return o;let s=await o.text().catch(()=>"");throw new b(s||`${r} (HTTP ${o.status})`,{status:o.status,response:o})}var Lm=()=>k().backendUrl||"",DP=new Set([502,503,504]),jP=e=>DP.has(e),Nm=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},$P=e=>Nm(e)||(e??"GET").toUpperCase()==="DELETE",UP=2,wr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function Re(e,t={}){let{showErrors:n=!0,errorContext:r,timeout: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 FP(e,i,n,r,o,s,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function FP(e,t,n,r,o,s,i,a){try{if(t.signal?.aborted)throw me();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},o);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await NP(e,t,c,o,s,i,a);if(p instanceof Q)return{error:p,success:!1};if(!p.ok)return await Cm(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await fe(p.json(),a.activeController.signal):g?.includes("text/")?d=await fe(p.text(),a.activeController.signal):d=await fe(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return KP(c,e,t.method,n,r,o,a)}finally{vr(a)}}function vr(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function LP(e,t,n){try{await fe(e.arrayBuffer(),t)}catch(r){if(wr(r))throw r}finally{vr(n)}}async function NP(e,t,n,r,o,s,i){let a=Nm(t.method),c=$P(t.method),p=c?UP+1:1,d;for(let g=0;g<p;g++){g>0&&await br(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 fe(rt(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(f){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),f instanceof Q)return new Q;if(i.didTimeout&&wr(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(wr(f)||g===p-1)throw f;continue}if(!a||!jP(d.status)||g===p-1)return o||vr(i),d;await LP(d,m.signal,i)}return d}function KP(e,t,n,r,o,s,i){vr(i);let a=wr(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(Lm(),"")||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(Lm(),"")||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 Ie=()=>k().backendUrl||"",ps="feature_not_supported",ds="model_not_servable",gs="provision_in_flight",ms="analytics_unavailable",fs="accounts_list_unavailable",qP={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 GP(e,t,n={}){let{timeout:r=3e4,fetch:o}=n,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await rt(`${Ie()}${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 Q)return yr();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>Re(`${Ie()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>Re(`${Ie()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>Re(`${Ie()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>Re(`${Ie()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>Re(`${Ie()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>Re(`${Ie()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],Re(`${Ie()}${e}`,{...o,method:"POST",body:t,headers:s})},uploadPut:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],Re(`${Ie()}${e}`,{...o,method:"PUT",body:t,headers:s})},postStream:GP};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function ks(e){return e.replace(/\/v1\/?$/,"")}async function Pt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=ks(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 Rs(){return u(await l.get("/accounts"))}async function Is(e){return u(await l.post("/accounts",e))}async function Cs(e){return u(await l.get(`/accounts/${e}`))}async function Ts(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function Es(e){return u(await l.get(`/accounts/${e}/branding`))}async function Ms(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function Os(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 Ds(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function js(e){return u(await l.delete(`/accounts/${e}/branding`))}async function $s(e){return u(await l.get(`/accounts/${e}/members`))}async function Us(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Fs(e){return u(await l.get(`/accounts/${e}/invites`))}async function Ls(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function Ns(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Ks(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function qs(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function Gs(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}async function Bs(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function Ws(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function Hs(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Vs(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function BP(e){return Pt(e,"/v1/accounts")}async function zs(){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 WP=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","apps","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","us_region","event_triggers","notification_center","drives","ephemeral_sandboxes"];async function ot(){return u(await l.get("/projects"))}async function Ys(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function on(e,t){return u(await l.get(`/projects/${e}`,t))}async function Qs(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Xs(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Js(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function HP(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function sn(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 an(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function cn(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function VP(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Zs(e){return u(await l.post("/projects",e))}async function ei(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function ti(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Km=200;function zP(e){let t=e.split(`
|
|
1
|
+
"use strict";var Kortix=(()=>{var gs=Object.defineProperty;var DP=Object.getOwnPropertyDescriptor;var jP=Object.getOwnPropertyNames;var $P=Object.prototype.hasOwnProperty;var UP=(e,t)=>{for(var n in t)gs(e,n,{get:t[n],enumerable:!0})},LP=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of jP(t))!$P.call(e,o)&&o!==n&&gs(e,o,{get:()=>t[o],enumerable:!(r=DP(t,o))||r.enumerable});return e};var FP=e=>LP(gs({},"__esModule",{value:!0}),e);var F$={};UP(F$,{ABORT_REASONS:()=>l_,ABORT_REASONS_NOT_YET_EMITTED:()=>pO,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>As,ACTIVE_INSTANCE_COOKIE:()=>dr,ANALYTICS_UNAVAILABLE_CODE:()=>ws,ATTACHMENT_PART_REF_PREFIX:()=>T_,ApiError:()=>h,AuthError:()=>Z,BillingError:()=>qe,CONNECTION_FAULT_GRACE_MS:()=>L_,CONNECTOR_POLL_FIRST_DELAY_MS:()=>v_,CONNECTOR_POLL_INTERVAL_MS:()=>k_,CONNECTOR_POLL_WINDOW_MS:()=>R_,CONTEXT_TOOLS:()=>mb,COST_MARKUP:()=>am,ConnectorApprovalPendingError:()=>Wr,ConnectorCallError:()=>_n,ConnectorPageLimitError:()=>Hr,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>fb,DEFAULT_NOTIFICATION_PREFERENCES:()=>Dv,DEFAULT_TRANSCRIPT_OPTIONS:()=>Mg,DESTRUCTIVE_PHASES:()=>__,FEATURE_DISABLED_CODE:()=>kr,FEATURE_FLAG_KEYS:()=>yx,FEATURE_NOT_SUPPORTED_CODE:()=>Ps,FILE_VERBS:()=>nt,FileExistsError:()=>Gt,HeadlessAuthError:()=>$t,HostBoundaryError:()=>fr,IMPERSONATION_HEADER:()=>qm,INBOX_NOTIFICATION_KINDS:()=>Ov,INBOX_OBSERVATION_MAX_MS:()=>rs,INITIAL_SETTLED_CONNECTION:()=>mj,INSTANCE_SCOPED_ROUTES:()=>u_,KNOWN_TOOL_KINDS:()=>gf,KORTIX_TRANSCRIPT_SCHEMA:()=>gk,KortixMemberError:()=>rt,MAX_PROMPT_ATTACHMENTS_BYTES:()=>uS,MAX_PROMPT_ATTACHMENT_BYTES:()=>fc,MAX_PROMPT_ATTACHMENT_FILES:()=>sf,MEMORY_VERBS:()=>wM,MODEL_NOT_SERVABLE_CODE:()=>xs,NO_GROUP_ACTIVITY_TOOLS:()=>Xf,OPTIMISTIC_ABORT_MAX_MS:()=>os,OPTIMISTIC_COMPACTION_MAX_MS:()=>Rj,OPTIMISTIC_RECEIPT_MAX_MS:()=>ts,PERSISTED_QUERY_CACHE_VERSION:()=>yW,PLUMBING_TOOLS:()=>Eb,PREVIEW_PROBE_TIMEOUT_MS:()=>sj,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>VS,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>HS,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>kf,PROVISION_IN_FLIGHT_CODE:()=>Ss,PublicSessionShareError:()=>ro,RUNTIME_NOT_READY_MARKERS:()=>wO,RUNTIME_PERMISSION_CAPABILITIES:()=>yk,RUNTIME_PERMISSION_REPLIES:()=>fk,RequestTooLargeError:()=>at,RuntimeNotReadyError:()=>qt,SANDBOX_FS_ROOTS:()=>jo,SANDBOX_PORTS:()=>$e,SERVER_COMPACTION_REVALIDATE_MS:()=>q_,SERVER_OBSERVATION_MAX_MS:()=>ns,SESSION_LIST_STATUS:()=>Kj,SESSION_LOG_MINOR:()=>df,SESSION_LOG_SCHEMA:()=>kn,SESSION_NOTICE:()=>Gj,STANDALONE_TOOLS:()=>Jf,STREAM_OBSERVATION_MAX_MS:()=>rn,SandboxNotReadyError:()=>gr,SessionNotReadyError:()=>ht,SessionStartError:()=>Jr,TURN_END_LEDGER_LAG_MS:()=>Pj,TURN_ERROR_CODES:()=>Cy,WAKE_ESCALATION_COOLDOWN_MS:()=>Oj,WAKE_MAX_RESTARTS:()=>Mj,WAKE_NO_PROGRESS_MS:()=>Ej,WIRE_ID_BACKDATE_MS:()=>Ro,WIRE_ID_CLOCK_TOLERANCE:()=>Qe,WIRE_ID_TIME_MASK:()=>Ue,WIRE_ID_TIME_SCALE:()=>Ft,WIRE_MESSAGE_ID:()=>Sy,__getConfigResolver:()=>qP,__setConfigResolver:()=>KP,abortErrorReason:()=>dO,acceptAccountInvite:()=>Js,acceptInvite:()=>GO,actReviewItem:()=>dp,activateConnection:()=>Aa,addComputerToProject:()=>Ra,addGroupMembers:()=>Nu,addMarketplaceSource:()=>Yp,advanceWakeEscalation:()=>$j,allDescendantIds:()=>Rb,appendPreviewToken:()=>bm,approveProjectAccessRequest:()=>Ti,approveTask:()=>kk,archiveProject:()=>bn,assignTicket:()=>Dk,attachGroupToProject:()=>Ni,authMfa:()=>Ao,authUser:()=>xo,authenticatedFetch:()=>E,authenticatedRequest:()=>xn,authorizePreviewUrl:()=>oj,backendApi:()=>l,bindSlackIdentity:()=>Sw,bindTeamsIdentity:()=>ww,brokerProjectSecretRequest:()=>Ji,browserKeyValueStorage:()=>QD,buildInstancePath:()=>d_,buildPresentationTemplateImageUrl:()=>lj,buildPresentationTemplatePdfUrl:()=>cj,buildPreviewAuthEndpoint:()=>hm,buildPublicTemplateUrl:()=>jD,buildRuntimePresentationConversionUrl:()=>U_,buildSandboxTemplate:()=>ac,buildScrapeFailureResults:()=>Db,buildStaticFileHealthPreviewUrl:()=>TC,buildStaticFileLocalUrl:()=>IC,buildStaticFilePreviewUrl:()=>CC,buildStaticFileServicePath:()=>gh,buildTunnelEventStreamUrl:()=>l$,buildWebProxyUrl:()=>jC,bulkActReviewItems:()=>gp,bulkDeletePolicies:()=>Ww,bulkImportPolicies:()=>Hw,burstSummary:()=>NT,burstSummaryLabel:()=>KT,callConnector:()=>pt,cancelAccountDeletion:()=>EA,cancelAccountInvite:()=>zs,cancelSandbox:()=>LO,cancelSandboxUpdate:()=>oD,cancelScheduledChange:()=>Hl,cancelSubscription:()=>Bl,checkAccessEmail:()=>hD,childMapByParent:()=>RT,claimComputer:()=>lD,claimNext:()=>Fh,claimPerSeatBilling:()=>hw,claimWarmProjectSession:()=>zc,classifyPart:()=>Hg,classifyPreviewProbeStatus:()=>$_,classifyPtyClose:()=>My,classifyTurn:()=>xb,cleanErrorMessage:()=>jT,cleanResultSnippet:()=>WT,cleanWorkerOutput:()=>hM,clearImpersonationSession:()=>Cs,clearKortixAppViewerCache:()=>tP,clearModelDefault:()=>Cl,clearSessionFresh:()=>AS,closeChangeRequest:()=>Ic,closeMilestone:()=>cR,collectTurnParts:()=>wT,commentTicket:()=>$k,commitSessionChanges:()=>Mc,compactionExpiryAtMs:()=>Ij,compactionTurnInfo:()=>qT,compareMessagesForDisplay:()=>bT,compareSemver:()=>GC,completeInFlight:()=>Nh,completeSlackInstall:()=>ou,completeTeamsInstall:()=>su,composerSelectableAgents:()=>km,computeStatusFromPart:()=>sm,configureAutoTopup:()=>Ql,configureKortix:()=>Sr,confirmCheckoutSession:()=>Kl,connectEmail:()=>gu,connectSlack:()=>nu,connectionFromHealth:()=>gj,connectionIsFaulted:()=>dj,connectionSharedWithEveryone:()=>Nx,connectorConnect:()=>nf,connectorFinalize:()=>rf,connectorHeadline:()=>KD,contextLabelForTool:()=>eE,contextToolSummary:()=>xI,contextToolTrigger:()=>SI,convertPresentationToGoogleSlides:()=>GA,convertRuntimePresentation:()=>uj,copyFile:()=>Qn,costExportUrl:()=>Jl,countLiveInboxPrompts:()=>Sj,countReviewItemsBySegment:()=>HA,createAccount:()=>Us,createAccountAuditWebhook:()=>Lp,createAccountSecretResource:()=>aa,createAccountToken:()=>kp,createApp:()=>Jp,createAppAccessSession:()=>id,createAppDeployment:()=>cd,createAppToken:()=>td,createAppVolume:()=>vd,createAppVolumeSnapshot:()=>Id,createArtifactKind:()=>SE,createAssignment:()=>ip,createAuditWebhook:()=>SA,createBackup:()=>VO,createCheckoutSession:()=>Nl,createConnector:()=>Ka,createConnectorLinkInfoCache:()=>LD,createFile:()=>Yn,createGatewayKey:()=>Eu,createGroup:()=>$u,createHttpSessionSyncController:()=>X_,createInstance:()=>iD,createKortix:()=>jh,createKortixPty:()=>gg,createKortixSession:()=>ko,createMarketplaceInstallSession:()=>uv,createMilestone:()=>iR,createModelVisibility:()=>CP,createOAuthClient:()=>tp,createPerSeatCheckout:()=>yw,createPersistedQueryCache:()=>YD,createPolicy:()=>qw,createPortalSession:()=>ql,createProject:()=>ci,createProjectAgent:()=>Hk,createProjectCliToken:()=>Ep,createProjectRepo:()=>li,createProjectResourceGrant:()=>Gi,createProjectSession:()=>mt,createProjectSkill:()=>fi,createProjectTrigger:()=>hl,createPromptAttachmentController:()=>Tg,createRole:()=>Vu,createSSEStream:()=>u$,createSandbox:()=>EO,createSandboxShare:()=>bp,createSandboxTemplate:()=>oc,createSavedCopyStore:()=>qS,createScimToken:()=>Qw,createServiceAccountApi:()=>bA,createSessionPrompt:()=>In,createSessionPublicShare:()=>Wc,createSessionQueue:()=>Uh,createSessionReminder:()=>xp,createSsoGroupMapping:()=>lA,createTask:()=>wk,createTicket:()=>Ek,createTunnelEventStream:()=>p$,createWarmSessionPool:()=>t$,currentSavedCopyStore:()=>Uc,declineAccountInvite:()=>Zs,declineInvite:()=>WO,deleteAccountImmediately:()=>MA,deleteAccountSecretResource:()=>ua,deleteApp:()=>ed,deleteAppDeployment:()=>md,deleteAuditWebhook:()=>AA,deleteBackup:()=>YO,deleteConnector:()=>Ba,deleteConnectorCredential:()=>Ya,deleteCredential:()=>fR,deleteDriveFile:()=>Cv,deleteEnv:()=>ug,deleteFile:()=>xt,deleteGatewayBudget:()=>Iu,deleteGitHubInstallation:()=>ki,deleteGroup:()=>Lu,deleteInstance:()=>aD,deleteKortixProject:()=>tR,deleteMilestone:()=>uR,deleteOAuthClient:()=>op,deletePersonalProjectSecret:()=>oa,deletePolicy:()=>Gw,deleteProjectAgent:()=>zk,deleteProjectProviderOAuth:()=>ea,deleteProjectResourceGrant:()=>Wi,deleteProjectSecret:()=>na,deleteProjectSession:()=>il,deleteProjectTrigger:()=>_l,deletePromptAttachment:()=>Et,deleteRole:()=>Qu,deleteSandboxTemplate:()=>ic,deleteServiceAccountApi:()=>PA,deleteSessionPrompt:()=>el,deleteSessionReminder:()=>so,deleteSessionReminders:()=>wp,deleteSsoGroupMapping:()=>uA,deleteSsoProvider:()=>aA,deleteTask:()=>Rk,deleteTicket:()=>Uk,describeAccountInvite:()=>Xs,describeConnectorTool:()=>Nr,destroyAppMachine:()=>xd,destroyAppVolume:()=>Rd,detachGroupFromProject:()=>qi,detectLocalhostUrls:()=>lh,directSubsessions:()=>Hj,disableServiceAccountApi:()=>_A,disconnectEmail:()=>mu,disconnectGitHubApp:()=>HD,disconnectSlack:()=>au,discoverConnectionOAuth2:()=>Gx,discoverConnectionOAuth2Resource:()=>Wx,discoverConnectorAuth:()=>qa,discoverLocalSandbox:()=>jO,dismissDriveConflict:()=>xv,downloadAccountAudit:()=>OD,downloadDriveFile:()=>wv,dropClientForUrl:()=>vR,dropPublicClientForUrl:()=>CR,editQueued:()=>Gh,editSessionPrompt:()=>tl,enqueue:()=>Lh,ensurePmSession:()=>Gk,ensurePreviewSessionCookie:()=>j_,ensureProjectConnectorConnection:()=>Kx,ensureSandbox:()=>b_,ensureWarmProjectSession:()=>Vc,env:()=>Ty,exchangeCode:()=>bo,execInApp:()=>wd,exportAccountAudit:()=>$p,extractGatewayErrorDetails:()=>ye,extractInstanceRoute:()=>tn,extractSkillBaseDir:()=>r_,extractSkillContent:()=>EM,extractSkillFiles:()=>n_,extractWorkerPreview:()=>_M,failInFlight:()=>Kh,fallbackBusyRowAfterTurnId:()=>VE,familyForTool:()=>Xo,featureDisabledKey:()=>hs,featureFlags:()=>Jd,fetchAccountStateWithToken:()=>gw,fetchAccountsWithToken:()=>fx,fetchAttachmentPart:()=>XD,fetchCostExportCsv:()=>xw,fetchKortixAppViewer:()=>Sm,fetchProjectArchive:()=>gc,fetchProjectFileRaw:()=>lS,fetchProjectsForAccountWithToken:()=>vx,fetchSessionAttachment:()=>Qd,fileDownloadRequest:()=>Hy,filePhase:()=>SM,fileVerb:()=>xM,files:()=>Zy,finalizeAppArtifact:()=>co,finalizeConnectorSetupLink:()=>AD,findActiveTranscriptShare:()=>YS,findFiles:()=>Vn,findLastTextPart:()=>AT,findSessionAttachments:()=>Yv,findText:()=>zn,fireProjectTrigger:()=>xl,fixSandboxWithAgent:()=>rc,flattenModels:()=>vP,flattenThought:()=>TE,forkAppVolume:()=>Ed,formatBillingErrorForUI:()=>_s,formatCost:()=>cM,formatDuration:()=>im,formatJsonFailureOutput:()=>$T,formatMessageDay:()=>$E,formatMessageExact:()=>UE,formatOpenCodeRuntimeError:()=>RO,formatRawOutput:()=>GT,formatRuntimeError:()=>h_,formatTokens:()=>lM,formatTranscript:()=>Hh,freshSendHint:()=>XE,generateSessionId:()=>$h,getAccount:()=>Ls,getAccountBranding:()=>Ns,getAccountDeletionStatus:()=>IA,getAccountState:()=>Ol,getAccountStateMinimal:()=>Dl,getActiveInstanceIdFromCookie:()=>m_,getAdminBootModes:()=>KA,getAdminProviderAnalytics:()=>UA,getAdminProviderDistribution:()=>DA,getAdminProviderFallback:()=>FA,getAdminRole:()=>OA,getAgentCardLabel:()=>_b,getAgentConfig:()=>cw,getAgentPersona:()=>Yk,getAllVersions:()=>tD,getAnsweredQuestionParts:()=>kT,getApp:()=>io,getAppAccess:()=>rd,getAppAuthEnv:()=>nd,getAppDeployment:()=>ud,getAppDeploymentLogs:()=>pd,getApprovalLink:()=>lv,getAuthToken:()=>It,getAuthTokenWithRetry:()=>jx,getAutoTopupSettings:()=>Yl,getAutoTopupSetupStatus:()=>fw,getBillingCreditBreakdown:()=>Ul,getBillingTierConfigurations:()=>Fl,getBillingTransactionsSummary:()=>$l,getBillingUsageHistory:()=>Ll,getChangeRequest:()=>Ac,getChangeRequestDiff:()=>vc,getChangeRequestMergePreview:()=>kc,getChildSessionError:()=>$I,getChildSessionId:()=>qg,getChildSessionToolParts:()=>UI,getClient:()=>Je,getClientForUrl:()=>Se,getConnectStatus:()=>Va,getConnectionOAuth2Application:()=>Bx,getConnectionOAuth2Status:()=>Qx,getConnectionPolicies:()=>Xx,getConnectorCatalog:()=>Tt,getConnectorConfig:()=>La,getConnectorPolicies:()=>$a,getConnectorSetupLink:()=>SD,getCostSummary:()=>Pw,getCurrentInstanceIdFromPathname:()=>g_,getCurrentInstanceIdFromWindow:()=>fO,getCurrentProject:()=>xg,getDefaultAccountState:()=>Ml,getDiagnostics:()=>KI,getDirectory:()=>bb,getDiscoverConnector:()=>Gr,getDiscoverIntegration:()=>rS,getDriveFileUrl:()=>Md,getEmailInstallation:()=>pu,getEmailMode:()=>du,getEnterpriseDemo:()=>kA,getFileStatus:()=>Hn,getFileWithDir:()=>Ng,getFilename:()=>hb,getFolderAccess:()=>yv,getFullChangelog:()=>P_,getGatewayBreakdown:()=>Au,getGatewayBudgets:()=>Ru,getGatewayErrors:()=>ku,getGatewayKeys:()=>Tu,getGatewayLog:()=>xu,getGatewayOverview:()=>Su,getGatewayRoutingPolicy:()=>yu,getGatewaySeries:()=>wu,getGatewaySessions:()=>vu,getGitHubAppStatus:()=>qD,getGitHubInstallation:()=>bi,getGoogleAuthUrl:()=>BA,getGroup:()=>ju,getHiddenToolParts:()=>EI,getImpersonationSession:()=>Wm,getInvite:()=>BO,getJustavpsServerTypes:()=>sD,getKortixProject:()=>Jk,getKortixProjectBySession:()=>Zk,getKortixPtyWebSocketUrl:()=>yg,getLatestSandboxVersion:()=>eD,getMaintenanceConfig:()=>ID,getManagedGitBackend:()=>Ri,getManagedGitStatus:()=>xx,getMarketplaceCatalogItem:()=>Hp,getMarketplaceCatalogItemFile:()=>Vp,getMfaRequired:()=>Jw,getMilestone:()=>oR,getMobileClientPolicy:()=>Eg,getModelDefaults:()=>kl,getNotificationPreferences:()=>Ud,getOAuthClient:()=>ep,getOAuthConsentRequest:()=>PD,getOpenCodeConfigInvalidError:()=>PO,getPartText:()=>CI,getPatPolicy:()=>fA,getPermissionForTool:()=>qI,getProject:()=>gn,getProjectActivity:()=>Qk,getProjectCommit:()=>_c,getProjectCommitDiff:()=>Pc,getProjectDetail:()=>mn,getProjectDrive:()=>fv,getProjectFileHistory:()=>xc,getProjectGitToken:()=>ai,getProjectLlmCatalog:()=>fn,getProjectLlmCatalogProviders:()=>bx,getProjectModelAccess:()=>Dn,getProjectModelPicker:()=>yn,getProjectSandboxHealth:()=>Pn,getProjectSandboxProviderTransition:()=>Sx,getProjectSession:()=>Cn,getProjectSessionConfigState:()=>al,getProjectSessionScope:()=>ul,getProrationPreview:()=>Vl,getProviders:()=>IO,getProxyBaseUrl:()=>EC,getPublicClientForUrl:()=>RR,getPublicMarketplaceItem:()=>fD,getPublicMarketplaceItemFile:()=>yD,getPublicSessionShare:()=>ov,getPublicSessionShareMessages:()=>sv,getPublicShareByToken:()=>RD,getPublicTemplate:()=>$D,getQuestionForTool:()=>BI,getReferralCode:()=>Ew,getReferralStats:()=>Dw,getRetryInfo:()=>uM,getRetryMessage:()=>pM,getReviewItem:()=>up,getRolePermissions:()=>Wu,getRoleUsage:()=>Hu,getRuntimeConfigInvalidError:()=>es,getSSHConnection:()=>XO,getSandbox:()=>TO,getSandboxById:()=>MO,getSandboxPortUrl:()=>CO,getSandboxProvisionStatus:()=>uD,getSandboxProvisionStreamUrl:()=>pD,getSandboxUpdateStatus:()=>ZO,getSandboxUrl:()=>gm,getSandboxUrlForExternalId:()=>Ge,getSecretSetupLink:()=>vD,getServerHealth:()=>$o,getServiceLogs:()=>PR,getSessionAudit:()=>Yc,getSessionCost:()=>aM,getSessionCostRecord:()=>On,getSessionDrives:()=>Yf,getSessionHealth:()=>vg,getSessionMessageAuthors:()=>ml,getSessionModelUsage:()=>fl,getSessionOpenBundle:()=>QS,getSessionOversight:()=>tA,getSessionParticipants:()=>Nc,getSessionPolicy:()=>pA,getSessionPreviewCandidates:()=>Bc,getSessionProviderSecretPool:()=>ma,getSessionTranscript:()=>Qc,getSessionTranscriptSync:()=>Xc,getSessionTurn:()=>Jc,getSessionWatch:()=>Kc,getShellModePart:()=>yM,getSlackChannelFile:()=>cu,getSlackInstallation:()=>tu,getSlackManifest:()=>iu,getSlackMode:()=>ru,getSsoProvider:()=>rA,getStaticFileHealthPath:()=>mh,getSupabaseAccessToken:()=>$r,getSupabaseAccessTokenWithRetry:()=>tf,getTask:()=>Pk,getTaskStatus:()=>Sk,getTemplate:()=>pv,getTicket:()=>Ik,getToolInfo:()=>LI,getToolPrimaryArg:()=>qo,getTranscriptFilename:()=>Vh,getTurnCost:()=>iM,getTurnError:()=>nM,getTurnErrorDetails:()=>oM,getTurnErrorRawText:()=>rM,getTurnStatus:()=>sM,getUsageRollup:()=>Xl,getUserRolesWithToken:()=>ED,getVersionDiff:()=>Sc,getWebPushPublicKey:()=>Fd,getWorkingState:()=>eM,grantAccountSecretResource:()=>pa,grantSandboxProjectAccess:()=>KO,grantSecretToAgent:()=>uw,groupMessagesIntoTurns:()=>PT,groupShowSegments:()=>NE,groupSteps:()=>rm,hasDiffs:()=>dM,hasLocalhostUrls:()=>vC,hasPreviewTarget:()=>dh,hasRetryingAssistantTurn:()=>IT,heartbeatGapEvent:()=>Uy,holdSessionPrompts:()=>ol,humanizeReviewActionPath:()=>yp,humanizeSearchQuery:()=>tr,humanizeToolName:()=>Gg,impersonationHeaders:()=>Is,importSsoProviderFromMetadata:()=>sA,inboxObservationSupersedes:()=>xj,initialWakeEscalationState:()=>Pm,inputPath:()=>Ne,installTemplate:()=>dv,interruptSessionPrompt:()=>nl,invalidateTokenCache:()=>Ur,inviteAccountMember:()=>Hs,inviteProjectMember:()=>ji,inviteRepoCollaborator:()=>si,isAbortError:()=>pr,isAdminBypassEnabled:()=>Ym,isAgentPart:()=>wI,isAppRouteUrl:()=>ch,isAttachment:()=>II,isAttachmentPartRef:()=>E_,isAuthFailure:()=>kt,isBillingError:()=>bs,isCompactionPart:()=>AI,isConfigured:()=>wr,isContextTool:()=>PI,isDestructivePhase:()=>JO,isEmptyConversation:()=>Z_,isEmptyShowPart:()=>lo,isErrorOutput:()=>TT,isExternalUrl:()=>LC,isFeatureDisabledError:()=>ys,isFilePart:()=>Kg,isImpersonationSessionLive:()=>Bm,isInstanceDetailPath:()=>gO,isInstanceScopedAppPath:()=>p_,isInternalLocalhostUrl:()=>DC,isInvisibleActivityPart:()=>Gd,isInviteSent:()=>Cx,isLastUserMessage:()=>ZE,isLegacyMigratedSession:()=>B_,isManagedGithubProject:()=>hx,isNoGroupActivityTool:()=>Bd,isOfferedModel:()=>ps,isOpenCodeConfigInvalidError:()=>xO,isPaintableSavedCopy:()=>Sf,isPatchPart:()=>kI,isPersistableQueryKey:()=>zD,isPreviewUrl:()=>OC,isProxiableLocalhostUrl:()=>fh,isQuestionTool:()=>Lv,isReasoningPart:()=>Ae,isRetryableTurnError:()=>Cb,isRuntimeConfigInvalidError:()=>f_,isRuntimeNotReadyResponse:()=>y_,isRuntimeReady:()=>Ag,isRuntimeStartingError:()=>kO,isSandboxNotReadyError:()=>nn,isSelectableAgent:()=>po,isServerReachable:()=>Sg,isSessionAttachmentRef:()=>Bv,isSessionFresh:()=>Dc,isSessionStartError:()=>rw,isShellActivityTool:()=>Uv,isShellMode:()=>Zb,isShortOutput:()=>bM,isShowContentUnavailable:()=>jv,isShowPayloadEmpty:()=>$n,isSnapshotPart:()=>vI,isStandaloneActivityTool:()=>Wd,isStepPart:()=>RI,isSubdomainPreviewUrl:()=>yr,isTextPart:()=>we,isToolPart:()=>ne,isToolPartHidden:()=>MI,isTurnErrorCode:()=>mk,isUnderSandboxRoot:()=>_g,isWebProxyUrl:()=>UC,isWireIdAheadOf:()=>Ay,kortixAppViewerToken:()=>nP,kortixBinding:()=>rP,kortixPty:()=>jy,kortixToken:()=>wm,leaveAccount:()=>ni,linkGitHubInstallation:()=>Ai,linkRepository:()=>yi,listAccountAudit:()=>Dp,listAccountAuditWebhooks:()=>Up,listAccountInvites:()=>Vs,listAccountMembers:()=>Ws,listAccountResourceGrants:()=>Nw,listAccountSecretResources:()=>ia,listAccountSessions:()=>gA,listAccountTokens:()=>vp,listAccounts:()=>$s,listActions:()=>Vw,listAdminSandboxes:()=>jA,listAgentIdentities:()=>Bu,listAllConnections:()=>_a,listAppAgents:()=>od,listAppDeployments:()=>ld,listAppMachines:()=>yd,listAppVolumeSnapshots:()=>Cd,listAppVolumes:()=>Ad,listApps:()=>Xp,listAssignments:()=>sp,listAuditEvents:()=>vA,listAuditWebhooks:()=>xA,listBackups:()=>HO,listBillingTransactions:()=>jl,listChangeRequests:()=>wc,listChannelBindings:()=>Cw,listColumns:()=>Lk,listConnectSections:()=>tS,listConnectToolkits:()=>eS,listConnections:()=>ba,listConnectorAccounts:()=>Kr,listConnectorTools:()=>Fr,listConnectors:()=>Ea,listCostByProject:()=>_w,listCredentialEvents:()=>dR,listCredentials:()=>pR,listDiscoverConnectors:()=>Br,listDiscoverIntegrations:()=>nS,listDiscoverSections:()=>Ha,listDriveConflicts:()=>Pv,listDriveFiles:()=>Sv,listDriveFolder:()=>zf,listDriveVersions:()=>Iv,listEnv:()=>cg,listFeaturedMarketplaces:()=>Wp,listFields:()=>Nk,listFiles:()=>Vt,listFolderPrincipals:()=>_v,listGatewayLogs:()=>Pu,listGitHubInstallations:()=>_i,listGitHubRepositories:()=>xi,listGitHubRepositoryBranches:()=>Si,listGroupMembers:()=>Fu,listGroupProjectGrants:()=>Uw,listGroups:()=>Du,listKortixProjectSessions:()=>eR,listKortixProjects:()=>Xk,listKortixPty:()=>dg,listLinkableGitHubInstallations:()=>Pi,listManagedGitRepositories:()=>Ci,listMarketplaceCatalogItems:()=>Bp,listMarketplaceSources:()=>zp,listMarketplaces:()=>Gp,listMemberGroups:()=>Lw,listMemberProjectAccess:()=>Fw,listMilestoneEvents:()=>sR,listMilestones:()=>rR,listMyAccountInvites:()=>Qs,listNotifications:()=>jd,listOAuthClients:()=>Zu,listOAuthGrants:()=>Cp,listPendingApprovals:()=>Hi,listPendingProjectInvites:()=>$i,listPermissions:()=>cp,listPipedreamApps:()=>Ga,listPipedreamSections:()=>Wa,listPolicies:()=>Kw,listProjectAccess:()=>Mi,listProjectAccessRequests:()=>Ii,listProjectAgentIdentities:()=>Gu,listProjectAgents:()=>Wk,listProjectAudit:()=>jp,listProjectBranches:()=>hc,listProjectCliTokens:()=>Tp,listProjectCommits:()=>bc,listProjectDirectory:()=>uc,listProjectFiles:()=>lc,listProjectGroupGrants:()=>Fi,listProjectPolicies:()=>Ja,listProjectProviderOAuth:()=>Zi,listProjectReminders:()=>Ap,listProjectResourceGrants:()=>Bi,listProjectSandboxTemplates:()=>ec,listProjectSandboxes:()=>cc,listProjectSecrets:()=>Yi,listProjectSessions:()=>gt,listProjectSessionsPage:()=>Lc,listProjectSnapshots:()=>tc,listProjectTriggerEventApps:()=>wl,listProjectTriggerEventTypes:()=>Sl,listProjectTriggers:()=>yl,listProjects:()=>ut,listProjectsForAccount:()=>oi,listPublicMarketplaceItems:()=>gD,listPublicMarketplaces:()=>mD,listReferrals:()=>jw,listReviewItems:()=>lp,listRoles:()=>qu,listSandboxProjectMembers:()=>NO,listSandboxShares:()=>hp,listSandboxes:()=>DO,listScimTokens:()=>Yw,listServiceAccountsApi:()=>hA,listServiceTemplates:()=>_R,listServices:()=>bR,listSessionConnectRequests:()=>Zx,listSessionCosts:()=>eu,listSessionDrives:()=>Mv,listSessionPrompts:()=>Zc,listSessionProviderSecretPools:()=>fa,listSessionPublicShares:()=>Gc,listSessionReminders:()=>Pp,listSessionsNeedingInput:()=>Vi,listSignedInDevices:()=>av,listSsoGroupMappings:()=>cA,listTaskEvents:()=>xk,listTasks:()=>_k,listTemplates:()=>qk,listTicketEvents:()=>Tk,listTickets:()=>Ck,loadHttpSessionHistory:()=>Q_,loadPreviewUrlTemplate:()=>Ye,looksLikeError:()=>Yg,looksLikeHtml:()=>YT,looksLikeJsonPayload:()=>BT,makeDriveFolder:()=>kv,mapApiReviewItem:()=>rv,markInstanceError:()=>cD,markNotificationsRead:()=>$d,markSessionFresh:()=>vn,maxWireIdClock:()=>og,memoryRelPath:()=>AM,mergeBurstSteps:()=>RE,mergeChangeRequest:()=>Cc,messageCreatedAt:()=>EE,messageTime:()=>Wb,migrateAdminSandboxProvider:()=>LA,mintWireMessageId:()=>Co,mintWireMessageIdAbove:()=>sg,mkdir:()=>Xt,modelInDefaultView:()=>IP,modelRefToKey:()=>dP,moveDriveFile:()=>Rv,narrateFailedStep:()=>nm,narrateStep:()=>tm,narrationToolName:()=>lr,narrowChatEvent:()=>Ly,newestWireIdClock:()=>vy,nextConnectorPollDelay:()=>ND,normalizeActivityToolName:()=>ce,normalizeAppPathname:()=>bO,normalizeExternalInput:()=>FC,normalizeName:()=>Y,normalizeToolName:()=>Bg,notifyHostSignal:()=>W_,openChangeRequest:()=>Rc,openEventStream:()=>Mo,openStressTestStream:()=>DD,paginateConnector:()=>Xa,parseBillingError:()=>un,parseEmbeddedFailure:()=>HT,parseFlagOverride:()=>Xv,parseJsonFailure:()=>Tb,parseLocalhostUrl:()=>er,parseMemoryView:()=>vM,parseOpenCodeErrorPayload:()=>_O,parsePresentationOutput:()=>CM,parseProxyHop:()=>wg,parseQuestionAnswersFromOutput:()=>IM,parseReadOutput:()=>TM,parseRuntimeErrorPayload:()=>dm,parseScrapeInputUrls:()=>Ob,parseScrapeOutput:()=>jb,parseSubdomainUrl:()=>Rg,parseTaskRows:()=>PM,parseWebProxyUrl:()=>$C,parseWebSearchOutput:()=>Zg,partOutcome:()=>Qg,patchKortixProject:()=>nR,patchVerb:()=>RM,pickerProviderList:()=>AP,pipedreamConnect:()=>Na,pipedreamConnectConnection:()=>Ia,pipedreamFinalize:()=>Qa,pipedreamFinalizeConnection:()=>Ta,platformConfig:()=>v,pollConnectionOAuth2DeviceAuthorization:()=>Yx,pollProjectProviderOAuth:()=>jr,previewGatewayRoute:()=>_u,previewMfaRequired:()=>Zw,previewSlackIdentity:()=>Aw,previewTeamsIdentity:()=>vw,probeEffectivePermission:()=>Xu,probeEffectivePermissions:()=>Ju,probePreviewPort:()=>ij,projectArchiveRequest:()=>mc,projectCompacting:()=>Cj,projectConfigAgentsToOpenCodeAgents:()=>uP,projectConfigAgentsToRuntimeAgents:()=>vm,projectSessionConnection:()=>pj,projectSessionForRuntimeId:()=>Vj,projectSessionStartSeed:()=>nw,projectWorking:()=>wj,provisionProject:()=>ui,provisionProjectStream:()=>Px,provisionProjectWithToken:()=>kx,proxyLocalhostUrl:()=>kg,proxyUrlToInternal:()=>MC,purchaseCredits:()=>zl,putConnectionOAuth2Application:()=>qx,rawErrorText:()=>jg,reactivateSandbox:()=>FO,reactivateSubscription:()=>Gl,readBlob:()=>Yt,readDriveFile:()=>Av,readFile:()=>zt,readKortixMember:()=>cs,readProjectFile:()=>dc,reasoningIsRunning:()=>Nb,rebuildProjectSnapshot:()=>nc,reconcileConnection:()=>Pa,reconcileMemberConnection:()=>xa,reconcileServices:()=>SR,recordPlatformLogout:()=>_D,recoverLinkResults:()=>zo,refreshReferralCode:()=>Mw,refreshSession:()=>Ut,registerAppArtifact:()=>ao,registerConnectionOAuth2Client:()=>Hx,registerDeviceToken:()=>Od,registerService:()=>wR,registerWebPushSubscription:()=>Nd,rejectProjectAccessRequest:()=>Ei,relativizePath:()=>NI,reloadProjectSessionConfig:()=>cl,reloadProjectSessionConfigStream:()=>ll,removeAccountAuditWebhook:()=>Np,removeAccountBrandingAsset:()=>Bs,removeAccountMember:()=>ei,removeGroupMember:()=>Ku,removeKortixPty:()=>fg,removeMarketplaceSource:()=>Qp,removeQueued:()=>Bh,renameConnection:()=>ka,renameFile:()=>Jn,renameSandbox:()=>OO,reopenChangeRequest:()=>Tc,reopenMilestone:()=>lR,reorderQueued:()=>Wh,replaceColumns:()=>Fk,replaceFields:()=>Kk,replaceProjectRepository:()=>hi,replaceTemplates:()=>Bk,requestAccountDeletion:()=>TA,requestChangesOnChangeRequest:()=>Ec,requestProjectAccess:()=>Rx,requestProjectConnector:()=>qp,requestProjectSecret:()=>Kp,requestTopUp:()=>mw,requireKortixMember:()=>iP,resendAccountInvite:()=>Ys,resendPendingProjectInvite:()=>Li,resetAccountBranding:()=>Gs,resetClient:()=>kR,resetGatewayRoutingPolicy:()=>bu,resetPassword:()=>_o,resetPublicClient:()=>IR,resetSandboxUpdateStatus:()=>rD,resolveApproval:()=>zi,resolveComposerAgent:()=>lP,resolveComposerModel:()=>MP,resolveConnectorStart:()=>FD,resolveModelDefault:()=>EP,resolvePublicShareUrl:()=>zS,resolveScrapeResults:()=>QT,resolveWorkingTurn:()=>JE,resolvedPlan:()=>dw,restartAppMachine:()=>Pd,restartProjectSession:()=>Tn,restartSandbox:()=>$O,restoreAppVolume:()=>Td,restoreBackup:()=>zO,restoreDriveVersion:()=>Tv,retryAccountSecretResource:()=>la,retryFailed:()=>qh,retrySessionPrompt:()=>rl,revealCredential:()=>mR,reviewItemTarget:()=>WA,reviewSegmentForStatus:()=>Gf,reviewVerdictForStatus:()=>VA,revokeAccountSecretResourceGrant:()=>da,revokeAccountSession:()=>mA,revokeAccountToken:()=>Rp,revokeAssignment:()=>ap,revokeConnection:()=>wa,revokeGatewayKey:()=>Mu,revokeOAuthGrant:()=>Ip,revokePendingProjectInvite:()=>Ui,revokeProjectAccess:()=>Di,revokeProjectCliToken:()=>Mp,revokeSandboxProjectAccess:()=>qO,revokeSandboxShare:()=>_p,revokeScimToken:()=>Xw,revokeSessionPublicShare:()=>Hc,rewriteLocalhostUrl:()=>tt,rollbackApp:()=>fd,rootRuntimeSession:()=>G_,rotateAccountSecretResource:()=>ca,rotateOAuthClientSecret:()=>rp,runConnector:()=>Vr,runGatewayPlayground:()=>Ou,runProjectProviderOAuthFlow:()=>Mx,runtimeSessionsOf:()=>ss,runtimeSupports:()=>rh,sanitizePtyChunk:()=>Dy,saveGitHubInstallation:()=>wi,savedCopyEmptyRoot:()=>J_,scaleApp:()=>Sd,scheduleDowngrade:()=>Wl,searchConnectorTools:()=>ha,searchProjectFiles:()=>pc,segmentTurn:()=>LE,selectableProjectAgents:()=>Zv,sendMagicLink:()=>fo,sendReferralEmails:()=>$w,serverCompactionRevalidateAtMs:()=>Tj,serviceAction:()=>xR,sessionConnectionLabel:()=>Bj,sessionListStatus:()=>qj,sessionModelPin:()=>gl,sessionParentId:()=>WS,sessionPromptActions:()=>ZS,sessionStartKey:()=>sw,setAccountSecretResourceAccess:()=>ga,setActiveInstanceCookie:()=>yO,setAdminBootModes:()=>qA,setAdminBypass:()=>zm,setAdminProviderDistribution:()=>$A,setAdminProviderFallback:()=>NA,setAgentScope:()=>Il,setBootstrapAuthToken:()=>Dx,setCachedAuthToken:()=>Ox,setConnectionPolicies:()=>Jx,setConnectorAuthorizationStrategy:()=>Da,setConnectorCredential:()=>za,setConnectorCredentialMode:()=>Oa,setConnectorName:()=>Fa,setConnectorPolicies:()=>Ua,setConnectorSecretBinding:()=>oS,setConnectorSensitive:()=>ja,setDefaultConnection:()=>va,setEnterpriseDemo:()=>RA,setEnv:()=>lg,setGatewayBudget:()=>Cu,setGatewayRoutingPolicy:()=>hu,setGitHubAppFromExisting:()=>GD,setGitHubAppPat:()=>WD,setImpersonationSession:()=>ZP,setMaintenanceConfig:()=>TD,setMemberSuperAdmin:()=>zw,setMfaRequired:()=>eA,setModelDefault:()=>Rl,setPersonalProjectSecret:()=>ra,setProjectModelAccess:()=>jn,setProjectModelEnablement:()=>iw,setProjectOnboardingComplete:()=>mi,setProjectOnboardingProfile:()=>Ax,setProjectPolicies:()=>Za,setProjectSecretStrategy:()=>Xi,setProjectSessionModel:()=>dl,setProjectSessionScope:()=>pl,setProjectSessionSharing:()=>Fc,setProjectTriggersActivation:()=>Pl,setSavedCopyStore:()=>BS,setSessionOversight:()=>nA,setSessionProviderSecretPool:()=>ya,setSessionWatch:()=>qc,settleSessionConnection:()=>fj,setupSSH:()=>QO,shareConnection:()=>Ca,shareFolder:()=>hv,shellActivityGroupLabel:()=>Fv,shellExitCode:()=>um,shouldAttachImpersonation:()=>Hm,shouldHideResponsePart:()=>tM,shouldShowToolPart:()=>yb,shouldSuppressWorkingTurnBusy:()=>WE,showGroupItems:()=>BE,showTurnBusyIndicator:()=>om,signInWithPassword:()=>mo,signInWithProvider:()=>ho,signInWithSso:()=>wo,signOut:()=>vo,signOutDevice:()=>cv,signUp:()=>go,skillDocumentPath:()=>UM,skillInputDir:()=>DM,sortSessions:()=>CT,splitTurnWork:()=>mM,splitUserParts:()=>TI,startApp:()=>dd,startAppMachine:()=>bd,startConnectionOAuth2Authorization:()=>Vx,startConnectionOAuth2DeviceAuthorization:()=>zx,startConnectorSetupLink:()=>wD,startGitHubAppManifest:()=>BD,startProjectProviderOAuth:()=>Dr,startProjectSession:()=>We,startProjectSessionOrThrow:()=>vl,startSessionWithToken:()=>CD,startTask:()=>vk,stepLabel:()=>Xg,stopApp:()=>gd,stopAppMachine:()=>_d,stopProjectSession:()=>En,stopSandbox:()=>UO,storeGitHubUserToken:()=>vi,stripAnsi:()=>WI,stripInstancePrefix:()=>mO,stripTrailingSlashes:()=>oe,submitAccessRequest:()=>bD,submitDemoRequest:()=>MD,submitOAuthConsent:()=>xD,submitReviewItem:()=>pp,submitSecretSetupLink:()=>kD,subscribeToImpersonation:()=>ex,supabaseClient:()=>gx,syncConnectors:()=>Ma,syncSubscription:()=>bw,systemReload:()=>ER,toDaemonPath:()=>et,toInstanceAwarePath:()=>hO,toInternalUrl:()=>yh,toSandboxAbsolutePath:()=>Ht,toToolView:()=>rT,toWorkspaceRelative:()=>Pg,toolInfo:()=>Bo,toolKind:()=>se,toolViewModel:()=>a_,triggerSandboxUpdate:()=>nD,triggersRequest:()=>Ey,turnEndCause:()=>K_,turnEndNotice:()=>kj,turnHasSteps:()=>vT,turnIsConfirmedActive:()=>zE,turnRendersQueued:()=>YE,turnRetryLabel:()=>Wj,unassignTicket:()=>jk,unregisterDeviceToken:()=>Dd,unregisterWebPushSubscription:()=>Kd,unshareFolder:()=>bv,unwrapError:()=>fe,updateAccountAuditWebhook:()=>Fp,updateAccountBranding:()=>Ks,updateAccountMemberRole:()=>ti,updateAccountName:()=>Fs,updateAgentConfig:()=>lw,updateApp:()=>Zp,updateAppAccess:()=>sd,updateAppVolume:()=>kd,updateAuditWebhook:()=>wA,updateChangeRequest:()=>Oc,updateChannelBinding:()=>Iw,updateConnectionCredential:()=>Sa,updateEmailPolicy:()=>fu,updateExperimentalFeature:()=>di,updateFeatureFlag:()=>pi,updateGroup:()=>Uu,updateKortixPty:()=>mg,updateMilestone:()=>aR,updateNotificationPreferences:()=>Ld,updateOAuthClient:()=>np,updatePassword:()=>Po,updatePatPolicy:()=>yA,updatePolicy:()=>Bw,updateProject:()=>hn,updateProjectAccess:()=>Oi,updateProjectAgent:()=>Vk,updateProjectDefaultAgent:()=>El,updateProjectGroupGrant:()=>Ki,updateProjectSandboxProvider:()=>gi,updateProjectSession:()=>sl,updateProjectTrigger:()=>bl,updateRole:()=>zu,updateRolePermissions:()=>Yu,updateSandboxTemplate:()=>sc,updateSessionPolicy:()=>dA,updateSessionReminder:()=>oo,updateSessionReminders:()=>Sp,updateTask:()=>Ak,updateTemplateWarmPool:()=>wx,updateTicket:()=>Mk,updateTicketStatus:()=>Ok,updateUserMetadata:()=>So,uploadAccountBrandingAsset:()=>qs,uploadAppArtifactArchive:()=>ad,uploadConnectorAttachment:()=>qr,uploadDriveFile:()=>vv,uploadFile:()=>Qt,uploadNativeFile:()=>zy,uploadPromptAttachment:()=>An,uploadSessionAttachment:()=>Yd,uploadSlackChannelFile:()=>lu,uploadTimeoutMsForBytes:()=>Bt,upsertCredential:()=>gR,upsertProjectGitCredential:()=>ta,upsertProjectSecret:()=>Qi,upsertSsoProvider:()=>oA,validateProjectManifest:()=>ii,validateReferralCode:()=>Ow,validateToken:()=>ri,verifyGatewayProvider:()=>Tw,verifyKortixToken:()=>cP,verifyOtp:()=>yo,verifySsoDomain:()=>iA,wakeEscalationAttemptSummary:()=>Nj,wakeEscalationNote:()=>Lj,wakeProgressFingerprint:()=>Dj,wireIdClock:()=>_t,wireIdClockAt:()=>Nt,wireIdClockDelta:()=>Pt,workedForLabel:()=>fM,workingExpiryAtMs:()=>Aj,workingTurnDrawsBusyRow:()=>QE,writeActivityGroupLabel:()=>Nv,writeFile:()=>Xn,wsDomain:()=>Qo,wsFavicon:()=>zT,wsRootDomain:()=>VT});var NP={backendUrl:"",getToken:async()=>null},ms=null,xr=null;function KP(e){xr=e}function qP(){return xr}function Sr(e,t){t?.global!==!1&&(ms=e)}function v(){return xr?.()??ms??NP}function wr(){return ms!==null||xr?.()!==void 0}function BP(e){return new Promise(t=>setTimeout(t,e))}async function Ar(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 BP(o)),i=await e(),i)return i;return i}var fs=12e4;function GP(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Um(e,t,n=fs){let r=e instanceof Request?e.signal:t?.signal;if(GP(e))return r??void 0;let o=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,o]):r:o}function vr(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var h=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)}},Z=class extends h{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},qe=class extends h{constructor(t,n,r,o={}){super(r||n.message||`Billing Error: ${t}`,{...o,status:t,detail:n}),this.name="BillingError"}},at=class extends h{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"}},WP="ENDPOINT_RETIRED";function U(e,t){let n=t?` ${t}`:"";return new h(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:WP})}var kr="feature_disabled";function Lm(e){if(!(e instanceof h)||e.status!==403||e.code!==kr)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function ys(e){let t=Lm(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function hs(e){let t=Lm(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function un(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 qe(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 bs(e){return e instanceof qe}function kt(e){if(e instanceof Z)return!0;let t=e?.status;return t===401||t===403}function _s(e){if(!(e instanceof qe))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 he(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function be(e,t){return new Promise((n,r)=>{let o=()=>{t.removeEventListener("abort",o),r(he())};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o)),t.aborted&&o()})}function Rr(e,t){return new Promise((n,r)=>{let o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),r(he())},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.aborted?o():t?.addEventListener("abort",o,{once:!0})})}var Fm="request_deadline",HP=/^Request exceeded the \d+s server processing deadline$/,Nm=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Fm||HP.test(n),VP="git_mirror_unavailable",zP=/^git mirror is temporarily unavailable$/,YP=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===VP||zP.test(n);async function QP(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await be(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 he();return{message:n,data:r}}function XP(e,t,n){return Nm(e,t,n)||YP(e,t,n)||e===501&&t?.code===Ps||e===409&&(t?.code===xs||t?.code===Ss)||e===503&&(t?.code===ws||t?.code===As)}async function Km(e,t,n,r){let{message:o,data:s}=await QP(e,t),i=new h(o,{status:e.status,response:e,details:s||void 0,data:s,detail:s?.detail,code:Nm(e.status,s,o)?Fm:s?.code||s?.error_code||s?.detail?.error_code||e.status.toString()});e.status===402&&(i=un(i));let a=e.status!==403?null:s?.code==="account_mfa_required"?"kortix:mfa-required":s?.code==="sso_required"?"kortix:sso-required":null;if(a&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a))}catch{}return e.status===431&&(i=new at(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&&!XP(e.status,s,o)&&v().onError?.(i,r),{error:i,success:!1}}var qm="X-Kortix-Impersonate",ks="kortix.impersonation",ct=null,Cr=!1,vs=new Set;function Rs(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function Bm(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 JP(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 Gm(){for(let e of vs)try{e()}catch{}}function Wm(){return Cr||(Cr=!0,ct=JP(Rs()?.getItem(ks)??null)),ct&&!Bm(ct)?(Cs(),null):ct}function ZP(e){if(Cr=!0,!e){Cs();return}ct=e;try{Rs()?.setItem(ks,JSON.stringify(e))}catch{}Gm()}function Cs(){Cr=!0;let e=ct!==null;ct=null;try{Rs()?.removeItem(ks)}catch{}e&&Gm()}function ex(e){return vs.add(e),()=>{vs.delete(e)}}var tx=/(^|\/)admin\/(api|analytics)(\/|$)/;function Hm(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!tx.test(t)}function Is(e){if(e!==void 0&&!Hm(e))return{};let t=Wm();return t?{[qm]:t.grantId}:{}}var Os=!1;function zm(e){Os=e}function Ym(){return Os}function nx(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function Es(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function pn(e,t,n){let r=t.toLowerCase();for(let o of Object.keys(e))o.toLowerCase()===r&&delete e[o];e[t]=n}function Ir(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[o,s]of r.flatMap(nx))pn(n,o,s);return n}function Ms(e,t,n){let r={...t},o=v().clientVersion?.trim();o&&!Es(r,"x-kortix-client-version")&&pn(r,"X-Kortix-Client-Version",o),Os&&pn(r,"x-kortix-admin-bypass","1");for(let[s,i]of Object.entries(Is(e)))pn(r,s,i);return Es(r,"authorization")||pn(r,"Authorization",`Bearer ${n}`),r}async function Er(e,t){let n=await Tr();if(!n)throw new Z;return{headers:new Headers(Ms(e,Ir(e,{headers:t}),n)),rejected:()=>dn(n)}}function rx(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function Vm(e,t,n,r,o){if(t instanceof Request){let c=new Headers(Ms(t.url,Ir(t,n),r));return e(new Request(t,{headers:c,...o?{signal:o}:{}}))}let s=String(t),i=Ms(s,Ir(t,n),r),a=s.startsWith("/")&&!s.startsWith("//");return e(s,{...n,headers:i,...a?{credentials:"same-origin"}:{},...o?{signal:o}:{}})}var Qm=null;async function Ds(e){let t=await Ar(()=>v().getToken(),e);return t&&(Qm=t),t}var Tr=Ds;function dn(e=Qm){e&&v().getToken.invalidate?.(e)}var Ts=new Map;function ox(e){let t=Ts.get(e);if(t)return t;let n=(async()=>(dn(e),Tr({attempts:2,baseDelayMs:200})))().finally(()=>Ts.delete(e));return Ts.set(e,n),n}async function lt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:o=fs}=n,s=n.fetch??v().fetch??fetch,i=o===null?(e instanceof Request?e.signal:t.signal)??void 0:Um(e,t,o);if(i?.aborted)throw he();let a=await(i?be(Tr(),i):Tr());if(!a)throw new Z;let c=r&&!rx(t)&&!Es(Ir(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await Vm(s,e,t,a,i);if(d.status!==401||!c)return d;let g=await ox(a);return!g||g===a?d:Vm(s,p,t,g,i)}async function Te(e,t,n,r){let o=await lt(e,t,n);if(o.ok)return o;let s=await o.text().catch(()=>"");throw new h(s||`${r} (HTTP ${o.status})`,{status:o.status,response:o})}var Xm=()=>v().backendUrl||"",sx=new Set([502,503,504]),ix=e=>sx.has(e),Jm=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},ax=e=>Jm(e)||(e??"GET").toUpperCase()==="DELETE",cx=2,Mr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function Ee(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 lx(e,i,n,r,o,s,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function lx(e,t,n,r,o,s,i,a){try{if(t.signal?.aborted)throw he();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 px(e,t,c,o,s,i,a);if(p instanceof Z)return{error:p,success:!1};if(!p.ok)return await Km(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await be(p.json(),a.activeController.signal):g?.includes("text/")?d=await be(p.text(),a.activeController.signal):d=await be(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return dx(c,e,t.method,n,r,o,a)}finally{Or(a)}}function Or(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function ux(e,t,n){try{await be(e.arrayBuffer(),t)}catch(r){if(Mr(r))throw r}finally{Or(n)}}async function px(e,t,n,r,o,s,i){let a=Jm(t.method),c=ax(t.method),p=c?cx+1:1,d;for(let g=0;g<p;g++){g>0&&await Rr(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 be(lt(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 Z)return new Z;if(i.didTimeout&&Mr(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(Mr(f)||g===p-1)throw f;continue}if(!a||!ix(d.status)||g===p-1)return o||Or(i),d;await ux(d,m.signal,i)}return d}function dx(e,t,n,r,o,s,i){Or(i);let a=Mr(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new h("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(Xm(),"")||t;c=new h(`Request timed out after ${Math.round(s/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:s})}else e instanceof Error?(c=new h(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(Xm(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&v().onError?.(c,o)):(c=new h(String(e)),r&&v().onError?.(c,o));return{error:c,success:!1}}var Me=()=>v().backendUrl||"",Ps="feature_not_supported",xs="model_not_servable",Ss="provision_in_flight",ws="analytics_unavailable",As="accounts_list_unavailable",gx={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let o=new h(r.message||"Database error",{code:r.code,details:r});return v().onError?.(o,t),{error:o,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new h(n.message,{name:n.name||"ApiError",stack:n.stack}):new h(String(n));return v().onError?.(r,t),{error:r,success:!1}}}};async function mx(e,t,n={}){let{timeout:r=3e4,fetch:o}=n,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await lt(`${Me()}${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 Z)return vr();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>Ee(`${Me()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>Ee(`${Me()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>Ee(`${Me()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>Ee(`${Me()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>Ee(`${Me()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>Ee(`${Me()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],Ee(`${Me()}${e}`,{...o,method:"POST",body:t,headers:s})},uploadPut:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],Ee(`${Me()}${e}`,{...o,method:"PUT",body:t,headers:s})},postStream:mx};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function js(e){return e.replace(/\/v1\/?$/,"")}async function Rt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=js(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 $s(){return u(await l.get("/accounts"))}async function Us(e){return u(await l.post("/accounts",e))}async function Ls(e){return u(await l.get(`/accounts/${e}`))}async function Fs(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function Ns(e){return u(await l.get(`/accounts/${e}/branding`))}async function Ks(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function qs(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 Bs(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function Gs(e){return u(await l.delete(`/accounts/${e}/branding`))}async function Ws(e){return u(await l.get(`/accounts/${e}/members`))}async function Hs(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Vs(e){return u(await l.get(`/accounts/${e}/invites`))}async function zs(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function Ys(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Qs(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function Xs(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function Js(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}async function Zs(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function ei(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function ti(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function ni(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function fx(e){return Rt(e,"/v1/accounts")}async function ri(){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 yx=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","apps","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","us_region","event_triggers","notification_center","volumes","stateless_sessions","drives","ephemeral_sandboxes","session_log"];async function ut(){return u(await l.get("/projects"))}async function oi(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function gn(e,t){return u(await l.get(`/projects/${e}`,t))}async function si(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function ii(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function ai(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function hx(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function mn(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 fn(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function yn(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function bx(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function ci(e){return u(await l.post("/projects",e))}async function li(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function ui(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Zm=200;function _x(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>
|
|
3
|
+
`);try{return JSON.parse(n)}catch(r){let o=n.length>Zm?`${n.slice(0,Zm)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${o})`,{cause:r})}}async function Px(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 h(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=zP(g);if(m){if(t(m),m.type==="error")throw new b(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{o.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function QP(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function ln(e,t){return u(await l.patch(`/projects/${e}`,t))}async function ni(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function ri(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function oi(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function XP(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function JP(e,t){throw F("updateTemplateWarmPool")}async function si(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function ZP(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function un(e){return u(await l.delete(`/projects/${e}`))}async function ex(e,t){return Pt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function tx(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=ks(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 ii(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function ai(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function ci(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function li(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ui(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function pi(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function di(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let 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 gi(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 mi(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function fi(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function yi(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function hi(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await l.delete(`/projects/github/installation?${n.toString()}`))}async function bi(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function _i(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await l.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function nx(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Pi(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function xi(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Si(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function wi(e){return u(await l.get(`/projects/${e}/access`))}async function vi(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function Ai(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function rx(e){return"status"in e&&e.status==="invited"}async function ki(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 Ri(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function Ii(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Ci(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Ti(e){return u(await l.get(`/projects/${e}/group-grants`))}async function Ei(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 Mi(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 Oi(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function Di(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function ji(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 $i(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function Ui(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Fi(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Li(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 Ni(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Ki(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function qi(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Gi(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Bi(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function Ar(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 kr(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Wi(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var ox=2e3,sx=3e3,ix=10*6e4;async function ax(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 Ar(t,n,r);if(c())return{status:"cancelled"};o?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(ox,p.interval_ms||sx),g=p.expires_at||a()+ix;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await kr(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 Hi(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function Vi(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function zi(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 Qi=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,xt=(e,t)=>`${Qi(e)}/${encodeURIComponent(t)}`,qm=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Xi(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${Qi(e)}${n}`))}async function Ji(e,t){return u(await l.post(Qi(e),t))}async function Zi(e,t,n){return u(await l.put(`${xt(e,t)}/value`,{value:n}))}async function ea(e,t){return u(await l.post(`${xt(e,t)}/retry`))}async function ta(e,t){return u(await l.delete(xt(e,t)))}async function na(e,t,n,r){return u(await l.put(`${xt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function ra(e,t,n,r){return u(await l.delete(`${xt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function oa(e,t,n,r){return u(await l.put(`${xt(e,t)}/access`,{mode:n,user_ids:r}))}async function sa(e,t,n){return u(await l.get(qm(e,t,n)))}async function ia(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function aa(e,t,n,r){return u(await l.put(qm(e,t,n),{secret_ids:r}))}async function Rr(){return As()}async function Gm(e){return fr(()=>k().getToken(),e,Ir)}function Ir(){rn()}function cx(e){e===null&&rn()}function lx(e){}async function St(){return Rr()}async function ux(e){return Gm(e)}async function E(e,t,n){try{return await rt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof Q)return yr();throw r}}function Cr(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function wt(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`${Cr(e,"catalog")}${r}`)).connectors??[]}async function Tr(e){let t=[];for(let n of await wt(e,{includeSchemas:!1}))for(let r of n.actions)t.push({tool:`${n.slug}.${r.path}`,connector:n.slug,action:r.path,risk:r.risk,description:r.description||r.name,inputSchema:r.inputSchema});return t}async function ca(e,t="",n={}){let r=t.trim().toLowerCase(),o=r.split(/\s+/).filter(Boolean),s=[],i=[];for(let a of await Tr(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 Er(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 wt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!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,outputSchema:s.outputSchema??null}}return null}function px(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var dx=9e4;async function st(e,t,n={},r={}){let{connector:o,action:s}=px(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(Cr(e,"call"),{connector:o,action:s,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??dx,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function Mr(e,t){let n=await l.get(Cr(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function gx(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 mx(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 Or(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=mx(k().backendUrl),a=Cr(e,"attachments"),c=await E(`${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(gx(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 fx(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 la(e){return u(await l.get(`/projects/${e}/connections`))}async function ua(e){return u(await l.get(`/projects/${e}/connections/all`))}async function pa(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function da(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function ga(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function Ce(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function yx(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function hx(e,t,n){return u(await l.put(Ce(e,t,"application"),n))}async function bx(e,t){return u(await l.get(Ce(e,t,"application")))}async function _x(e,t,n){return u(await l.post(Ce(e,t,"discover"),n))}async function Px(e,t,n={}){return u(await l.post(Ce(e,t,"discover-resource"),n))}async function xx(e,t,n){return u(await l.post(Ce(e,t,"register"),n))}async function Sx(e,t,n){return u(await l.post(Ce(e,t,"authorize"),n))}async function wx(e,t,n){return u(await l.post(Ce(e,t,"device"),n))}async function vx(e,t,n){return u(await l.post(Ce(e,t,`device/${encodeURIComponent(n)}`),{}))}async function Ax(e,t){return u(await l.get(Ce(e,t,"status")))}async function ma(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function fa(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function ya(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function ha(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function ba(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function _a(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Pa(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function xa(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Sa(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 wa(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function va(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Aa(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function ka(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Ra(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Ia(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function kx(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function Rx(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Ca(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Ta(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Bm(e,t,n={}){return u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var Ea=Bm;async function Ix(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Ma(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function Oa(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function Da(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function ja(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,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 $a(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function Cx(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 Tx(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 Dr(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 Ua(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function jr(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var Ex=Dr,Mx=jr;async function Fa(){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 Na(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function Ox(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Wm(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 Ka=Wm;var pn=class extends b{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:o,action:s,binding:i,upstreamStatus:a,retryAfterSeconds:c,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=o,this.action=s,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},$r=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},Ur=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,o){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=o,Object.setPrototypeOf(this,new.target.prototype)}},ye=e=>typeof e=="string"&&e?e:null;function Hm(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function Dx(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function jx(e,t,n){if(!(e instanceof b)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},o=ye(r.reason)??ye(r.error)??e.message,s=/^upstream_(\d{3})\b/.exec(o),i=typeof r.upstream_status=="number"?r.upstream_status:s?Number(s[1]):null;return new pn(ye(r.message)??ye(r.hint)??o,{status:e.status,code:i===null?Hm(o):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:o,connector:ye(r.connector)??t,action:ye(r.action)??n,binding:ye(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:Dx(e.response),connectUrl:ye(r.connect_url),hint:ye(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:ye(r.requested_account)})}function $x(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function Fr(e,t,n,r={},o={}){let s=t.trim(),i=n.trim();if(!s||!i)throw new Error("connector slug and action are required");let a;try{a=await st(e,`${s}.${i}`,r,o)}catch(c){throw jx(c,s,i)}if(a.status==="pending_approval")throw new $r(s,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new pn(c,{status:200,code:a.upstream_error?"upstream_error":Hm(c),details:a,data:a,reason:c,connector:s,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return $x(a)}async function*qa(e,t,n,r,o){let{next:s,maxPages:i=100,...a}=o,c=r;for(let p=0;c;p++){if(p>=i)throw new Ur(t,n,i,c);let d=await Fr(e,t,n,c,a);yield d,c=s(d,c)}}async function Ga(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function Ba(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Wa(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Ha(e){return u(await l.get(`/projects/${e}/snapshots`))}async function dn(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Va(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function za(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Ya(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function Qa(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Xa(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Ja(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Za(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function gn(e){let t=new URL(k().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Kortix backend: ${n.origin}`);let{headers:r}=await Sr(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function ec(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function tc(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),u(await l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function nc(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await l.get(`/projects/${e}/files/search?${r.toString()}`))}async function rc(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var Ux=10*6e4;async function oc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"",s=`${k().backendUrl||""}/projects/${e}/files/archive${o}`;return await(await ke(s,{method:"GET"},{timeoutMs:Ux},"Failed to download")).blob()}async function sc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"";return gn(`${k().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${o}`)}async function Fx(e,t,n,r){let o=new URLSearchParams({path:t});n&&o.set("ref",n);let s=o.toString()?`?${o.toString()}`:"",i=`${k().backendUrl||""}/projects/${e}/files/raw${s}`;return await(await ke(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var ic=52428800,Lx=104857600,Vm=20;var Nr=e=>`/projects/${encodeURIComponent(e)}/attachments`,Kr={showErrors:!1,deadlineCoversBody:!0},zm=3e4,Nx=12e4,Kx=6e4,qx=5*6e4,Gx=6e4,Bx=6e4;function Lr(){return new b("Request aborted",{name:"AbortError",code:"ABORTED"})}function mn(e){if(e?.aborted)throw Lr()}function Wx(e){return!(e instanceof b)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function fn(e,t,n=!1){let r;for(let o=0;;o++){mn(t);try{return await e()}catch(s){let i=n&&s instanceof b&&s.status===409&&s.code==="attachment_processing";if(t?.aborted||!(Wx(s)||i))throw s;r??=Date.now()+(n?qx:Kx);let a=Math.min(8e3,500*2**o)*(.5+Math.random()/2);if(Date.now()+a>=r)throw s;try{await br(a,t)}catch{throw mn(t),s}}}}function Hx(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function ac(e,t,n){let r=e?.upload,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"&&Hx(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 Ym(e,t,n,r){return u(await l.post(Nr(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Kr,signal:n,timeout:zm}),"Failed to start attachment upload")}async function Qm(e,t,n,r){let o=ac({...await fn(()=>Ym(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(o),o}function Xm(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 Vx(e){if(!(e instanceof b))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function zx(e,t,n,r){return new Promise((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()},Gx)},m=()=>{d(Lr()),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(Xm(i.status,i.responseText))},i.onerror=()=>d(new b("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(Lr()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function Yx(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"?Lr():new b(s instanceof Error?s.message:String(s),{name:s instanceof Error?s.name:"TypeError"})}if(!o.ok)throw Xm(o.status,await o.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function Qx(e,t,n){mn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?zx(r,e,t,n):Yx(e,t,n)}async function Xx(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 fn(()=>Qx(i,t,r),r.signal)}catch(a){let c=Vx(a);if(c!==409){if(s||!(c===400||c===401||c===403))throw a;s=!0,o=await Qm(e,t,o,r);continue}}return o={...o,received_bytes:t.size},r.onUpload?.(o),o}return Jm(e,t,o,r)}async function Jm(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let o=n.upload.chunk_size,s=`${Nr(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){mn(r.signal);let a=i.received_bytes,c=Math.min(a+o,t.size),p=t.slice(a,c),d=await fn(async()=>u(await l.putRaw(`${s}/chunks/${a/o}`,p,{...Kr,signal:r.signal,timeout:zm}),"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 yn(e,t,n={}){if(!e)throw new Error("A project is required to upload attachments");if(!Number.isSafeInteger(t.size)||t.size<=0||t.size>52428800)throw new Error("Attachment must contain 1 byte to 50 MiB");mn(n.signal);let r=n.resume?ac({...n.resume},t):ac({...await fn(()=>Ym(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()<Bx&&(r=await Qm(e,t,r,n)),r=r.upload.kind==="direct"?await Xx(e,t,r,n):await Jm(e,t,r,n)),n.onProcessing?.();let o=`${Nr(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await fn(async()=>u(await l.post(`${o}/complete`,{},{...Kr,signal:n.signal,timeout:Nx}),"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 vt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${Nr(e)}/${encodeURIComponent(t)}`,{...Kr,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function cc(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/branches${r}`))}async function lc(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 uc(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function pc(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 dc(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await l.get(`/projects/${e}/files/history?${r.toString()}`))}async function gc(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 mc(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit));let o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${o}`,{showErrors:!1,timeout:15e3}))}async function fc(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function yc(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function hc(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function bc(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function _c(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Pc(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function xc(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Sc(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function wc(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function vc(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var At=new Set,Jx=500;function hn(e){e&&(At.add(e),At.size>Jx&&At.delete(At.values().next().value))}function Ac(e){return!!e&&At.has(e)}function Zx(e){e&&At.delete(e)}function kc(e){return!!e&&e.available===!0&&e.source==="mirror"&&Array.isArray(e.messages)&&e.messages.length>0&&!!(e.runtime_session_id??e.opencode_session_id)}var qr=1,eS=12,tS=15e5,nS=3e5,rS=336*60*60*1e3,oS="kortix.saved-copy";function Rc(e){return!!e&&typeof e.then=="function"}function sS(e,t){return Rc(e)?e.then(t):t(e)}function iS(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 aS(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}function cS(e){let{storage:t,userId:n,maxSessions:r=eS,maxBytes:o=tS,maxEnvelopeBytes:s=nS,maxAgeMs:i=rS,namespace:a=oS,now:c=()=>Date.now()}=e,p=`${a}:${n}:`,d=`${p}index`,g=(w,P)=>`${p}${w}/${P}`,m=w=>{try{let P=t.getItem(w);return Rc(P)?P.catch(()=>null):P}catch{return null}},f=w=>{try{let P=t.removeItem(w);Rc(P)&&P.catch(()=>{})}catch{}},h=async w=>{try{await t.removeItem(w)}catch{}},S=w=>{if(!w)return[];try{let P=JSON.parse(w);return P?.v===qr&&Array.isArray(P.entries)?P.entries:[]}catch{return[]}},D=Promise.resolve(),j=w=>{let P=D.then(w,w);return D=P.catch(()=>{}),P},L=async w=>{try{await t.setItem(d,JSON.stringify({v:qr,entries:w}))}catch{}},y=async()=>S(await m(d)),_=async(w,P)=>{let A=[...w].sort((T,N)=>T.u-N.u),C=A.reduce((T,N)=>T+N.b,0);for(;A.length>r||C>o;){let T=A.findIndex($=>$.s!==P);if(T===-1)break;let[N]=A.splice(T,1);C-=N.b,await h(`${p}${N.s}`)}return A},x=w=>{j(async()=>{let P=await y(),A=P.find(C=>C.s===w);A&&(A.u=c(),await L(P))})},M=w=>j(async()=>{await h(`${p}${w}`);let P=await y(),A=P.filter(C=>C.s!==w);A.length!==P.length&&await L(A)});return{keyFor:g,read(w,P){let A=`${w}/${P}`;return sS(m(g(w,P)),C=>{if(!C)return null;let T;try{T=JSON.parse(C)}catch{return f(g(w,P)),M(A),null}return!T||T.v!==qr||T.user!==n||c()-T.at>i||!kc(T.e)?(f(g(w,P)),M(A),null):(x(A),T.e)})},write(w,P,A){let C=`${w}/${P}`;if(!kc(A))return M(C);let T={v:qr,user:n,at:c(),e:A},N=iS(T,s);if(N===null)return M(C);let $=aS(A);return j(async()=>{let K=await y(),q=K.find(Se=>Se.s===C);if(q&&$>0&&q.c>$)return;let de=K.filter(Se=>Se.s!==C),le={s:C,b:N.length,u:c(),c:$},Je=await _([...de,le],C),yt=g(w,P);try{await t.setItem(yt,N)}catch{let Se=Je.filter(we=>we.s!==C).sort((we,ie)=>we.u-ie.u)[0];Se&&(await h(`${p}${Se.s}`),Je=Je.filter(we=>we.s!==Se.s));try{await t.setItem(yt,N)}catch{await h(yt),Je=Je.filter(we=>we.s!==C)}}await L(Je)})},remove(w,P){return M(`${w}/${P}`)},clear(){return j(async()=>{let w=await y();for(let P of w)await h(`${p}${P.s}`);await h(d)})}}}var Zm=null;function lS(e){Zm=e}function Ic(){return Zm}var uS=new Set;function ef(e){for(let t of uS)try{t(e)}catch{}}function pS(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 dS=50,tf=200,gS=tf;function nf(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 Cc(e,t){let n=await l.get(`/projects/${e}/sessions${nf(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function it(e,t){return u(await l.get(`/projects/${e}/sessions${nf(t)}`))}async function Tc(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Ec(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Mc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Oc(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}function mS(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 fS(e,t=new Date){let n=null;for(let r of e)r.resource_type!=="transcript"||r.revoked_at||r.expires_at&&Date.parse(r.expires_at)<=t.getTime()||(!n||Date.parse(r.created_at)>Date.parse(n.created_at))&&(n=r);return n}async function Dc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function jc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function $c(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Uc(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function at(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||hn(n?.session_id),n}async function Fc(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||hn(r.session.session_id),r}async function Lc(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return hn(n.session_id),n}async function bn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Nc(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 Kc(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 qc(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await l.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Gc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/turn`))}async function yS(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}))}function hS(e){if(e)return e==="interrupt"?"transcript":"composer"}async function _n(e,t,n){let r=n.placement??hS(n.delivery);return u(await l.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Bc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Wc(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Hc(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Vc(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function zc(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Yc(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Qc(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function Xc(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return Ic()?.remove(e,t),n}async function Pn(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,n.reset_machine?{reset_machine:!0,...n.discard_state?{discard_state:!0}:{}}:{}))}async function xn(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return ef(t),n}async function Jc(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function bS(e){let t=e.split(`
|
|
7
|
+
`);let m=_x(g);if(m){if(t(m),m.type==="error")throw new h(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 xx(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function hn(e,t){return u(await l.patch(`/projects/${e}`,t))}async function pi(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function di(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function gi(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function Sx(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function wx(e,t){throw U("updateTemplateWarmPool")}async function mi(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function Ax(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function bn(e){return u(await l.delete(`/projects/${e}`))}async function vx(e,t){return Rt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function kx(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=js(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 fi(e,t,n){return u(await l.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function yi(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function hi(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function bi(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function _i(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Pi(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function xi(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 Si(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 wi(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function Ai(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function vi(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function ki(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 Ri(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function Ci(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 Rx(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Ii(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function Ti(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Ei(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Mi(e){return u(await l.get(`/projects/${e}/access`))}async function Oi(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function Di(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function Cx(e){return"status"in e&&e.status==="invited"}async function ji(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 $i(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function Ui(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Li(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Fi(e){return u(await l.get(`/projects/${e}/group-grants`))}async function Ni(e,t,n,r){return u(await l.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function Ki(e,t,n,r){return u(await l.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function qi(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function Bi(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function Gi(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 Wi(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function Hi(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Vi(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function zi(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 Yi(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Qi(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function Xi(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Ji(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Zi(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function Dr(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 jr(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function ea(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Ix=2e3,Tx=3e3,Ex=10*6e4;async function Mx(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 Dr(t,n,r);if(c())return{status:"cancelled"};o?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Ix,p.interval_ms||Tx),g=p.expires_at||a()+Ex;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await jr(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 ta(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function na(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function ra(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function oa(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var sa=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Ct=(e,t)=>`${sa(e)}/${encodeURIComponent(t)}`,ef=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function ia(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${sa(e)}${n}`))}async function aa(e,t){return u(await l.post(sa(e),t))}async function ca(e,t,n){return u(await l.put(`${Ct(e,t)}/value`,{value:n}))}async function la(e,t){return u(await l.post(`${Ct(e,t)}/retry`))}async function ua(e,t){return u(await l.delete(Ct(e,t)))}async function pa(e,t,n,r){return u(await l.put(`${Ct(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function da(e,t,n,r){return u(await l.delete(`${Ct(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function ga(e,t,n,r){return u(await l.put(`${Ct(e,t)}/access`,{mode:n,user_ids:r}))}async function ma(e,t,n){return u(await l.get(ef(e,t,n)))}async function fa(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function ya(e,t,n,r){return u(await l.put(ef(e,t,n),{secret_ids:r}))}async function $r(){return Ds()}async function tf(e){return Ar(()=>v().getToken(),e,Ur)}function Ur(){dn()}function Ox(e){e===null&&dn()}function Dx(e){}async function It(){return $r()}async function jx(e){return tf(e)}async function E(e,t,n){try{return await lt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof Z)return vr();throw r}}function Lr(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Tt(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`${Lr(e,"catalog")}${r}`)).connectors??[]}async function Fr(e){let t=[];for(let n of await Tt(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 ha(e,t="",n={}){let r=t.trim().toLowerCase(),o=r.split(/\s+/).filter(Boolean),s=[],i=[];for(let a of await Fr(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 Nr(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 Tt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!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,outputSchema:s.outputSchema??null}}return null}function $x(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var Ux=9e4;async function pt(e,t,n={},r={}){let{connector:o,action:s}=$x(t),i=r.account?.trim(),a=r.approvalContext?.trim(),c=u(await l.post(Lr(e,"call"),{connector:o,action:s,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??Ux,signal:r.signal}));return c.ok&&c.binding!==void 0&&!("output"in c)&&(c.output=c.data),c}async function Kr(e,t){let n=await l.get(Lr(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function Lx(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 Fx(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 qr(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=Fx(v().backendUrl),a=Lr(e,"attachments"),c=await E(`${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 h(Lx(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 Nx(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 ba(e){return u(await l.get(`/projects/${e}/connections`))}async function _a(e){return u(await l.get(`/projects/${e}/connections/all`))}async function Pa(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function xa(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function Sa(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function Oe(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function Kx(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function qx(e,t,n){return u(await l.put(Oe(e,t,"application"),n))}async function Bx(e,t){return u(await l.get(Oe(e,t,"application")))}async function Gx(e,t,n){return u(await l.post(Oe(e,t,"discover"),n))}async function Wx(e,t,n={}){return u(await l.post(Oe(e,t,"discover-resource"),n))}async function Hx(e,t,n){return u(await l.post(Oe(e,t,"register"),n))}async function Vx(e,t,n){return u(await l.post(Oe(e,t,"authorize"),n))}async function zx(e,t,n){return u(await l.post(Oe(e,t,"device"),n))}async function Yx(e,t,n){return u(await l.post(Oe(e,t,`device/${encodeURIComponent(n)}`),{}))}async function Qx(e,t){return u(await l.get(Oe(e,t,"status")))}async function wa(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Aa(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function va(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function ka(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Ra(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Ca(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Ia(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function Ta(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Ea(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 Ma(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Oa(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Da(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function ja(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function $a(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Ua(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function Xx(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function Jx(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function La(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Fa(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function nf(e,t,n={}){return u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var Na=nf;async function Zx(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Ka(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function qa(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function Ba(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Ga(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 Wa(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 eS(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 tS(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 Br(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 Ha(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 Gr(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var nS=Br,rS=Gr;async function Va(){return u(await l.get("/connectors/connect-status"))}async function za(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 Ya(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function oS(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function rf(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 Qa=rf;var _n=class extends h{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:o,action:s,binding:i,upstreamStatus:a,retryAfterSeconds:c,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=o,this.action=s,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=c??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},Wr=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},Hr=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,o){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=o,Object.setPrototypeOf(this,new.target.prototype)}},_e=e=>typeof e=="string"&&e?e:null;function of(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function sS(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function iS(e,t,n){if(!(e instanceof h)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},o=_e(r.reason)??_e(r.error)??e.message,s=/^upstream_(\d{3})\b/.exec(o),i=typeof r.upstream_status=="number"?r.upstream_status:s?Number(s[1]):null;return new _n(_e(r.message)??_e(r.hint)??o,{status:e.status,code:i===null?of(o):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:o,connector:_e(r.connector)??t,action:_e(r.action)??n,binding:_e(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:sS(e.response),connectUrl:_e(r.connect_url),hint:_e(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:_e(r.requested_account)})}function aS(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function Vr(e,t,n,r={},o={}){let s=t.trim(),i=n.trim();if(!s||!i)throw new Error("connector slug and action are required");let a;try{a=await pt(e,`${s}.${i}`,r,o)}catch(c){throw iS(c,s,i)}if(a.status==="pending_approval")throw new Wr(s,i,a);if(!a.ok||a.upstream_error){let c=a.upstream_error??a.reason??"connector_error";throw new _n(c,{status:200,code:a.upstream_error?"upstream_error":of(c),details:a,data:a,reason:c,connector:s,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return aS(a)}async function*Xa(e,t,n,r,o){let{next:s,maxPages:i=100,...a}=o,c=r;for(let p=0;c;p++){if(p>=i)throw new Hr(t,n,i,c);let d=await Vr(e,t,n,c,a);yield d,c=s(d,c)}}async function Ja(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function Za(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function ec(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function tc(e){return u(await l.get(`/projects/${e}/snapshots`))}async function Pn(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function nc(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function rc(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function oc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function sc(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function ic(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function ac(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function cc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function xn(e){let t=new URL(v().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Kortix backend: ${n.origin}`);let{headers:r}=await Er(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function lc(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 uc(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),u(await l.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function pc(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 dc(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var cS=10*6e4;async function gc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"",s=`${v().backendUrl||""}/projects/${e}/files/archive${o}`;return await(await Te(s,{method:"GET"},{timeoutMs:cS},"Failed to download")).blob()}async function mc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"";return xn(`${v().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${o}`)}async function lS(e,t,n,r){let o=new URLSearchParams({path:t});n&&o.set("ref",n);let s=o.toString()?`?${o.toString()}`:"",i=`${v().backendUrl||""}/projects/${e}/files/raw${s}`;return await(await Te(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var fc=52428800,uS=104857600,sf=20;var Yr=e=>`/projects/${encodeURIComponent(e)}/attachments`,Qr={showErrors:!1,deadlineCoversBody:!0},af=3e4,pS=12e4,dS=6e4,gS=5*6e4,mS=6e4,fS=6e4;function zr(){return new h("Request aborted",{name:"AbortError",code:"ABORTED"})}function Sn(e){if(e?.aborted)throw zr()}function yS(e){return!(e instanceof h)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function wn(e,t,n=!1){let r;for(let o=0;;o++){Sn(t);try{return await e()}catch(s){let i=n&&s instanceof h&&s.status===409&&s.code==="attachment_processing";if(t?.aborted||!(yS(s)||i))throw s;r??=Date.now()+(n?gS:dS);let a=Math.min(8e3,500*2**o)*(.5+Math.random()/2);if(Date.now()+a>=r)throw s;try{await Rr(a,t)}catch{throw Sn(t),s}}}}function hS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function yc(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"&&hS(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 cf(e,t,n,r){return u(await l.post(Yr(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Qr,signal:n,timeout:af}),"Failed to start attachment upload")}async function lf(e,t,n,r){let o=yc({...await wn(()=>cf(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(o),o}function uf(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 h(r,{status:e,details:n,code:String(n?.statusCode??e)})}function bS(e){if(!(e instanceof h))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function _S(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 h("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},mS)},m=()=>{d(zr()),i.abort()};i.open(t.method,t.url);for(let[f,b]of Object.entries(t.headers))i.setRequestHeader(f,b);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(uf(i.status,i.responseText))},i.onerror=()=>d(new h("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(zr()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function PS(e,t,n){let r=v().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"?zr():new h(s instanceof Error?s.message:String(s),{name:s instanceof Error?s.name:"TypeError"})}if(!o.ok)throw uf(o.status,await o.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function xS(e,t,n){Sn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?_S(r,e,t,n):PS(e,t,n)}async function SS(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 wn(()=>xS(i,t,r),r.signal)}catch(a){let c=bS(a);if(c!==409){if(s||!(c===400||c===401||c===403))throw a;s=!0,o=await lf(e,t,o,r);continue}}return o={...o,received_bytes:t.size},r.onUpload?.(o),o}return pf(e,t,o,r)}async function pf(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let o=n.upload.chunk_size,s=`${Yr(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Sn(r.signal);let a=i.received_bytes,c=Math.min(a+o,t.size),p=t.slice(a,c),d=await wn(async()=>u(await l.putRaw(`${s}/chunks/${a/o}`,p,{...Qr,signal:r.signal,timeout:af}),"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 An(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");Sn(n.signal);let r=n.resume?yc({...n.resume},t):yc({...await wn(()=>cf(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()<fS&&(r=await lf(e,t,r,n)),r=r.upload.kind==="direct"?await SS(e,t,r,n):await pf(e,t,r,n)),n.onProcessing?.();let o=`${Yr(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await wn(async()=>u(await l.post(`${o}/complete`,{},{...Qr,signal:n.signal,timeout:pS}),"Failed to complete attachment upload"),n.signal,!0)}catch(s){throw r.upload.kind==="direct"&&s instanceof h&&s.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),s}}async function Et(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${Yr(e)}/${encodeURIComponent(t)}`,{...Qr,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function hc(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 bc(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 _c(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Pc(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 xc(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 Sc(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 wc(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 Ac(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function vc(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function kc(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function Rc(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function Cc(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Ic(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Tc(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Ec(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Mc(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function Oc(e,t,n){return u(await l.patch(`/projects/${e}/change-requests/${t}`,n))}var Mt=new Set,wS=500;function vn(e){e&&(Mt.add(e),Mt.size>wS&&Mt.delete(Mt.values().next().value))}function Dc(e){return!!e&&Mt.has(e)}function AS(e){e&&Mt.delete(e)}var kn="kortix.session/2",df=1,gf=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var ee=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),H=e=>typeof e=="string",Pe=e=>H(e)&&e.length>0,je=e=>e===null||H(e),z=(e,t)=>e===void 0||t(e),De=(...e)=>t=>e.includes(t),Rn=e=>Number.isInteger(e)&&e>=0,Ot=e=>typeof e=="number",yf=e=>e.schema===kn&&Rn(e.v),dt=e=>z(e,H),jc=e=>e===void 0||ee(e)&&Object.values(e).every(t=>ee(t)&&H(t.version)),hf=e=>e===null||ee(e)&&H(e.provider)&&H(e.model)&&dt(e.variant),vS=e=>e===null||ee(e)&&Ot(e.input)&&Ot(e.output)&&Ot(e.cache_read)&&Ot(e.cache_write)&&z(e.reasoning,Ot)&&z(e.cost,Ot),mf=e=>ee(e)&&(e.type==="text"&&H(e.text)||e.type==="attachment"&&H(e.mime)),kS=e=>ee(e)&&Array.isArray(e.content)&&e.content.every(mf)&&z(e.model_content,t=>Array.isArray(t)&&t.every(mf))&&typeof e.is_error=="boolean",ff={text:e=>H(e.text)&&z(e.bytes,Rn)&&dt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>H(e.text),attachment:e=>H(e.mime)&&dt(e.ref)&&z(e.bytes,Rn)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>H(e.call_id)&&H(e.name)&&Pe(e.kind)&&De("pending","running","complete","error")(e.status)&&z(e.result,kS),compaction:e=>je(e.summary)&&je(e.first_kept_message_id),subtask:e=>H(e.thread_id)&&H(e.agent)&&H(e.description),step:e=>De("start","finish")(e.phase),harness:e=>Pe(e.harness)&&Pe(e.kind)&&typeof e.model_visible=="boolean"};function RS(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!ee(r)||!Pe(r.id)||n.has(r.id)||!Object.hasOwn(ff,r.type)||!ff[r.type](r)||!jc(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function CS(e){return ee(e)&&yf(e)&&Pe(e.message_id)&&Pe(e.thread_id)&&Number.isInteger(e.seq)&&De("user","assistant","system")(e.role)&&De("turn","compaction","context")(e.kind)&&De("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&z(e.hidden_reason,De("failed_attempt","aborted","retracted","reverted","superseded"))&&z(e.origin,De("prompt","steer","command","automation","subagent","notification"))&&z(e.agent,je)&&z(e.reply_to,je)&&z(e.parent_message_id,je)&&dt(e.native_agent_id)&&dt(e.context_ref)&&hf(e.model)&&vS(e.usage)&&De("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||ee(e.error)&&Pe(e.error.code)&&H(e.error.message))&&H(e.created_at)&&je(e.completed_at)&&ee(e.producer)&&Pe(e.producer.harness)&&H(e.producer.harness_version)&&H(e.producer.adapter_version)&&jc(e.ext)&&RS(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function IS(e){return ee(e)&&yf(e)&&Pe(e.thread_id)&&je(e.parent_thread_id)&&(e.spawned_by===null||ee(e.spawned_by))&&H(e.created_at)}function TS(e){return ee(e)&&z(e.schema,t=>t===kn)&&z(e.v,Rn)&&dt(e.session_id)&&z(e.title,je)&&dt(e.created_at)&&z(e.restore_grade,De("native","converted","partial"))&&z(e.todos,Array.isArray)&&z(e.pending,t=>ee(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&z(e.selection,t=>ee(t)&&z(t.agent,je)&&hf(t.model??null))&&z(e.harness,t=>ee(t)&&H(t.current)&&Array.isArray(t.history))&&jc(e.ext)}function bf(e){return ee(e)&&Rn(e.generation)&&typeof e.has_more=="boolean"&&TS(e.session)&&Array.isArray(e.threads)&&e.threads.every(IS)&&(e.thread_id===null||Pe(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>CS(t)&&t.thread_id===e.thread_id)}var ES=e=>bf(e)&&e.messages.length>0;function MS(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let o=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(o.length<=t)return o}return null}var _f={paintable:ES,fit:MS,capturedAt:()=>0},OS=new WeakMap;function Pf(e,t,n){OS.set(e,{read:(r,o)=>t.read(r,o),write:async(r,o,s)=>{await t.write(r,o,s),await n(r,o)}})}function Sf(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 Xr=1,DS=12,jS=15e5,$S=3e5,US=336*60*60*1e3,wf="kortix.saved-copy";function $c(e){return!!e&&typeof e.then=="function"}function LS(e,t){return $c(e)?e.then(t):t(e)}function FS(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 NS(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var KS={paintable:Sf,fit:FS,capturedAt:NS};function qS(e){let t=xf(e,KS),n=xf({...e,namespace:`${e.namespace??wf}.log`},_f),r={...t,remove:async(o,s)=>{await Promise.all([t.remove(o,s),n.remove(o,s)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return Pf(r,n,t.remove),r}function xf(e,t){let{storage:n,userId:r,maxSessions:o=DS,maxBytes:s=jS,maxEnvelopeBytes:i=$S,maxAgeMs:a=US,namespace:c=wf,now:p=()=>Date.now()}=e,d=`${c}:${r}:`,g=`${d}index`,m=(x,S)=>`${d}${x}/${S}`,f=x=>{try{let S=n.getItem(x);return $c(S)?S.catch(()=>null):S}catch{return null}},b=x=>{try{let S=n.removeItem(x);$c(S)&&S.catch(()=>{})}catch{}},P=async x=>{try{await n.removeItem(x)}catch{}},j=x=>{if(!x)return[];try{let S=JSON.parse(x);return S?.v===Xr&&Array.isArray(S.entries)?S.entries:[]}catch{return[]}},L=Promise.resolve(),N=x=>{let S=L.then(x,x);return L=S.catch(()=>{}),S},y=async x=>{try{await n.setItem(g,JSON.stringify({v:Xr,entries:x}))}catch{}},_=async()=>j(await f(g)),w=async(x,S)=>{let I=[...x].sort((F,M)=>F.u-M.u),C=I.reduce((F,M)=>F+M.b,0);for(;I.length>o||C>s;){let F=I.findIndex(K=>K.s!==S);if(F===-1)break;let[M]=I.splice(F,1);C-=M.b,await P(`${d}${M.s}`)}return I},D=x=>{N(async()=>{let S=await _(),I=S.find(C=>C.s===x);I&&(I.u=p(),await y(S))})},T=x=>N(async()=>{await P(`${d}${x}`);let S=await _(),I=S.filter(C=>C.s!==x);I.length!==S.length&&await y(I)});return{keyFor:m,read(x,S){let I=`${x}/${S}`;return LS(f(m(x,S)),C=>{if(!C)return null;let F;try{F=JSON.parse(C)}catch{return b(m(x,S)),T(I),null}return!F||F.v!==Xr||F.user!==r||p()-F.at>a||!t.paintable(F.e)?(b(m(x,S)),T(I),null):(D(I),F.e)})},write(x,S,I){let C=`${x}/${S}`;if(!t.paintable(I))return T(C);let F={v:Xr,user:r,at:p(),e:I},M=t.fit(F,i);if(M===null)return T(C);let K=t.capturedAt(I);return N(async()=>{let q=await _(),ge=q.find(Re=>Re.s===C);if(ge&&K>0&&ge.c>K)return;let me=q.filter(Re=>Re.s!==C),jm={s:C,b:M.length,u:p(),c:K},ke=await w([...me,jm],C),ln=m(x,S);try{await n.setItem(ln,M)}catch{let Re=ke.filter(X=>X.s!==C).sort((X,ot)=>X.u-ot.u)[0];Re&&(await P(`${d}${Re.s}`),ke=ke.filter(X=>X.s!==Re.s));try{await n.setItem(ln,M)}catch{await P(ln),ke=ke.filter(X=>X.s!==C)}}await y(ke)})},remove(x,S){return T(`${x}/${S}`)},clear(){return N(async()=>{let x=await _();for(let S of x)await P(`${d}${S.s}`);await P(g)})}}}var Af=null;function BS(e){Af=e}function Uc(){return Af}var GS=new Set;function vf(e){for(let t of GS)try{t(e)}catch{}}function WS(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 HS=50,kf=200,VS=kf;function Rf(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 Lc(e,t){let n=await l.get(`/projects/${e}/sessions${Rf(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function gt(e,t){return u(await l.get(`/projects/${e}/sessions${Rf(t)}`))}async function Fc(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Nc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Kc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function qc(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}function zS(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 YS(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 Bc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function Gc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Wc(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Hc(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function mt(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||vn(n?.session_id),n}async function Vc(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||vn(r.session.session_id),r}async function zc(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return vn(n.session_id),n}async function Cn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Yc(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 Qc(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 Xc(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 Jc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/turn`))}async function QS(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}))}function XS(e){if(e)return e==="interrupt"?"transcript":"composer"}async function In(e,t,n){let r=n.placement??XS(n.delivery);return u(await l.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Zc(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function el(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function tl(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function nl(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function rl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function ol(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function sl(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function il(e,t){let n=u(await l.delete(`/projects/${e}/sessions/${t}`));return Uc()?.remove(e,t),n}async function Tn(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,n.reset_machine?{reset_machine:!0,...n.discard_state?{discard_state:!0}:{}}:{}))}async function En(e,t){let n=u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}));return vf(t),n}async function al(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function JS(e){let t=e.split(`
|
|
8
8
|
`).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).replace(/^ /,""));if(t.length===0)return null;try{return JSON.parse(t.join(`
|
|
9
|
-
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function
|
|
9
|
+
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function cl(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function ll(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 h(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
11
|
`);for(;m!==-1;){let f=c.slice(0,m);c=c.slice(m+2),m=c.indexOf(`
|
|
12
12
|
|
|
13
|
-
`);let h=bS(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 tl(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function nl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function rl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function ol(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function sl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function il(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function _S(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function al(e){return u(await l.get(`/projects/${e}/triggers`))}async function cl(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function ll(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function ul(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function pl(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function dl(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}async function gl(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await l.get(`/projects/${e}/triggers/event-types?${n}`))}async function ml(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var Ue=new Map;function fl(e,t){return`${e}::${t}`}function rf(e,t){Ue.delete(e),Ue.set(e,t)}function of(e,t){let n=fl(e,t),r=Ue.get(n);return r&&rf(n,r),r}function sf(e,t,n){let r=fl(e,t);if(!Ue.has(r)&&Ue.size>=512){let o=Ue.keys().next().value;o!==void 0&&Ue.delete(o)}rf(r,n)}function af(e,t){Ue.delete(fl(e,t))}function PS(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Sn(){return PS(k().backendUrl||"http://localhost:8008/v1")}function cf(){let e=k().sandboxId;return e?`${Sn()}/p/${e}/8000`:""}function xS(e,t=8e3){return`${Sn()}/p/${e}/${t}`}function Fe(e,t=8e3){return xS(e,t)}function SS(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 Gr=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 wS(e){return e instanceof Error&&e.name==="SessionStartError"}function vS(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 Gr(o,{status:n,code:r,terminal:!0}):null}function lf(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),typeof n=="object"&&n?.keepStopped&&s.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&s.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=s.size>0?`?${s.toString()}`:"";return l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function Le(e,t,n){let r=await lf(e,t,n);if(!r.success||!r.data){let o=vS(r.error);if(o&&!(o.status===404&&Ac(t)))throw o;return null}return uf(e,t,r.data)}async function yl(e,t,n){let r=await lf(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return uf(e,t,r.data)}function uf(e,t,n){let r=n.sandbox?.external_id,o=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&o&&sf(e,t,{runtimeSessionId:o,opencodeSessionId:o,runtimeUrl:Fe(r),sandboxId:r}),n}function AS(e,t){return["session-start",e,t]}async function hl(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function bl(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function _l(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 kS(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function pf(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function RS(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Br(e){let t=e.connectors_required?pf(e.connectors_required):void 0,n=e.connectors_personal?pf(e.connectors_personal):void 0;if(t&&n&&!RS(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 Pl(e,t,n){let r=Br(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function IS(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?xl(n.block):null}}async function CS(e,t,n){let r=xl(n,!0),o=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...o,block:o.block?xl(o.block):null}}function xl(e,t=!1){let n=Br(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 TS(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Sl(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var df="Use createPerSeatCheckout().";function wl(){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 ES(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function MS(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??wl(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),o=(n.tier?.display_name||"").trim()||r;return{family:ES(r),label:o,sublabel:null,isGrandfathered:!1}}async function gf(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?wl():t.data}function mf(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 vl(e){return gf(`/billing/account-state${mf(e)}`)}async function Al(e){return gf(`/billing/account-state/minimal${mf(e)}`)}async function kl(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 Rl(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 Il(){return u(await l.get("/billing/credit-breakdown"))}async function Cl(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function Tl(){return u(await l.get("/billing/tier-configurations"))}async function OS(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Pt(e,`/v1/billing/account-state${t}`)}async function El(e){throw F("createCheckoutSession",df)}async function Ml(e,t){throw F("confirmCheckoutSession",df)}async function Ol(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Dl(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function jl(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function $l(e,t,n){throw F("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Ul(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function Fl(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 Ll(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 Nl(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 DS(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Kl(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 jS(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 $S(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 US(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function FS(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function ql(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 Bl(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Wr(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 Wl(e={}){let t=new URLSearchParams;return Bl(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Wr(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 wn(e,t={}){let n=new URLSearchParams;return Bl(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${Hr(n)}`))}async function LS(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Wr(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 NS(e={}){let t=new URLSearchParams;return Bl(t,e),e.sessionId&&t.set("session_id",e.sessionId),Wr(t,e),u(await l.get(`/usage/cost-summary${Hr(t)}`))}function Gl(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)}Wr(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 KS(e,t={}){let n=Gl(e==="projects"?"projects":"sessions",t),r=await ke(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),o=r.headers.get("x-kortix-row-cap"),s=o!=null?Number(o):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(s)?s:null}}async function ff(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function qS(e){return ff("slack",e)}function GS(e){return ff("teams",e)}async function yf(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function BS(e){return yf("slack",e)}function WS(e){return yf("teams",e)}async function Hl(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function Vl(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var HS={oauth_available:!1,install_url:null};async function zl(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?HS:t.data}async function hf(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 Yl(e,t){return hf("slack",e,t)}function Ql(e,t){return hf("teams",e,t)}async function Xl(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Jl(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 Zl(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 eu(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 tu(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 VS={provider:"agentmail",managed_available:!1};async function nu(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?tu(r.data):null}async function ru(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?VS:t.data}async function ou(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return tu(n)}async function su(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 iu(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 tu(r)}async function zS(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function YS(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 au(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function cu(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function lu(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function uu(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function pu(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 du(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function gu(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function mu(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function fu(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function yu(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function hu(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function bu(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function _u(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Pu(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function xu(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Su(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function wu(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function vu(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 QS(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function XS(){throw F("getReferralCode")}async function JS(){throw F("refreshReferralCode")}async function ZS(e){throw F("validateReferralCode")}async function ew(){throw F("getReferralStats")}async function tw(e={}){throw F("listReferrals")}async function nw(e){throw F("sendReferralEmails")}function O(e){return l.get(e,{showErrors:!1})}function v(e){return u(e,"Unexpected empty response")}async function Au(e){return v(await O(`/accounts/${e}/iam/groups`)).groups}async function ku(e,t){return v(await O(`/accounts/${e}/iam/groups/${t}`))}async function Ru(e,t){return v(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Iu(e,t,n){return v(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Cu(e,t){return v(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function Tu(e,t){return v(await O(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Eu(e,t,n){return v(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function rw(e,t){return v(await O(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Mu(e,t,n){return v(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function ow(e,t){return v(await O(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function sw(e,t){let n=v(await O(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function Ne(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 iw(e,t={}){let n=Ne({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return v(await O(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function aw(e,t={}){let n=Ne({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return v(await O(`/accounts/${e}/iam/policies${n}`)).policies}async function cw(e,t){return v(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function lw(e,t,n){return v(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function uw(e,t){return v(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function pw(e,t){return v(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function dw(e,t){return v(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Ou(e){return v(await O(`/accounts/${e}/iam/roles`)).roles}async function Du(e){return v(await O(`/accounts/${e}/iam/agent-identities`)).agents}async function ju(e){return v(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function $u(e,t){return v(await O(`/accounts/${e}/iam/roles/${t}/permissions`))}async function gw(e){return v(await O(`/accounts/${e}/iam/actions`)).actions}async function Uu(e,t){return v(await O(`/accounts/${e}/iam/roles/${t}/usage`))}async function Fu(e,t){return v(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Lu(e,t,n){return v(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Nu(e,t,n){return v(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Ku(e,t){return v(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function mw(e,t,n){return v(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function fw(e){return v(await O(`/accounts/${e}/iam/scim/tokens`)).tokens}async function yw(e,t){return v(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function hw(e,t){return v(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function bw(e){return v(await O(`/accounts/${e}/iam/mfa-required`))}async function _w(e){return v(await O(`/accounts/${e}/iam/mfa-required/preview`))}async function Pw(e,t){return v(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function xw(e){return v(await O(`/accounts/${e}/iam/session-oversight`))}async function Sw(e,t){return v(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function ww(e){return v(await O(`/accounts/${e}/iam/sso/provider`)).provider}async function vw(e,t){return v(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function Aw(e,t){return v(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function kw(e){return v(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function Rw(e){return v(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function Iw(e){return v(await O(`/accounts/${e}/iam/sso/mappings`)).mappings}async function Cw(e,t){return v(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function Tw(e,t){return v(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function Ew(e){return v(await O(`/accounts/${e}/iam/session-policy`))}async function Mw(e,t){return v(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function Ow(e){return v(await O(`/accounts/${e}/iam/sessions`)).sessions}async function Dw(e,t){return v(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function jw(e){return v(await O(`/accounts/${e}/iam/pat-policy`))}async function $w(e,t){return v(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function Uw(e){return v(await O(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function Fw(e,t){return v(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function Lw(e,t){return v(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function Nw(e,t){return v(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function Kw(e){return v(await O(`/accounts/${e}/audit/webhooks`)).webhooks}async function qw(e,t){return v(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function Gw(e,t,n){return v(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Bw(e,t){return v(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Ww(e,t={}){let n=Ne({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return v(await O(`/accounts/${e}/audit${n}`))}async function qu(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),v(await O(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Gu(e,t,n){return n.length===0?[]:v(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function Hw(e){return v(await O(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function Vw(e,t){return v(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function Bu(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function Wu(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function Hu(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function Vu(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function zu(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Yu(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function zw(e){return Ne({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 Qu(e,t){return u(await O(`/accounts/${e}/iam/assignments${zw(t)}`)).assignments}async function Xu(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 Ju(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function Zu(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await O(`/accounts/${e}/iam/permissions${n}`)).permissions}async function Yw(){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 Qw(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function Xw(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function Jw(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function Zw(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function ev(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function tv(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function nv(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function rv(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function ov(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function sv(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function iv(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}function av(){return l.get("/admin/api/boot-modes").then(e=>u(e))}function cv(e){return l.put("/admin/api/boot-modes",e).then(t=>u(t))}var bf="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function lv(e){throw F("getGoogleAuthUrl",bf)}async function uv(e,t){throw F("convertPresentationToGoogleSlides",bf)}async function ep(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind);let r=n.toString();return u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function tp(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function np(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function rp(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function op(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}var sp="call:";function pv(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(sp)&&e.length>sp.length?{type:"connector_call",executionId:e.slice(sp.length)}:{type:"review_item",reviewItemId:e}}function Pf(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function dv(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Pf(n.status)]+=1;return t}function gv(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function ip(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function ap(e){let t=e.indexOf(".");return t<=0?ip(e):`(${ip(e.slice(0,t))}) ${ip(e.slice(t+1))}`}function mv(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Vr=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,he=e=>Array.isArray(e)?e:void 0,_f=e=>typeof e=="number"?e:0,fv=e=>e.split(`
|
|
14
|
-
`).map(t=>t.trim()).filter(Boolean);function yv(e,t){let n=Vr(e.advanced),r=U(e.description),o=he(e.whatChanged)??(r?fv(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:he(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:he(e.conflicts),requestedChanges:he(e.requested_changes)??[],advanced:{headRef:U(n.headRef)??U(e.head_ref)??"",baseRef:U(n.baseRef)??U(e.base_ref)??"",headSha:U(n.headSha)??U(e.head_sha)??U(e.head_commit_sha)??"",baseSha:U(n.baseSha)??U(e.base_sha)??"",additions:_f(n.additions),deletions:_f(n.deletions),files:he(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function hv(e,t){let n=he(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:he(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}=mv(r),i=Vr(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?ap(r):t.title||"Run action",connector: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 bv(e,t){return{artifactKind:U(e.artifactKind)??"document",artifactLabel:U(e.artifactLabel)??"Output",previewUrl:U(e.previewUrl)??U(e.preview_url),preview:U(e.preview),files:he(e.files),note:U(e.note)??t.summary??""}}function _v(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:he(e.options)??[]}}function Pv(e,t){return{note:U(e.note)??t.summary??"",children:he(e.children)??[]}}function xv(e){let t=Vr(e.detail);switch(e.kind){case"change":return yv(t,e);case"approval":return hv(t,e);case"output":return bv(t,e);case"decision":return _v(t,e);case"batch":return Pv(t,e)}}function Sv(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 wv(e,t={}){let n=Vr(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"?Sv(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?ap(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:xv(e)}}async function cp(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function lp(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 up(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 zr=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function xf(e,t=""){return`${Sn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Sf(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 zr(o,t.status)}return r}async function vv(e){return Sf(xf(e))}async function Av(e){return Sf(xf(e,"/messages"))}async function pp(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function dp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Yr(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Qr(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var kv=4;async function wf(e,t){let n=new Array(e.length),r=0,o=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(kv,e.length)},o));let s={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?s.done.push(i):s.failed.push({reminder:i,error:c.error})}),s}function gp(e,t,n){return wf(t,r=>Yr(e,r.sessionId,r.reminderId,n))}function mp(e,t){return wf(t,n=>Qr(e,n.sessionId,n.reminderId))}async function fp(e){return u(await l.get(`/projects/${e}/reminders`))}async function yp(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await l.get(`/accounts/tokens${r}`))}async function hp(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 bp(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function _p(){return u(await l.get("/oauth/grants")).grants}async function Pp(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function Rv(){return u(await l.get("/accounts/me/devices")).devices}async function Iv(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function xp(e){return u(await l.get(`/projects/${e}/cli-token`))}async function Sp(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function wp(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function kt(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,o]of Object.entries(e))n.includes(` ${r} `)&&o!=null&&o!==""&&t.set(r,String(o));return t}function vp(e={}){return{format:e.format,action:e.action,actor:e.actor,actor_type:e.actorType,project_id:e.projectId,session_id:e.sessionId,source:e.source,credential_kind:e.credentialKind,phase:e.phase,outcome:e.outcome,resource_type:e.resourceType,request_id:e.requestId,correlation_id:e.correlationId,since:e.since,until:e.until,q:e.q,cursor:e.cursor,limit:e.limit}}async function Ap(e,t){let n=kt(vp(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function kp(e,t){let n=kt(vp({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function Rp(e,t){let n=kt(vp(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Ip(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Cp(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Tp(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Ep(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Mp(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 Op(e,t){return u(await l.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function Cv(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function Dp(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await l.get(`/marketplace/items${n}`))}async function jp(){return u(await l.get("/marketplace/marketplaces"))}async function $p(){return u(await l.get("/marketplace/marketplaces/featured"))}async function Up(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Fp(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Lp(){return u(await l.get("/marketplace/sources"))}async function Np(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Kp(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function Tv(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function Ev(e){throw F("getTemplate")}async function Mv(e,t){throw F("installTemplate")}async function qp(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Gp(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Xr(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Bp(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Wp(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Hp(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function Vp(e,t){let n=await Xr(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await l.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),o=new TextEncoder().encode(JSON.stringify(r)),s="";for(let i of o)s+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(s)}`}}async function zp(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Yp(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 Qp(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Xp(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Jr(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Zr(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function Ov(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function Dv(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 Jp(e,t,n={}){let r=await Ov(t),o=n.mediaType??"application/gzip",s=await Jr(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),Zr(e,s.artifact.artifact_id,{sha256:await Dv(r),size_bytes:r.byteLength})}async function Zp(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function ed(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function td(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function nd(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 rd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function od(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function sd(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function id(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var ae=(e,t)=>`/projects/${e}/apps/${t}`;async function ad(e,t){return u(await l.get(`${ae(e,t)}/machines`),"Failed to list machines").machines}async function cd(e,t,n,r){return u(await l.post(`${ae(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var ld=(e,t,n)=>cd(e,t,n,"start"),ud=(e,t,n)=>cd(e,t,n,"stop"),pd=(e,t,n)=>cd(e,t,n,"restart");async function dd(e,t,n){return u(await l.delete(`${ae(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function gd(e,t,n){return u(await l.put(`${ae(e,t)}/scale`,{count:n}),"Failed to scale the App")}async function md(e,t,n){return u(await l.post(`${ae(e,t)}/exec`,n),"Failed to run the command")}async function fd(e,t){return u(await l.get(`${ae(e,t)}/volumes`),"Failed to list volumes").volumes}async function yd(e,t,n){return u(await l.post(`${ae(e,t)}/volumes`,n),"Failed to create the volume")}async function hd(e,t,n,r){return u(await l.patch(`${ae(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function bd(e,t,n,r){u(await l.delete(`${ae(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function _d(e,t,n){return u(await l.get(`${ae(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Pd(e,t,n){return u(await l.post(`${ae(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function xd(e,t,n,r){return u(await l.post(`${ae(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function Sd(e,t,n,r){return u(await l.post(`${ae(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function ee(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var re=e=>`/drives/${encodeURIComponent(e)}`;async function jv(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new b("Files not found",{status:404});return t[0]}async function $v(e,t){return u(await l.get(`${re(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function Uv(e,t){return u(await l.put(`${re(e)}/access`,t),"Failed to share folder")}async function Fv(e,t){let n=u(await l.delete(`${re(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function Lv(e){return u(await l.get(`${re(e)}/principals`),"Failed to load people")}async function Nv(e){return u(await l.get(`${re(e)}/conflicts`),"Failed to load conflicts").conflicts}async function Kv(e,t){u(await l.post(`${re(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function qv(e,t="/"){return(await vf(e,t)).entries}async function vf(e,t="/"){return u(await l.get(`${re(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function wd(e,t,n){let r=ee(k().backendUrl),o={path:t};return n?.download&&(o.download="1"),`${r}${re(e)}/files/content?${new URLSearchParams(o)}`}async function Gv(e,t,n){let r=await E(wd(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new b(o?.message||"Could not download file",{status:r.status})}return r.blob()}async function Bv(e,t,n){let r=await E(wd(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new b(o?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function Wv(e,t,n,r){return u(await l.putRaw(`${re(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function Hv(e,t){return u(await l.post(`${re(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function Vv(e,t,n){return u(await l.post(`${re(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function zv(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${re(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function Yv(e){return u(await l.get(`${re(e)}/versions`),"Failed to load versions").versions}async function Qv(e,t){u(await l.post(`${re(e)}/restore`,{versionId:t}),"Failed to restore version")}var Xv=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function Jv(e,t){return(await Af(e,t)).drives}async function Af(e,t){return u(await l.get(Xv(e,t)),"Failed to load session files")}async function vd(e){return u(await l.post("/notifications/device-token",e))}async function Ad(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var Zv=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered"];async function kd(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return u(await l.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function Rd(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await l.post("/notifications/read",t))}var eA={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1}};async function Id(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function Cd(e){return u(await l.put("/notifications/preferences",e))}async function Td(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function Ed(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await l.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function Md(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function vn(e){return u(await l.get(`/projects/${e}/model-access`))}async function An(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function tA(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 Od(e){return typeof e=="string"&&e.trim().length>0}function kf(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Od(t)||Od(n)||Od(r)}function nA(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 kn(e){if(!e)return!0;let t=nA(e.items);return t?!t.some(kf):!kf(e)}function ue(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function rA(e){return ue(e)==="bash"}function oA(e){let t=ue(e);return t==="question"||t==="ask"}function sA(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Rf=new Set(["show","show_user"]);function Dd(e){return Rf.has(ue(e))}function iA(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function jd(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||eo(e))}function eo(e){let t=ue(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:kn(e.state?.input)}var If=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function $d(e){return If.has(ue(e))}var aA=50*1024*1024,Ud="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",cA=new RegExp(`^kortix-attachment://(${Ud})/(${Ud})/(${Ud})$`);function Ld(e){if(typeof e!="string")return null;let t=cA.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function lA(e){return Ld(e)!==null}var Fd=new WeakMap;async function Nd(e,t,n,r={}){if(n.size>aA)throw new Error("Attachments must be 50 MiB or smaller.");let o=`${e}/${t}`,s=r.attachmentId?void 0:Fd.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=Fd.get(n)??new Map;c.set(o,i),Fd.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 Kd(e,t){let n=Ld(e);if(!n)throw new Error("Invalid attachment reference");let r=k().backendUrl.replace(/\/$/,""),o=await E(`${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 uA=new Set(["show","show_user"]);function pA(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 Rt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Rn=e=>typeof e=="string"&&e.length>0?e:null,Cf=e=>typeof e=="string"?Rn(e.split("/").pop()):null;function to(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function dA(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 gA(e,t){for(let n of pA(e))t(to(n,"attachment"),to(n,"filename")??Cf(to(n,"path")),to(n,"mime"))}function mA(e,t){for(let n of[e,...dA(e.items)])Rt(n)&&t(n.attachment,Cf(n.path),null)}function fA(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!Rt(r)||!Rt(r.info)||!Array.isArray(r.parts))continue;let o=Rn(r.info.id);if(!o)continue;let s=Rn(r.info.role)??"unknown",i=(a,c,p)=>{let d=Ld(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)Rt(a)&&(a.type==="file"?i(a.url,Rn(a.filename),Rn(a.mime)):a.type==="text"&&typeof a.text=="string"?gA(a.text,i):a.type==="tool"&&typeof a.tool=="string"&&uA.has(ue(a.tool))&&Rt(a.state)&&Rt(a.state.input)&&mA(a.state.input,i))}return t}function Ke(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function yA(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 hA(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 qd(e,t,n){return e!==void 0?e:yA(Ke(t),n)}var Gd={get disableMobileAdvertising(){return qd(k().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return qd(k().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return qd(k().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var bA=new Set(["project-manager"]);function no(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Gd.enableProjects||!bA.has(e.name)}function _A(e){let t=e.agents.filter(no),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 Tf(){return{projects:{list:ot,listForAccount:Ys,get:on,detail:sn,create:Zs,createRepo:ei,provision:ti,update:ln,archive:un,llmCatalog:an,modelPicker:cn,modelAccess:vn,setModelAccess:An,sandboxHealth:dn,sandboxTemplates:Wa,sessions:it,createSession:at},github:{linkRepository:ai,replaceProjectRepository:ci,getInstallation:li,listInstallations:ui,listLinkableInstallations:pi,listRepositories:di,listRepositoryBranches:gi,linkInstallation:fi,saveInstallation:mi,deleteInstallation:hi,storeUserToken:yi},gitBackend:{get:bi,repositories:_i},connectStatus:Fa,marketplace:{items:s=>Dp(s),item:s=>Up(s),itemFile:(s,i)=>Fp(s,i),marketplaces:()=>jp(),featured:()=>$p(),sources:{list:()=>Lp(),add:s=>Np(s),remove:s=>Kp(s)}}}}function Ef(){return{billing:{accountState:vl,accountStateMinimal:Al,transactions:kl,transactionsSummary:Rl,creditBreakdown:Il,usageHistory:Cl,usageRollup:ql,sessionCosts:{list:Wl,get:wn},tierConfigurations:Tl,checkout:{createSession:n=>El(n),confirmSession:(n,r)=>Ml(n,r)},subscription:{createPortalSession:(n,r)=>Ol(n,r),cancel:(n,r)=>Dl(n,r),reactivate:n=>jl(n),scheduleDowngrade:(n,r,o)=>$l(n,r,o),cancelScheduledChange:n=>Ul(n),prorationPreview:(n,r)=>Fl(n,r)},credits:{purchase:n=>Ll(n),autoTopupSettings:n=>Nl(n),configureAutoTopup:n=>Kl(n)}},sandboxShares:{list:cp,create:lp,revoke:up}}}var Te={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function qe(){let e=Ke("BACKEND_URL")||k().backendUrl;return e||"http://localhost:8008/v1"}function Cn(e){let t=ee(e);return t.endsWith("/v1")?t:`${t}/v1`}function In(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=In(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return In(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function PA(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 Bd(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"daytona",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${qe()}/p/${n.external_id}/${Te.KORTIX_MASTER}`:""),status:PA(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 Wd(){let e=await ot(),t=[];for(let n of e){let r=await it(n.project_id).catch(()=>[]);for(let o of r)t.push({project:n,session:o,runtime:null,sandbox:Bd(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 ct(e){let t=await Wd();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 It=class extends Error{constructor(n,r,o){super(r);this.code=n;this.status=o;this.name="HeadlessAuthError"}code;status};async function X(e,t,n){let r=n?.fetch??k().fetch??((p,d)=>fetch(p,d)),o=ee(n?.backendUrl??k().backendUrl??"");if(!o)throw new It("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(`${Cn(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 It(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 ro(e,t){return X("/auth/signup",{body:e},t)}function oo(e,t){return X("/auth/sign-in/password",{body:e},t)}function so(e,t){return X("/auth/sign-in/magic-link",{body:e},t)}function io(e,t){return X("/auth/verify-otp",{body:e},t)}function ao(e,t){return X("/auth/sign-in/oauth",{body:e},t)}function co(e,t){return X("/auth/oauth/exchange",{body:e},t)}function Ct(e,t){return X("/auth/refresh",{body:e},t)}function lo(e,t){return X("/auth/password/reset",{body:e},t)}function uo(e,t,n){return X("/auth/password/update",{body:e,bearer:t},n)}function po(e,t){return X("/auth/user",{bearer:e},t)}function go(e,t,n){return X("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function mo(e,t){return X("/auth/sign-in/sso",{body:e},t)}var fo={enroll:(e,t,n)=>X("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>X(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>X(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>X(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function yo(e,t={},n){return X("/auth/sign-out",{body:t,bearer:e},n)}function ho(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=S=>(S.expires_at??0)*1e3,g=S=>d(S)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:o})):await e.storage.remove());for(let S of[...p])try{S(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(s)return r;if(!i){let S=c,D=(async()=>{let j=await e.storage.get();if(S===c&&j)try{let L=JSON.parse(j);L.session?.access_token&&L.session?.refresh_token&&(r=L.session,o=L.user??null)}catch{r=null}return s=!0,r})();i=D,D.then(()=>{i===D&&(i=null)},()=>{i===D&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let S=r.refresh_token,D=c,j=Ct({refresh_token:S},e.request).then(async L=>(D!==c||(r=L.session,L.user&&(o=L.user),await m()),r)).catch(async L=>{if(D!==c)return r;let y=L&&typeof L=="object"&&"status"in L?L.status:0;if(y>=400&&y<500)return r=null,o=null,await m(),null;throw L}).finally(()=>{a===j&&(a=null)});a=j}return a}return{subscribe(S){return p.add(S),()=>{p.delete(S)}},current:()=>r,user:()=>o,load:f,async set(S,D){await f(),c+=1,a=null,r=S,D!==void 0&&(o=D),S||(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 Mf(){return{list:Rs,get:Cs,create:Is,secretResources:{list:Xi,create:Ji,rotate:Zi,retry:ea,remove:ta,grant:na,revoke:ra,setAccess:oa},updateName:Ts,branding:{get:Es,update:Ms,uploadAsset:Os,removeAsset:Ds,reset:js},leave:Vs,members:$s,invite:Us,removeMember:Ws,updateMemberRole:Hs,invites:Fs,cancelInvite:Ls,resendInvite:Ns,tokens:{list:yp,create:hp,revoke:bp},connectedApps:{list:_p,revoke:Pp},audit:{log:Ap,export:Rp,webhooks:{list:Ip,create:Cp,update:Tp,remove:Ep}}}}function Of(){return{assignments:{list:Qu,create:Xu,revoke:Ju},permissions:{list:Zu,forRole:$u},roles:{list:Ou,create:Fu,update:Lu,setPermissions:Nu,remove:Ku,usage:Uu},groups:{list:Au,get:ku,create:Ru,update:Iu,remove:Cu,members:{list:Tu,add:Eu,remove:Mu}},agentIdentities:Du,oauthClients:{list:Bu,get:Wu,create:Hu,update:Vu,rotateSecret:zu,remove:Yu},can:qu,canBatch:Gu}}function Df(){let e={signUp:ro,signInWithPassword:oo,sendMagicLink:so,verifyOtp:io,signInWithProvider:ao,exchangeCode:co,refresh:Ct,resetPassword:lo,updatePassword:uo,updateUserMetadata:go,signInWithSso:mo,mfa:fo,user:po,signOut:yo,session:ho},t=Mf(),n=Of();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Ks,describe:qs,accept:Gs,decline:Bs}}}var Tn=new Map,Hd=new Map;function Vd(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function jf(e){return Tn.get(Vd(e))??null}function $f(){return[...Tn.values()].filter(e=>typeof e=="string")}function Uf(e){return Tn.has(Vd(e))}async function Ge(e){let t=Vd(e),n=Tn.get(t);if(n!==void 0)return n;let r=Hd.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 Tn.set(t,i),i}catch{return null}finally{Hd.delete(t)}})();return Hd.set(t,o),o}function Ff(e){let{apiBaseUrl:t}=e;return Uf(t)||Ge(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:jf(t)}}function Lf(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),Ff({sandboxId:r,apiBaseUrl:o,backendPort:s})}}function Nf(e,t){let n=null;async function r(){n||(n=bn(e,t,{showErrors:!1}).then(o=>{let s=ol(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 En=new Map;function Kf(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 lt=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};var Tt={url:null,sandboxId:null,dbSandboxId:null,version:0},SA=new Set;function qf(e,t=null,n=null){if(!(Tt.url===e&&Tt.sandboxId===t&&Tt.dbSandboxId===n)){Tt={url:e,sandboxId:t,dbSandboxId:n,version:Tt.version+1};for(let r of SA)r()}}function Gf(){return Tt.url}function Bf(e,t){async function n(r){let o=Date.now()+r,s=()=>Math.max(0,o-Date.now()),i=await Le(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 Le(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(Kf(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=Fe(c);return qf(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function Wf(e,t,n){let r=null;function o(){if(r)return r;let p=of(e,t);return p&&(r=p),r}let s=Bf(e,t);async function i(p){let d=o();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=Ge(k().backendUrl??n.backendUrl).catch(()=>null),f=`${e}
|
|
15
|
-
${t}`,
|
|
13
|
+
`);let b=JS(f);if(b){if(r(b),b.type==="error")throw new h(b.error,{status:b.status,code:b.code,data:{reason:b.reason}});b.type==="done"&&(p=b.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function ul(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function pl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function dl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function gl(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function ml(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function fl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function ZS(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function yl(e){return u(await l.get(`/projects/${e}/triggers`))}async function hl(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function bl(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function _l(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function Pl(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function xl(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}async function Sl(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await l.get(`/projects/${e}/triggers/event-types?${n}`))}async function wl(e){return u(await l.get(`/projects/${e}/triggers/event-apps`))}var Be=new Map;function Al(e,t){return`${e}::${t}`}function Cf(e,t){Be.delete(e),Be.set(e,t)}function If(e,t){let n=Al(e,t),r=Be.get(n);return r&&Cf(n,r),r}function Tf(e,t,n){let r=Al(e,t);if(!Be.has(r)&&Be.size>=512){let o=Be.keys().next().value;o!==void 0&&Be.delete(o)}Cf(r,n)}function Ef(e,t){Be.delete(Al(e,t))}function ew(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Mn(){return ew(v().backendUrl||"http://localhost:8008/v1")}function Mf(){let e=v().sandboxId;return e?`${Mn()}/p/${e}/8000`:""}function tw(e,t=8e3){return`${Mn()}/p/${e}/${t}`}function Ge(e,t=8e3){return tw(e,t)}function nw(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 Jr=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 rw(e){return e instanceof Error&&e.name==="SessionStartError"}function ow(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 Jr(o,{status:n,code:r,terminal:!0}):null}function Of(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),typeof n=="object"&&n?.keepStopped&&s.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&s.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=s.size>0?`?${s.toString()}`:"";return l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function We(e,t,n){let r=await Of(e,t,n);if(!r.success||!r.data){let o=ow(r.error);if(o&&!(o.status===404&&Dc(t)))throw o;return null}return Df(e,t,r.data)}async function vl(e,t,n){let r=await Of(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return Df(e,t,r.data)}function Df(e,t,n){let r=n.sandbox?.external_id,o=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&o&&Tf(e,t,{runtimeSessionId:o,opencodeSessionId:o,runtimeUrl:Ge(r),sandboxId:r}),n}function sw(e,t){return["session-start",e,t]}async function kl(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function Rl(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function Cl(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 iw(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function jf(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function aw(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Zr(e){let t=e.connectors_required?jf(e.connectors_required):void 0,n=e.connectors_personal?jf(e.connectors_personal):void 0;if(t&&n&&!aw(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 Il(e,t,n){let r=Zr(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function cw(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Tl(n.block):null}}async function lw(e,t,n){let r=Tl(n,!0),o=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...o,block:o.block?Tl(o.block):null}}function Tl(e,t=!1){let n=Zr(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 uw(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function El(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}var $f="Use createPerSeatCheckout().";function Ml(){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 pw(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function dw(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??Ml(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),o=(n.tier?.display_name||"").trim()||r;return{family:pw(r),label:o,sublabel:null,isGrandfathered:!1}}async function Uf(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?Ml():t.data}function Lf(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 Ol(e){return Uf(`/billing/account-state${Lf(e)}`)}async function Dl(e){return Uf(`/billing/account-state/minimal${Lf(e)}`)}async function jl(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 $l(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 Ul(){return u(await l.get("/billing/credit-breakdown"))}async function Ll(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function Fl(){return u(await l.get("/billing/tier-configurations"))}async function gw(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Rt(e,`/v1/billing/account-state${t}`)}async function Nl(e){throw U("createCheckoutSession",$f)}async function Kl(e,t){throw U("confirmCheckoutSession",$f)}async function ql(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Bl(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Gl(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Wl(e,t,n){throw U("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Hl(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function Vl(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 zl(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 Yl(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 mw(e){return u(await l.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Ql(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 fw(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 yw(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 hw(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function bw(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function Xl(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 Zl(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function eo(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function to(e){return e.size>0?`?${e}`:""}async function eu(e={}){let t=new URLSearchParams;return Zl(t,e),e.ownerId&&t.set("owner_id",e.ownerId),eo(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${to(t)}`))}async function On(e,t={}){let n=new URLSearchParams;return Zl(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${to(n)}`))}async function _w(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),eo(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${to(t)}`))}async function Pw(e={}){let t=new URLSearchParams;return Zl(t,e),e.sessionId&&t.set("session_id",e.sessionId),eo(t,e),u(await l.get(`/usage/cost-summary${to(t)}`))}function Jl(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)}eo(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`${v().backendUrl||""}${r}?${n}`}async function xw(e,t={}){let n=Jl(e==="projects"?"projects":"sessions",t),r=await Te(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),o=r.headers.get("x-kortix-row-cap"),s=o!=null?Number(o):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(s)?s:null}}async function Ff(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function Sw(e){return Ff("slack",e)}function ww(e){return Ff("teams",e)}async function Nf(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function Aw(e){return Nf("slack",e)}function vw(e){return Nf("teams",e)}async function tu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function nu(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var kw={oauth_available:!1,install_url:null};async function ru(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?kw:t.data}async function Kf(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 ou(e,t){return Kf("slack",e,t)}function su(e,t){return Kf("teams",e,t)}async function iu(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function au(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 cu(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 lu(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 uu(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 Rw={provider:"agentmail",managed_available:!1};async function pu(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?uu(r.data):null}async function du(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Rw:t.data}async function gu(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return uu(n)}async function mu(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 fu(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 uu(r)}async function Cw(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function Iw(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 yu(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function hu(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function bu(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function _u(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Pu(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 xu(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Su(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function wu(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Au(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function vu(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function ku(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ru(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Cu(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Iu(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Tu(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Eu(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Mu(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Ou(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 Tw(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function Ew(){throw U("getReferralCode")}async function Mw(){throw U("refreshReferralCode")}async function Ow(e){throw U("validateReferralCode")}async function Dw(){throw U("getReferralStats")}async function jw(e={}){throw U("listReferrals")}async function $w(e){throw U("sendReferralEmails")}function O(e){return l.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function Du(e){return A(await O(`/accounts/${e}/iam/groups`)).groups}async function ju(e,t){return A(await O(`/accounts/${e}/iam/groups/${t}`))}async function $u(e,t){return A(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Uu(e,t,n){return A(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Lu(e,t){return A(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function Fu(e,t){return A(await O(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Nu(e,t,n){return A(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function Uw(e,t){return A(await O(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Ku(e,t,n){return A(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function Lw(e,t){return A(await O(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function Fw(e,t){let n=A(await O(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function He(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 Nw(e,t={}){let n=He({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await O(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function Kw(e,t={}){let n=He({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await O(`/accounts/${e}/iam/policies${n}`)).policies}async function qw(e,t){return A(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function Bw(e,t,n){return A(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function Gw(e,t){return A(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function Ww(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function Hw(e,t){return A(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function qu(e){return A(await O(`/accounts/${e}/iam/roles`)).roles}async function Bu(e){return A(await O(`/accounts/${e}/iam/agent-identities`)).agents}async function Gu(e){return A(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function Wu(e,t){return A(await O(`/accounts/${e}/iam/roles/${t}/permissions`))}async function Vw(e){return A(await O(`/accounts/${e}/iam/actions`)).actions}async function Hu(e,t){return A(await O(`/accounts/${e}/iam/roles/${t}/usage`))}async function Vu(e,t){return A(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function zu(e,t,n){return A(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Yu(e,t,n){return A(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Qu(e,t){return A(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function zw(e,t,n){return A(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function Yw(e){return A(await O(`/accounts/${e}/iam/scim/tokens`)).tokens}async function Qw(e,t){return A(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function Xw(e,t){return A(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function Jw(e){return A(await O(`/accounts/${e}/iam/mfa-required`))}async function Zw(e){return A(await O(`/accounts/${e}/iam/mfa-required/preview`))}async function eA(e,t){return A(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function tA(e){return A(await O(`/accounts/${e}/iam/session-oversight`))}async function nA(e,t){return A(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function rA(e){return A(await O(`/accounts/${e}/iam/sso/provider`)).provider}async function oA(e,t){return A(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function sA(e,t){return A(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function iA(e){return A(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function aA(e){return A(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function cA(e){return A(await O(`/accounts/${e}/iam/sso/mappings`)).mappings}async function lA(e,t){return A(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function uA(e,t){return A(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function pA(e){return A(await O(`/accounts/${e}/iam/session-policy`))}async function dA(e,t){return A(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function gA(e){return A(await O(`/accounts/${e}/iam/sessions`)).sessions}async function mA(e,t){return A(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function fA(e){return A(await O(`/accounts/${e}/iam/pat-policy`))}async function yA(e,t){return A(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function hA(e){return A(await O(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function bA(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function _A(e,t){return A(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function PA(e,t){return A(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function xA(e){return A(await O(`/accounts/${e}/audit/webhooks`)).webhooks}async function SA(e,t){return A(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function wA(e,t,n){return A(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function AA(e,t){return A(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function vA(e,t={}){let n=He({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return A(await O(`/accounts/${e}/audit${n}`))}async function Xu(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),A(await O(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Ju(e,t,n){return n.length===0?[]:A(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function kA(e){return A(await O(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function RA(e,t){return A(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function Zu(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function ep(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function tp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function np(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function rp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function op(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function CA(e){return He({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 sp(e,t){return u(await O(`/accounts/${e}/iam/assignments${CA(t)}`)).assignments}async function ip(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 ap(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function cp(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await O(`/accounts/${e}/iam/permissions${n}`)).permissions}async function IA(){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 TA(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function EA(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function MA(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function OA(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function DA(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function jA(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function $A(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function UA(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function LA(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function FA(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function NA(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}function KA(){return l.get("/admin/api/boot-modes").then(e=>u(e))}function qA(e){return l.put("/admin/api/boot-modes",e).then(t=>u(t))}var qf="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function BA(e){throw U("getGoogleAuthUrl",qf)}async function GA(e,t){throw U("convertPresentationToGoogleSlides",qf)}async function lp(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 up(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function pp(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function dp(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function gp(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}var mp="call:";function WA(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(mp)&&e.length>mp.length?{type:"connector_call",executionId:e.slice(mp.length)}:{type:"review_item",reviewItemId:e}}function Gf(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function HA(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Gf(n.status)]+=1;return t}function VA(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 fp(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function yp(e){let t=e.indexOf(".");return t<=0?fp(e):`(${fp(e.slice(0,t))}) ${fp(e.slice(t+1))}`}function zA(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var no=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},$=e=>typeof e=="string"&&e?e:void 0,xe=e=>Array.isArray(e)?e:void 0,Bf=e=>typeof e=="number"?e:0,YA=e=>e.split(`
|
|
14
|
+
`).map(t=>t.trim()).filter(Boolean);function QA(e,t){let n=no(e.advanced),r=$(e.description),o=xe(e.whatChanged)??(r?YA(r):t.summary?[t.summary]:[]);return{crId:$(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:o,impact:$(e.impact)??"",verification:xe(e.verification)??[],previewUrl:$(e.previewUrl)??$(e.preview_url),conflicts:xe(e.conflicts),requestedChanges:xe(e.requested_changes)??[],advanced:{headRef:$(n.headRef)??$(e.head_ref)??"",baseRef:$(n.baseRef)??$(e.base_ref)??"",headSha:$(n.headSha)??$(e.head_sha)??$(e.head_commit_sha)??"",baseSha:$(n.baseSha)??$(e.base_sha)??"",additions:Bf(n.additions),deletions:Bf(n.deletions),files:xe(n.files)??[],mergeMode:$(n.mergeMode)??"merge"}}}function XA(e,t){let n=xe(e.actions);if(n)return{actions:n.map((c,p)=>({id:$(c.id)??`${t.review_item_id}-${p}`,title:$(c.title)??"Action",connector:$(c.connector)??"",action:$(c.action)??"",consequence:$(c.consequence)??"",risk:$(c.risk)??t.risk,icon:$(c.icon)??"generic",argsPreview:xe(c.argsPreview)??[],policySource:$(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=$(e.action_path)??"",{connector:o,action:s}=zA(r),i=no(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:$(e.execution_id)??t.review_item_id,title:r?yp(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:$(e.approval_context),connectorRisk:$(e.risk)??null,policySource:"Requires approval"}]}}function JA(e,t){return{artifactKind:$(e.artifactKind)??"document",artifactLabel:$(e.artifactLabel)??"Output",previewUrl:$(e.previewUrl)??$(e.preview_url),preview:$(e.preview),files:xe(e.files),note:$(e.note)??t.summary??""}}function ZA(e,t){return{question:$(e.question)??t.title??"",context:$(e.context),options:xe(e.options)??[]}}function ev(e,t){return{note:$(e.note)??t.summary??"",children:xe(e.children)??[]}}function tv(e){let t=no(e.detail);switch(e.kind){case"change":return QA(t,e);case"approval":return XA(t,e);case"output":return JA(t,e);case"decision":return ZA(t,e);case"batch":return ev(t,e)}}function nv(e,t){let n=typeof e.number=="number"?e.number:void 0,r=$(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function rv(e,t={}){let n=no(e.detail),r=e.origin_session_id??void 0,o=r?t.sessionLabels?.[r]:void 0,s=e.kind==="approval"?$(n.action_path):void 0,i=e.kind==="change"?nv(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?yp(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:tv(e)}}async function hp(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function bp(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 _p(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 ro=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Wf(e,t=""){return`${Mn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Hf(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 ro(o,t.status)}return r}async function ov(e){return Hf(Wf(e))}async function sv(e){return Hf(Wf(e,"/messages"))}async function Pp(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function xp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function oo(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function so(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var iv=4;async function Vf(e,t){let n=new Array(e.length),r=0,o=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(iv,e.length)},o));let s={done:[],failed:[]};return e.forEach((i,a)=>{let c=n[a];c.ok?s.done.push(i):s.failed.push({reminder:i,error:c.error})}),s}function Sp(e,t,n){return Vf(t,r=>oo(e,r.sessionId,r.reminderId,n))}function wp(e,t){return Vf(t,n=>so(e,n.sessionId,n.reminderId))}async function Ap(e){return u(await l.get(`/projects/${e}/reminders`))}async function vp(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 kp(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 Rp(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function Cp(){return u(await l.get("/oauth/grants")).grants}async function Ip(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function av(){return u(await l.get("/accounts/me/devices")).devices}async function cv(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function Tp(e){return u(await l.get(`/projects/${e}/cli-token`))}async function Ep(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function Mp(e,t){return u(await l.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 Op(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 Dp(e,t){let n=Dt(Op(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function jp(e,t){let n=Dt(Op({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function $p(e,t){let n=Dt(Op(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Up(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function Lp(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function Fp(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Np(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Kp(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 qp(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 lv(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function Bp(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 Gp(){return u(await l.get("/marketplace/marketplaces"))}async function Wp(){return u(await l.get("/marketplace/marketplaces/featured"))}async function Hp(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Vp(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function zp(){return u(await l.get("/marketplace/sources"))}async function Yp(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Qp(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function uv(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function pv(e){throw U("getTemplate")}async function dv(e,t){throw U("installTemplate")}async function Xp(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Jp(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function io(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Zp(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function ed(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function td(e,t){return u(await l.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function nd(e,t){let n=await io(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await l.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),o=new TextEncoder().encode(JSON.stringify(r)),s="";for(let i of o)s+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(s)}`}}async function rd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function od(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 sd(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function id(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function ao(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function co(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function gv(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function mv(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 ad(e,t,n={}){let r=await gv(t),o=n.mediaType??"application/gzip",s=await ao(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),co(e,s.artifact.artifact_id,{sha256:await mv(r),size_bytes:r.byteLength})}async function cd(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function ld(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function ud(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function pd(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 dd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function gd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function md(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function fd(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var pe=(e,t)=>`/projects/${e}/apps/${t}`;async function yd(e,t){return u(await l.get(`${pe(e,t)}/machines`),"Failed to list machines").machines}async function hd(e,t,n,r){return u(await l.post(`${pe(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var bd=(e,t,n)=>hd(e,t,n,"start"),_d=(e,t,n)=>hd(e,t,n,"stop"),Pd=(e,t,n)=>hd(e,t,n,"restart");async function xd(e,t,n){return u(await l.delete(`${pe(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Sd(e,t,n){return u(await l.put(`${pe(e,t)}/scale`,{count:n}),"Failed to scale the App")}async function wd(e,t,n){return u(await l.post(`${pe(e,t)}/exec`,n),"Failed to run the command")}async function Ad(e,t){return u(await l.get(`${pe(e,t)}/volumes`),"Failed to list volumes").volumes}async function vd(e,t,n){return u(await l.post(`${pe(e,t)}/volumes`,n),"Failed to create the volume")}async function kd(e,t,n,r){return u(await l.patch(`${pe(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function Rd(e,t,n,r){u(await l.delete(`${pe(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Cd(e,t,n){return u(await l.get(`${pe(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Id(e,t,n){return u(await l.post(`${pe(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Td(e,t,n,r){return u(await l.post(`${pe(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function Ed(e,t,n,r){return u(await l.post(`${pe(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function oe(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var ae=e=>`/drives/${encodeURIComponent(e)}`;async function fv(e){let t=u(await l.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new h("Files not found",{status:404});return t[0]}async function yv(e,t){return u(await l.get(`${ae(e)}/access?${new URLSearchParams({path:t})}`),"Failed to load sharing")}async function hv(e,t){return u(await l.put(`${ae(e)}/access`,t),"Failed to share folder")}async function bv(e,t){let n=u(await l.delete(`${ae(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function _v(e){return u(await l.get(`${ae(e)}/principals`),"Failed to load people")}async function Pv(e){return u(await l.get(`${ae(e)}/conflicts`),"Failed to load conflicts").conflicts}async function xv(e,t){u(await l.post(`${ae(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function Sv(e,t="/"){return(await zf(e,t)).entries}async function zf(e,t="/"){return u(await l.get(`${ae(e)}/files?${new URLSearchParams({path:t})}`),"Failed to load files")}function Md(e,t,n){let r=oe(v().backendUrl),o={path:t};return n?.download&&(o.download="1"),`${r}${ae(e)}/files/content?${new URLSearchParams(o)}`}async function wv(e,t,n){let r=await E(Md(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new h(o?.message||"Could not download file",{status:r.status})}return r.blob()}async function Av(e,t,n){let r=await E(Md(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new h(o?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function vv(e,t,n,r){return u(await l.putRaw(`${ae(e)}/files/content?${new URLSearchParams({path:t})}`,n,{signal:r?.signal,...r?.ifMatch?{headers:{"If-Match":r.ifMatch}}:{}}),"Failed to upload file")}async function kv(e,t){return u(await l.post(`${ae(e)}/files/mkdir`,{path:t}),"Failed to create folder")}async function Rv(e,t,n){return u(await l.post(`${ae(e)}/files/move`,{from:t,to:n}),"Failed to move")}async function Cv(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await l.delete(`${ae(e)}/files?${new URLSearchParams(r)}`),"Failed to delete")}async function Iv(e){return u(await l.get(`${ae(e)}/versions`),"Failed to load versions").versions}async function Tv(e,t){u(await l.post(`${ae(e)}/restore`,{versionId:t}),"Failed to restore version")}var Ev=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function Mv(e,t){return(await Yf(e,t)).drives}async function Yf(e,t){return u(await l.get(Ev(e,t)),"Failed to load session files")}async function Od(e){return u(await l.post("/notifications/device-token",e))}async function Dd(e,t){return u(await l.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}var Ov=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered"];async function jd(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return u(await l.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function $d(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await l.post("/notifications/read",t))}var Dv={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1}};async function Ud(){return u(await l.get("/notifications/preferences",{showErrors:!1}))}async function Ld(e){return u(await l.put("/notifications/preferences",e))}async function Fd(){return u(await l.get("/notifications/web-push/key",{showErrors:!1}))}async function Nd(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await l.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function Kd(e,t){return u(await l.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function Dn(e){return u(await l.get(`/projects/${e}/model-access`))}async function jn(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function jv(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 qd(e){return typeof e=="string"&&e.trim().length>0}function Qf(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return qd(t)||qd(n)||qd(r)}function $v(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 $n(e){if(!e)return!0;let t=$v(e.items);return t?!t.some(Qf):!Qf(e)}function ce(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function Uv(e){return ce(e)==="bash"}function Lv(e){let t=ce(e);return t==="question"||t==="ask"}function Fv(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Xf=new Set(["show","show_user"]);function Bd(e){return Xf.has(ce(e))}function Nv(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Gd(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||lo(e))}function lo(e){let t=ce(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:$n(e.state?.input)}var Jf=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Wd(e){return Jf.has(ce(e))}var Kv=50*1024*1024,Hd="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",qv=new RegExp(`^kortix-attachment://(${Hd})/(${Hd})/(${Hd})$`);function zd(e){if(typeof e!="string")return null;let t=qv.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function Bv(e){return zd(e)!==null}var Vd=new WeakMap;async function Yd(e,t,n,r={}){if(n.size>Kv)throw new Error("Attachments must be 50 MiB or smaller.");let o=`${e}/${t}`,s=r.attachmentId?void 0:Vd.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=Vd.get(n)??new Map;c.set(o,i),Vd.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 Qd(e,t){let n=zd(e);if(!n)throw new Error("Invalid attachment reference");let r=v().backendUrl.replace(/\/$/,""),o=await E(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!o.ok)throw new h("Could not load attachment",{status:o.status});return o.blob()}var Gv=new Set(["show","show_user"]);function Wv(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 jt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Un=e=>typeof e=="string"&&e.length>0?e:null,Zf=e=>typeof e=="string"?Un(e.split("/").pop()):null;function uo(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function Hv(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 Vv(e,t){for(let n of Wv(e))t(uo(n,"attachment"),uo(n,"filename")??Zf(uo(n,"path")),uo(n,"mime"))}function zv(e,t){for(let n of[e,...Hv(e.items)])jt(n)&&t(n.attachment,Zf(n.path),null)}function Yv(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!jt(r)||!jt(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=zd(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)jt(a)&&(a.type==="file"?i(a.url,Un(a.filename),Un(a.mime)):a.type==="text"&&typeof a.text=="string"?Vv(a.text,i):a.type==="tool"&&typeof a.tool=="string"&&Gv.has(ce(a.tool))&&jt(a.state)&&jt(a.state.input)&&zv(a.state.input,i))}return t}function Ve(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function Qv(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 Xv(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 Xd(e,t,n){return e!==void 0?e:Qv(Ve(t),n)}var Jd={get disableMobileAdvertising(){return Xd(v().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Xd(v().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Xd(v().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var Jv=new Set(["project-manager"]);function po(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Jd.enableProjects||!Jv.has(e.name)}function Zv(e){let t=e.agents.filter(po),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 ey(){return{projects:{list:ut,listForAccount:oi,get:gn,detail:mn,create:ci,createRepo:li,provision:ui,update:hn,archive:bn,llmCatalog:fn,modelPicker:yn,modelAccess:Dn,setModelAccess:jn,sandboxHealth:Pn,sandboxTemplates:ec,sessions:gt,createSession:mt},github:{linkRepository:yi,replaceProjectRepository:hi,getInstallation:bi,listInstallations:_i,listLinkableInstallations:Pi,listRepositories:xi,listRepositoryBranches:Si,linkInstallation:Ai,saveInstallation:wi,deleteInstallation:ki,storeUserToken:vi},gitBackend:{get:Ri,repositories:Ci},connectStatus:Va,marketplace:{items:s=>Bp(s),item:s=>Hp(s),itemFile:(s,i)=>Vp(s,i),marketplaces:()=>Gp(),featured:()=>Wp(),sources:{list:()=>zp(),add:s=>Yp(s),remove:s=>Qp(s)}}}}function ty(){return{billing:{accountState:Ol,accountStateMinimal:Dl,transactions:jl,transactionsSummary:$l,creditBreakdown:Ul,usageHistory:Ll,usageRollup:Xl,sessionCosts:{list:eu,get:On},tierConfigurations:Fl,checkout:{createSession:n=>Nl(n),confirmSession:(n,r)=>Kl(n,r)},subscription:{createPortalSession:(n,r)=>ql(n,r),cancel:(n,r)=>Bl(n,r),reactivate:n=>Gl(n),scheduleDowngrade:(n,r,o)=>Wl(n,r,o),cancelScheduledChange:n=>Hl(n),prorationPreview:(n,r)=>Vl(n,r)},credits:{purchase:n=>zl(n),autoTopupSettings:n=>Yl(n),configureAutoTopup:n=>Ql(n)}},sandboxShares:{list:hp,create:bp,revoke:_p}}}var $e={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function ze(){let e=Ve("BACKEND_URL")||v().backendUrl;return e||"http://localhost:8008/v1"}function ft(e){let t=oe(e);return t.endsWith("/v1")?t:`${t}/v1`}function Ln(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=Ln(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return Ln(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function ek(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 Zd(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?`${ze()}/p/${n.external_id}/${$e.KORTIX_MASTER}`:""),status:ek(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 eg(){let e=await ut(),t=[];for(let n of e){let r=await gt(n.project_id).catch(()=>[]);for(let o of r)t.push({project:n,session:o,runtime:null,sandbox:Zd(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 yt(e){let t=await eg();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 $t=class extends Error{constructor(n,r,o){super(r);this.code=n;this.status=o;this.name="HeadlessAuthError"}code;status};async function te(e,t,n){let r=n?.fetch??v().fetch??((p,d)=>fetch(p,d)),o=oe(n?.backendUrl??v().backendUrl??"");if(!o)throw new $t("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(`${ft(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 $t(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 go(e,t){return te("/auth/signup",{body:e},t)}function mo(e,t){return te("/auth/sign-in/password",{body:e},t)}function fo(e,t){return te("/auth/sign-in/magic-link",{body:e},t)}function yo(e,t){return te("/auth/verify-otp",{body:e},t)}function ho(e,t){return te("/auth/sign-in/oauth",{body:e},t)}function bo(e,t){return te("/auth/oauth/exchange",{body:e},t)}function Ut(e,t){return te("/auth/refresh",{body:e},t)}function _o(e,t){return te("/auth/password/reset",{body:e},t)}function Po(e,t,n){return te("/auth/password/update",{body:e,bearer:t},n)}function xo(e,t){return te("/auth/user",{bearer:e},t)}function So(e,t,n){return te("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function wo(e,t){return te("/auth/sign-in/sso",{body:e},t)}var Ao={enroll:(e,t,n)=>te("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>te(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>te(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>te(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function vo(e,t={},n){return te("/auth/sign-out",{body:t,bearer:e},n)}function ko(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=P=>(P.expires_at??0)*1e3,g=P=>d(P)-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 P of[...p])try{P(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(s)return r;if(!i){let P=c,j=(async()=>{let L=await e.storage.get();if(P===c&&L)try{let N=JSON.parse(L);N.session?.access_token&&N.session?.refresh_token&&(r=N.session,o=N.user??null)}catch{r=null}return s=!0,r})();i=j,j.then(()=>{i===j&&(i=null)},()=>{i===j&&(i=null)})}return i}async function b(){if(await f(),!r)return null;if(!a){let P=r.refresh_token,j=c,L=Ut({refresh_token:P},e.request).then(async N=>(j!==c||(r=N.session,N.user&&(o=N.user),await m()),r)).catch(async N=>{if(j!==c)return r;let y=N&&typeof N=="object"&&"status"in N?N.status:0;if(y>=400&&y<500)return r=null,o=null,await m(),null;throw N}).finally(()=>{a===L&&(a=null)});a=L}return a}return{subscribe(P){return p.add(P),()=>{p.delete(P)}},current:()=>r,user:()=>o,load:f,async set(P,j){await f(),c+=1,a=null,r=P,j!==void 0&&(o=j),P||(o=null),await m()},async getToken(){return await f(),r?g(r)?(await b().catch(()=>r))?.access_token??null:r.access_token:null},refresh:b,async clear(){c+=1,a=null,r=null,o=null,s=!0,await m()}}}function ny(){return{list:$s,get:Ls,create:Us,secretResources:{list:ia,create:aa,rotate:ca,retry:la,remove:ua,grant:pa,revoke:da,setAccess:ga},updateName:Fs,branding:{get:Ns,update:Ks,uploadAsset:qs,removeAsset:Bs,reset:Gs},leave:ni,members:Ws,invite:Hs,removeMember:ei,updateMemberRole:ti,invites:Vs,cancelInvite:zs,resendInvite:Ys,tokens:{list:vp,create:kp,revoke:Rp},connectedApps:{list:Cp,revoke:Ip},audit:{log:Dp,export:$p,webhooks:{list:Up,create:Lp,update:Fp,remove:Np}}}}function ry(){return{assignments:{list:sp,create:ip,revoke:ap},permissions:{list:cp,forRole:Wu},roles:{list:qu,create:Vu,update:zu,setPermissions:Yu,remove:Qu,usage:Hu},groups:{list:Du,get:ju,create:$u,update:Uu,remove:Lu,members:{list:Fu,add:Nu,remove:Ku}},agentIdentities:Bu,oauthClients:{list:Zu,get:ep,create:tp,update:np,rotateSecret:rp,remove:op},can:Xu,canBatch:Ju}}function oy(){let e={signUp:go,signInWithPassword:mo,sendMagicLink:fo,verifyOtp:yo,signInWithProvider:ho,exchangeCode:bo,refresh:Ut,resetPassword:_o,updatePassword:Po,updateUserMetadata:So,signInWithSso:wo,mfa:Ao,user:xo,signOut:vo,session:ko},t=ny(),n=ry();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Qs,describe:Xs,accept:Js,decline:Zs}}}var Fn=new Map,tg=new Map;function ng(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function sy(e){return Fn.get(ng(e))??null}function iy(){return[...Fn.values()].filter(e=>typeof e=="string")}function ay(e){return Fn.has(ng(e))}async function Ye(e){let t=ng(e),n=Fn.get(t);if(n!==void 0)return n;let r=tg.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 Fn.set(t,i),i}catch{return null}finally{tg.delete(t)}})();return tg.set(t,o),o}function cy(e){let{apiBaseUrl:t}=e;return ay(t)||Ye(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:sy(t)}}function ly(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new h(`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=v().backendUrl??e.backendUrl,s=80,i=t(o);return i&&(s=i.port?Number(i.port):i.protocol==="https:"?443:80),cy({sandboxId:r,apiBaseUrl:o,backendPort:s})}}function uy(e,t){let n=null;async function r(){n||(n=Cn(e,t,{showErrors:!1}).then(o=>{let s=gl(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 Nn=new Map;function py(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let 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 ht=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 Lt={url:null,sandboxId:null,dbSandboxId:null,version:0},nk=new Set;function dy(e,t=null,n=null){if(!(Lt.url===e&&Lt.sandboxId===t&&Lt.dbSandboxId===n)){Lt={url:e,sandboxId:t,dbSandboxId:n,version:Lt.version+1};for(let r of nk)r()}}function gy(){return Lt.url}function my(e,t){async function n(r){let o=Date.now()+r,s=()=>Math.max(0,o-Date.now()),i=await We(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 We(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 h(py(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new h("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ge(c);return dy(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function fy(e,t,n){let r=null;function o(){if(r)return r;let p=If(e,t);return p&&(r=p),r}let s=my(e,t);async function i(p){let d=o();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=Ye(v().backendUrl??n.backendUrl).catch(()=>null),f=`${e}
|
|
15
|
+
${t}`,b=Nn.get(f);if(b)return r=await b,await m,r;let P=s(g);Nn.set(f,P);try{return r=await P,await m,r}finally{Nn.get(f)===P&&Nn.delete(f)}}function a(p){let d=o();if(!d)throw new ht(p);return d}function c(){r=null,Ef(e,t)}return{ensureReady:i,tryResolveReady:o,requireReady:a,forgetReady:c}}var B=["directory","workspace"],yy=["messageID","model","agent","noReply","tools","format","system","variant","parts"],k=(e,t,n=B,r=[],o)=>({method:e,path:t,query:n,body:r,bodyParam:o}),rk={"session.list":k("GET","/session",[...B,"scope","path","roots","start","search","limit"]),"session.get":k("GET","/session/{sessionID}"),"session.create":k("POST","/session",B,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":k("DELETE","/session/{sessionID}"),"session.update":k("PATCH","/session/{sessionID}",B,["title","metadata","permission","time"]),"session.status":k("GET","/session/status"),"session.messages":k("GET","/session/{sessionID}/message",[...B,"limit","before"]),"session.prompt":k("POST","/session/{sessionID}/message",B,yy),"session.promptAsync":k("POST","/session/{sessionID}/prompt_async",B,yy),"session.abort":k("POST","/session/{sessionID}/abort"),"session.revert":k("POST","/session/{sessionID}/revert",B,["messageID","partID"]),"session.unrevert":k("POST","/session/{sessionID}/unrevert"),"session.summarize":k("POST","/session/{sessionID}/summarize",B,["providerID","modelID","auto"]),"session.command":k("POST","/session/{sessionID}/command",B,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":k("POST","/session/{sessionID}/share"),"session.unshare":k("DELETE","/session/{sessionID}/share"),"session.fork":k("POST","/session/{sessionID}/fork",B,["messageID"]),"session.diff":k("GET","/session/{sessionID}/diff",[...B,"messageID"]),"session.todo":k("GET","/session/{sessionID}/todo"),"permission.list":k("GET","/permission"),"permission.reply":k("POST","/permission/{requestID}/reply",B,["reply","message"]),"question.list":k("GET","/question"),"question.reply":k("POST","/question/{requestID}/reply",B,["answers"]),"question.reject":k("POST","/question/{requestID}/reject"),"part.update":k("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",B,[],"part"),"part.delete":k("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":k("GET","/file",[...B,"path"]),"file.read":k("GET","/file/content",[...B,"path"]),"find.files":k("GET","/find/file",[...B,"query","dirs","type","limit"]),"vcs.diff":k("GET","/vcs/diff",[...B,"mode","context"]),"global.health":k("GET","/global/health",[]),"global.dispose":k("POST","/global/dispose",[]),"global.config.get":k("GET","/global/config",[]),"global.config.update":k("PATCH","/global/config",[],[],"config"),"provider.list":k("GET","/provider"),"provider.auth":k("GET","/provider/auth"),"provider.oauth.authorize":k("POST","/provider/{providerID}/oauth/authorize",B,["method","inputs"]),"provider.oauth.callback":k("POST","/provider/{providerID}/oauth/callback",B,["method","code"]),"auth.set":k("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":k("GET","/agent"),"app.skills":k("GET","/skill"),"app.log":k("POST","/log",B,["service","level","message","extra"]),"command.list":k("GET","/command"),"tool.ids":k("GET","/experimental/tool/ids"),"tool.list":k("GET","/experimental/tool",[...B,"provider","model"]),"mcp.status":k("GET","/mcp"),"mcp.add":k("POST","/mcp",B,["name","config"]),"mcp.connect":k("POST","/mcp/{name}/connect"),"mcp.disconnect":k("POST","/mcp/{name}/disconnect"),"mcp.auth.start":k("POST","/mcp/{name}/auth"),"mcp.auth.callback":k("POST","/mcp/{name}/auth/callback",B,["code"]),"mcp.auth.remove":k("DELETE","/mcp/{name}/auth"),"project.list":k("GET","/project"),"project.current":k("GET","/project/current"),"path.get":k("GET","/path")};function ok(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 sk(e,t,n={},r={}){let o=rk[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}${ok(o,n)}`,{method:o.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function ik(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 ak(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=ik(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 rg(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
|
-
`);a=d.pop()??"";for(let g of d){let m={},f=[];for(let
|
|
20
|
-
`))if(
|
|
21
|
-
`)),yield m}}}finally{r.removeEventListener("abort",i),s.releaseLock()}}}async function*IA(e,t,n){let r=e.eventTransport??zd(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 Mn(e){let t=o=>(s,i)=>RA(e,AA(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:IA(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 Vf=200;async function CA(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 ut(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 zf(e){let t=e.runtimeUrl.replace(/\/$/,""),n=Mn({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=S=>e.fetch(new Request(`${t}${S}${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 CA(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,Vf),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,Vf),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=>ut(i,"Reading the session status failed")),n.permission.list().then(i=>ut(i,"Reading permission requests failed")),n.question.list().then(i=>ut(i,"Reading questions failed"))]);return{statuses:r??{},permissions:o??[],questions:s??[]}},answerPermission:async(r,o,s)=>{ut(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){ut(await n.question.reject({requestID:r}),"Dismissing the question failed");return}ut(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 ut(await n.session.summarize({sessionID:e.rootId,providerID:o.providerID,modelID:o.modelID}),"Compacting the session failed"),o}}}function Yf(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return zf({runtimeUrl:r,rootId:n,fetch:E})}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 Qf(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await rl(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Et=BigInt(4096),Ee=BigInt(0xffffffffffff),Xf=Ee+BigInt(1),TA=Xf/BigInt(2),Be=BigInt(3600*1e3)*Et,bo=120*1e3,Jf=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,EA=/^msg_([0-9a-f]{12})/,Zf="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function pt(e){let t=EA.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function Mt(e){return BigInt(Math.trunc(e))*Et&Ee}function dt(e,t){let n=e-t&Ee;return n>=TA&&(n-=Xf),n}function Yd(e){let t=null;for(let n of e)n!=null&&(t===null||dt(n,t)>BigInt(0))&&(t=n);return t}function ey(e,t){let n=pt(e);return n===null?!1:dt(n,Mt(t))>Be}function ty(e,t){let n=t===void 0?null:Mt(t);return ny(e,r=>n===null||dt(r,n)<=Be)}function ny(e,t){let n=[];for(let r of e){let o=pt(r);o!==null&&t(o)&&n.push(o)}return Yd(n)}function MA(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Zf[n%62])}return e}function Qd(e){let t=e.random,n=Mt(e.nowMs-(e.backdateMs??bo)),r=e.newestKnownTime??null;if(r!==null){let s=dt(r,n);s>=BigInt(0)&&s<=Be&&(n=r+BigInt(1)&Ee)}let o="";if(t)for(let s=0;s<14;s++)o+=Zf[Math.min(61,Math.floor(t()*62))];else o=MA();return{id:`msg_${n.toString(16).padStart(12,"0")}${o}`,time:n}}function _o(e={}){let t=e.nowMs??Date.now(),n=Mt(t-bo),r=ny(e.after??[],o=>{let s=dt(o,n);return s>=BigInt(0)&&s<=Be});return Qd({nowMs:t,newestKnownTime:r}).id}function ry(e){return{scope:()=>tl(e.projectId,e.sessionId),providerSecretPool:{list:()=>ia(e.projectId,e.sessionId),get:t=>sa(e.projectId,e.sessionId,t),set:(t,n)=>aa(e.projectId,e.sessionId,t,n)},rescope:t=>nl(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=_o(),p=await _n(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 OA="kortix.transcript.v1",oy=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function DA(e){return typeof e=="string"&&oy.includes(e)}var jA=["once","always","reject"],$A=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var sy=async function*(e){let t=k().eventStreamTransport;if(!t){yield*zd(((o,s)=>E(o,s,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await Sr(e.url,e.headers);try{yield*t({...e,headers:n})}catch(o){throw o?.status===401&&r(),o}};function Me(){let e=Gf();return e||(k().billingEnabled??!1?"":cf())}async function Xd(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Jd(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function Zd(e){let t=Jd(e),n=await E(`${t}/env`);if(!n.ok)throw new Error(await Xd(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function eg(e,t,n){let r=Jd(e),o=await E(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!o.ok)throw new Error(await Xd(o,"Failed to save secret"))}async function tg(e,t){let n=Jd(e),r=await E(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Xd(r,"Failed to delete secret"))}var iy={list:Zd,set:eg,delete:tg};async function ay(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let o=await E(`${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 Po(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function On(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return ee(e)}async function rg(e){let t=On(e),n=await E(`${t}/kortix/pty`);if(!n.ok)throw new Error(await Po(n,"Failed to list terminals"));return n.json()}async function og(e,t){let n=On(e),r=await E(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await Po(r,"Failed to create terminal"));return r.json()}async function sg(e,t,n){let r=On(e),o=await E(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(await Po(o,"Failed to update terminal"));return o.json()}async function ig(e,t){let n=On(e),r=await E(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Po(r,"Failed to remove terminal"))}async function ag(e,t,n){let r=On(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:"),ee(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await St();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${s}${s.includes("?")?"&":"?"}${c}`:s}function cy(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 We="\x1B",ly="\x07",UA="\0",ng=`(?:${ly}|${We}\\\\)`,FA=[new RegExp(`${We}\\]697;[^${ly}${We}]*${ng}`,"g"),new RegExp(`${UA}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${We}\\][0-9]+;rgb:[0-9a-fA-F/]+${ng}`,"g"),new RegExp(`${We}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${ng}`,"g"),new RegExp(`${We}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${We}\\[\\d+;\\d+R`,"g"),new RegExp(`${We}\\[\\?[0-9;]*c`,"g")];function uy(e){let t=e;for(let n of FA)t=t.replace(n,"");return t}var py={list:rg,create:og,update:sg,remove:ig,webSocketUrl:ag};async function I(e,t,n,r){let o=e;for(;o.endsWith("/");)o=o.slice(0,-1);let s=await E(`${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 LA(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 NA(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function KA(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function qA(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function GA(e,t){return I(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function BA(e,t,n){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function WA(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function HA(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function VA(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function zA(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return I(e,`/kortix/tickets${n}`)}async function YA(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function QA(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function XA(e,t){return I(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function JA(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function ZA(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function ek(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function tk(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function nk(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function rk(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function ok(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function sk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function ik(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function ak(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function ck(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function lk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function uk(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function pk(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function dk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function gk(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function mk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function fk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function yk(e,t,n=200){return I(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function hk(e){return I(e,"/kortix/projects")}async function bk(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function _k(e,t){return I(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function Pk(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function xk(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Sk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function wk(e,t,n="all"){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function vk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function Ak(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function kk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function Rk(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function Ik(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function Ck(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function Tk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Ek(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function Mk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function Ok(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function Dk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function jk(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var $k=1e4,Uk={retryOnAuthError:!1};function Ot(e,t,n){return I(e,t,{signal:AbortSignal.timeout($k),...n},Uk)}async function Fk(e,t=!1){return(await Ot(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function Lk(e){return(await Ot(e,"/kortix/services/templates")).templates??[]}async function Nk(e,t){return(await Ot(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function Kk(e,t,n){let r=n==="delete",o=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return Ot(e,o,{method:r?"DELETE":"POST"})}async function qk(e,t){return Ot(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function Gk(e,t){return Ot(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Oe=new Map,Bk=256,Dt=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function He(){let e=Me();if(!e)throw new Dt;return be(e)}function be(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Oe.get(e);if(t)return Oe.delete(e),Oe.set(e,t),t;if(!mr())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=Mn({baseUrl:e,fetch:E,eventTransport:sy});return Oe.set(e,n),Oe.size>Bk&&Oe.delete(Oe.keys().next().value),n}function Wk(e){Oe.delete(e)}function Hk(){Oe.clear()}var xo=new Map;function Vk(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=xo.get(e);if(t)return t;let n=Mn({baseUrl:e,fetch});return xo.set(e,n),n}function zk(e){xo.delete(e)}function Yk(){xo.clear()}async function Qk(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 Xk(e){let t=Me();if(!t)throw new b("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await E(`${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 Qk(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 dy="frontend";function So(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${dy}] ${t}`,...n?[n]:[]);try{He().app.log({service:dy,level:e,message:t,extra:n})}catch{}}var Ve={debug:(e,t)=>So("debug",e,t),info:(e,t)=>So("info",e,t),warn:(e,t)=>So("warn",e,t),error:(e,t)=>So("error",e,t)};function gy(e){return{type:"heartbeat-gap",gapMs:e}}function my(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 Jk={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},Zk=16,eR=8,tR=6e4,nR=5e3,rR=250,oR=1e3,sR=3e4,iR=5,aR=1e4,cR=4,lR=.5,uR=3e3,pR=3e4,dR=2e4,gR=2e3,mR=8;function fR(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function yR(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 fy(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 Dn=new WeakMap;function hR(e,t,n){let r=t.timers??Jk,o=t.connectTimeoutMs??dR,s=t.heartbeatTimeoutMs??tR,i=t.maxConsecutiveHardFailures??mR,a=new AbortController;function c(_,...x){for(let M of n){let w=_(M);if(w)try{w(...x)}catch(P){console.warn("[opencode-events] subscriber handler threw, skipping",P)}}}let p=null,d=!1,g=_=>{p!==_&&(p=_,_&&c(x=>x.onConnectionChange,_))},m=r.now(),f=null,h=[],S,D=0,j=new Map,L=()=>{if(S&&r.clearTimeout(S),S=void 0,h.length===0)return;let _=h;h=[],j.clear(),D=r.now(),m=r.now();for(let x of _)x&&c(M=>M.onEvent,x.event)},y=()=>{if(S)return;let _=r.now()-D;S=r.setTimeout(L,Math.max(0,Zk-_))};return(async()=>{let _=0,x=0,M=0;for(;!a.signal.aborted;){let w=!1,P=!1,A,C,T=null,N=r.now(),$=new AbortController;g("connecting");let K=fy(a.signal);K.promise.then(()=>$.abort());try{let ie=await new Promise((ht,et)=>{let ne=!1;C=r.setTimeout(()=>{ne||(ne=!0,Ve.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:o}),$.abort(),et(new Error(`SSE connect timed out after ${o}ms`)))},o),e.global.event({signal:$.signal,sseDefaultRetryDelay:uR,sseMaxRetryDelay:pR,sseMaxRetryAttempts:1}).then(ve=>{ne||(ne=!0,r.clearTimeout(C),ht(ve))},ve=>{ne||(ne=!0,r.clearTimeout(C),et(ve))})}),{stream:en}=ie;if(f){let ht=r.now()-f.lastActivityAt,et=f.eventful;f=null,(et||ht>nR)&&c(ne=>ne.onGapRehydrate,ht)}m=r.now();let Ze=()=>{r.clearTimeout(A),A=r.setTimeout(()=>{Ve.warn("SSE heartbeat timeout, forcing reconnect"),$.abort()},s)};Ze();let pr=r.now(),cP=en[Symbol.asyncIterator]();for(;!$.signal.aborted;){let ht=cP.next().then(Ae=>({kind:"next",result:Ae}),Ae=>({kind:"error",error:Ae})),et=fy($.signal),ne=await Promise.race([ht,et.promise.then(()=>({kind:"aborted"}))]);if(et.cleanup(),ne.kind==="aborted")break;if(ne.kind==="error")throw ne.error;if(ne.result.done)break;g("open"),Ze();let ve=ne.result.value,bt=ve&&typeof ve=="object"&&"payload"in ve?ve.payload:ve;if(!bt?.type)continue;bt.type!=="server.connected"&&(w=!0);let rs=yR(h[h.length-1]?.event,bt);if(rs)h[h.length-1]={type:rs.type,event:rs};else{let Ae=fR(bt);if(Ae){let vm=j.get(Ae);vm!==void 0&&(h[vm]=void 0),j.set(Ae,h.length)}h.push({type:bt.type,event:bt})}y(),!(r.now()-pr<eR)&&(pr=r.now(),await new Promise(Ae=>r.setTimeout(Ae,0)))}P=w}catch(ie){if(a.signal.aborted)break;T=ie;let en=String(ie),Ze=_t(ie)||_t(ie?.cause);if(Ve.error("SSE event stream error",{error:en,retryCount:_,isAuthError:Ze}),Ze)try{Ir(),await Rr(),Ve.info("SSE: refreshed auth token after auth error")}catch(pr){Ve.error("SSE: failed to refresh auth token",{error:String(pr)})}}finally{r.clearTimeout(A),r.clearTimeout(C),$.abort(),K.cleanup(),L()}if(a.signal.aborted)break;let q=r.now()-N,de=T?.cause?.status;if(x=!w&&(typeof de=="number"&&de>=400||q<gR)?x+1:0,x>=i){Ve.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:x,lastError:String(T)}),p=null,d=!0,c(ie=>ie.onParked,{consecutiveFailures:x,lastError:T});break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||w},M=P&&q<aR?M+1:0;let yt=P&&M<=cR;yt?_=0:(_++,_>1&&Ve.warn("SSE event stream reconnecting",{retryCount:_}));let Se=yt?rR:Math.min(oR*2**Math.min(_-1,iR),sR),we=Math.round(Se*(1+lR*(r.random?.()??0)));await new Promise(ie=>{let en=r.setTimeout(ie,we),Ze=()=>{r.clearTimeout(en),ie()};a.signal.addEventListener("abort",Ze,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),S&&r.clearTimeout(S)}}}function wo(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o,signal:s}=e,i=e.client??(e.url?be(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o},c=Dn.get(i);if(c?.isParked()&&(Dn.delete(i),c=void 0),!c)c=hR(i,e,new Set([a])),Dn.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(),Dn.get(i)===p&&Dn.delete(i)))},m=()=>g();return s&&(s.aborted?g():s.addEventListener("abort",m,{once:!0})),{close:g}}function yy(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return be(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return be(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return be(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return wo({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Py(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new b(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Ut(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function Y(e){let t=(e??Me()).trim();if(!t)throw new Dt;return t}async function Ao(e,t){let n=await E(`${Y(t)}${e}`);if(!n.ok)throw new b(await Ut(n),{status:n.status,response:n});return n.json()}var ko=["/workspace","/tmp","/home","/opt"],bR=ko.filter(e=>e!=="/workspace");function ug(e){return ko.some(t=>e===t||e.startsWith(`${t}/`))}function Ft(e){return ug(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(bR.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var pg=ze;async function Lt(e,t){let n=Y(t),r=ze(e)||".";return(await Ao(`/file?path=${encodeURIComponent(r)}`,n)).map(s=>({...s,path:s.absolute||`/workspace/${s.path}`}))}async function Nt(e,t){let n=Y(t),r=ze(e),o=await E(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!o.ok)throw new b(await Ut(o),{status:o.status,response:o});return o.json()}async function _R(e,t,n){let r=Y(n),o=ze(e),s=await E(`${r}/file/raw?path=${encodeURIComponent(o)}`);if(!s.ok)throw new b(await Ut(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}var PR=8,vo=0,xy=[];async function xR(){if(vo<PR){vo++;return}await new Promise(e=>xy.push(e)),vo++}function SR(){vo--,xy.shift()?.()}function Sy(e,t){let n=Y(t);return gn(`${n}/file/raw?path=${encodeURIComponent(ze(e))}`)}async function Kt(e,t){await xR();try{let n=Y(t);try{return await _R(e,void 0,n)}catch{}let r=await Nt(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"})}finally{SR()}}async function Un(e){return Ao("/file/status",Y(e))}async function Fn(e,t,n){let r=Y(n),o=new URLSearchParams({query:e});return t?.type&&o.set("type",t.type),t?.limit&&o.set("limit",String(t.limit)),Ao(`/find/file?${o.toString()}`,r)}async function Ln(e,t){let n=Y(t);return(await Ao(`/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 jn=[400,1200],wR=e=>e===408||e===429||e===502||e===503||e===504,hy=e=>new Promise(t=>setTimeout(t,e));function vR(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var cg=3e4,wy=15*6e4,AR=256;function jt(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return cg;let t=cg+e/AR;return Math.min(wy,Math.max(cg,Math.round(t)))}async function kR(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 $n(e,t){let n;for(let o=0;o<=jn.length;o++){let s;try{s=await t(e())}catch(a){if(n=a,vR(a)||o===jn.length)break;await hy(jn[o]);continue}if(s.ok)return s.json();let i=await kR(s);if(n=new b(`Upload failed (${s.status}): ${i}`,{status:s.status,response:s}),!wR(s.status)||o===jn.length)throw n;await hy(jn[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 lg=8*1024*1024;function RR(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 by(e,t){try{e?.onProgress?.(t)}catch{}}function _y(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 IR(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function qt(e,t,n,r,o){let s=typeof r=="string"?r:void 0,i=typeof r=="string"?o:r,a=Y(s),c=jt(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=lg){let f=await $n(()=>_y(e,t,p),h=>E(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return RR(f[0],e.size),by(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await $n(()=>_y(new Blob([],{type:e.type}),t,p),f=>E(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:jt(0)})))[0]?.path;if(!g)throw new b("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=IR(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+=lg){let h=Math.min(e.size,f+lg),S=e.slice(f,h,e.type),D=await $n(()=>{let j=new FormData;return m.parent&&j.append("path",m.parent),j.append("filename",m.name),j.append("first",f===0?"true":"false"),j.append("offset",String(f)),j.append("file",S,m.name),j},j=>E(`${a}/file/append`,{method:"POST",body:j},{timeoutMs:jt(S.size)}));if(D.path!==g||D.size!==h)throw new b(`Upload verification failed for ${g}: expected ${h} bytes, received ${D.size}`,{code:"UPLOAD_SIZE_MISMATCH"});by(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await gt(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function vy(e,t,n){let r=Y(n);return $n(()=>{let o=new FormData;return t&&o.append("path",t),o.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),o},o=>E(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:CR}))}var CR=wy;function TR(e,t,n){let r=Y(n),o=jt(t.size);return $n(()=>{let s=new FormData;return s.append(e,t,e.split("/").pop()||"file"),s},s=>E(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:o}))}var $t=class extends b{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function Nn(e,t){let n=Y(t),r=e.trim(),s=(r.startsWith("/")?r:`/${r}`).split("/"),i=s.pop()||"untitled",a=s.join("/")||"/workspace",c=Ft(`${a}/${i}`),p=[];try{p=await Lt(Ay(c),n)}catch(g){if(!(g instanceof b&&g.status===404))throw g}if(p.some(g=>g.name===ky(c)))throw new $t(c);let d=await Ry(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function Kn(e,t,n){let r=Y(n);return TR(t,await Kt(e,r),r)}function ER(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Ay(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function ky(e){return e.slice(e.lastIndexOf("/")+1)}function MR(){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 qn(e,t,n){let r=Y(n),o=Ft(ER(e.trim()));return Ry(o,t,r,{overwrite:!0})}async function Ry(e,t,n,r){let o=ky(e);if(!o)throw new b(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let s=Ay(e);await Gt(s,n).catch(()=>{});let i=MR(),a=await qt(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=Ft(c);try{await Iy(p,e,n,r.overwrite)}catch(g){throw await gt(p,n).catch(()=>{}),!r.overwrite&&g instanceof b&&g.status===409?new $t(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function gt(e,t){let n=await E(`${Y(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Delete failed (${n.status}): ${await Ut(n)}`,{status:n.status,response:n});return n.json()}async function Gt(e,t){let n=await E(`${Y(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Mkdir failed (${n.status}): ${await Ut(n)}`,{status:n.status,response:n});return n.json()}async function Gn(e,t,n){return Iy(e,t,Y(n),!0)}async function Iy(e,t,n,r){let o=await E(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!o.ok)throw new b(`Rename failed (${o.status}): ${await Ut(o)}`,{status:o.status,response:o});return o.json()}async function dg(){return Py(await He().project.current())}async function Ro(){return Py(await He().global.health())}async function gg(){try{return(await Ro()).healthy===!0}catch{return!1}}var Cy={list:Lt,read:Nt,readBlob:Kt,status:Un,findFiles:Fn,findText:Ln,upload:qt,write:qn,create:Nn,copy:Kn,remove:gt,mkdir:Gt,rename:Gn,currentProject:dg,health:Ro,isReachable:gg,toDaemonPath:ze,toSandboxAbsolutePath:Ft,toWorkspaceRelative:pg};function Ty(e){return{list:async t=>Lt(t,(await e()).runtimeUrl),read:async t=>Nt(t,(await e()).runtimeUrl),readBlob:async t=>Kt(t,(await e()).runtimeUrl),status:async()=>Un((await e()).runtimeUrl),findFiles:async(t,n)=>Fn(t,n,(await e()).runtimeUrl),findText:async t=>Ln(t,(await e()).runtimeUrl),upload:async(t,n,r,o)=>qt(t,n,r,(await e()).runtimeUrl,o),write:async(t,n)=>qn(t,n,(await e()).runtimeUrl),create:async t=>Nn(t,(await e()).runtimeUrl),copy:async(t,n)=>Kn(t,n,(await e()).runtimeUrl),remove:async t=>gt(t,(await e()).runtimeUrl),mkdir:async t=>Gt(t,(await e()).runtimeUrl),rename:async(t,n)=>Gn(t,n,(await e()).runtimeUrl)}}function Ey(e){return{get:t=>bn(e.projectId,e.sessionId,t),presence:(t,n)=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>wn(e.sessionId,{projectId:e.projectId}),update:t=>Qc(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),Xc(e.projectId,e.sessionId)),start:(...t)=>Le(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>yl(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Pn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),xn(e.projectId,e.sessionId)),configState:()=>Jc(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),Zc(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),el(e.projectId,e.sessionId,...t)),setSharing:t=>Tc(e.projectId,e.sessionId,t),previews:()=>Dc(e.projectId,e.sessionId),participants:()=>Ec(e.projectId,e.sessionId),watch:()=>Mc(e.projectId,e.sessionId),setWatch:t=>Oc(e.projectId,e.sessionId,t),commit:t=>wc(e.projectId,e.sessionId,t),publicShares:{list:()=>jc(e.projectId,e.sessionId),create:(...t)=>$c(e.projectId,e.sessionId,...t),revoke:(...t)=>Uc(e.projectId,e.sessionId,...t)}}}function My(e){return{reminders:{list:()=>pp(e.projectId,e.sessionId),create:t=>dp(e.projectId,e.sessionId,t),update:(t,n)=>Yr(e.projectId,e.sessionId,t,n),remove:t=>Qr(e.projectId,e.sessionId,t)},audit:(t,n)=>Nc(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Nd(e.projectId,e.sessionId,t,n),read:(t,n)=>Kd(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Kc(e.projectId,e.sessionId,t),messageAuthors:()=>sl(e.projectId,e.sessionId),modelUsage:()=>il(e.projectId,e.sessionId),transcriptSync:t=>qc(e.projectId,e.sessionId,t),turn:()=>Gc(e.projectId,e.sessionId),prompts:{create:t=>_n(e.projectId,e.sessionId,t),list:()=>Bc(e.projectId,e.sessionId),remove:t=>Wc(e.projectId,e.sessionId,t),retry:t=>zc(e.projectId,e.sessionId,t),edit:(t,n)=>Hc(e.projectId,e.sessionId,t,n),interrupt:t=>Vc(e.projectId,e.sessionId,t),hold:t=>Yc(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function Oy(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var DR=["control_plane","provider_ingress","daemon","upstream_port"];function mg(e){return typeof e=="string"&&DR.includes(e)?e:null}function fg(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 yg(e,t){let n=(e===void 0?Me():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await E(`${n}/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=mg(r.headers.get("X-Kortix-Proxy-Hop"))??mg(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 Dy=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,jy=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,$y=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,Uy=new Set([22,4096,parseInt(Te.KORTIX_MASTER,10)]);function jR(e){return jy.test(e)}function Io(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 $R(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var UR=new Set(["'",'"',"`","<","(","["]),FR=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function LR(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&&UR.has(e[t]);)t++;for(;n>t&&FR.has(e[n-1]);)n--;return e.slice(t,n)}function NR(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var KR=/^\/proxy\/(\d{1,5})(\/.*)?$/,qR=/^\/(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 Fy(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:qR.test(t.pathname)}catch{return!1}}function Wn(e){if(!e)return null;let t=LR($R(e.trim())),n=bg(t);if(n){let r=Io(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(Te.KORTIX_MASTER,10);if(o===i){let c=r.pathname.match(KR);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return o=p,s=Io(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${o}${s}`,port:o,path:s}}}let a=Io(s);return{originalUrl:`${r.protocol}//${r.hostname}:${o}${a}`,port:o,path:a}}catch{let r=NR(e);return r&&r!==e?Wn(r):null}}function GR(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 BR(e,t){return t.some(([n,r])=>e>=n&&e<r)}function Ly(e){let t=[],n=new Set,r=GR(e);Dy.lastIndex=0;let o;for(;(o=Dy.exec(e))!==null;){let s=Wn(o[0]);if(!s)continue;let{originalUrl:i,port:a,path:c}=s;a<1||a>65535||Uy.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:BR(o.index,r)}))}return t}function WR(e){return Ly(e).length>0}function HR(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function Ny(e){return e.trim().toLowerCase().split("_").join("-")}function Ky(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function VR(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(Ny(n.sandboxId));return`${Ky(o)}${t}`}function qy(e){return e.sandboxId.trim().length>0}function Ye(e,t,n){let r=Io(t);if(!qy(n))return Hy(e,r);let o=VR(e,r,n);return o||(HR(n.apiBaseUrl)?`http://p${e}-${Ny(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${Ky(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function zR(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(o=>encodeURIComponent(o)).join("/");return Ye(3211,`/open?path=/workspace/${r}`,t)}function Gy(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function YR(e){return`http://localhost:3211${Gy(e)}`}function By(){return"/health"}function QR(e){return Ye(3211,By(),e)}function XR(e,t){return Ye(e,"/",t)}function Wy(e){let t=Wn(e);return!(!t||Uy.has(t.port)||Fy(e))}function hg(e,t){if(!e)return e;let n=Wn(e);return n?Wy(n.originalUrl)?Ye(n.port,n.path,t):n.originalUrl:e}function Hy(e,t="/"){return`http://localhost:${e}${t}`}var Vy=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function bg(e){let t=e.match(jy);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($y);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(Vy);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 JR(e){try{let t=bg(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function ZR(e){return jR(e)||$y.test(e)||Vy.test(e)}function eI(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Bn="/web-proxy/";function tI(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),o=`${Bn}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,s=parseInt(Te.KORTIX_MASTER,10);return`${Ye(s,"/",t).replace(/\/$/,"")}${o}`}catch{return null}}function nI(e){try{let t=new URL(e),n=t.pathname.indexOf(Bn);if(n===-1)return null;let o=t.pathname.slice(n+Bn.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 rI(e){try{return new URL(e).pathname.includes(Bn)}catch{return e.includes(Bn)}}function oI(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 sI(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 zy(e){return{health:t=>yg(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>Ye(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>hg(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Fe(e.requireReady("sandboxPortUrl").sandboxId,t)}}function _g(e,t,n,r){let o,s,{persistedPromptDefaults:i,clearPersistedDefaults:a}=Nf(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=Wf(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{...Ey(m),...My(m),...zy(m),...Qf(m),...ry(m),...yy(m),files:Ty(c),...Yf(m),get runtime(){return be(d("runtime").runtimeUrl)}}}function Yy(e){return{apps:{list:()=>qp(e),create:t=>Gp(e,t),get:t=>Xr(e,t),update:(...t)=>Bp(e,...t),access:{get:(...t)=>zp(e,...t),update:(...t)=>Qp(e,...t),session:(...t)=>Xp(e,...t),agents:t=>Yp(e,t)},remove:t=>Wp(e,t),token:t=>Hp(e,t),authEnv:t=>Vp(e,t),artifacts:{register:t=>Jr(e,t),uploadArchive:(...t)=>Jp(e,...t),finalize:(...t)=>Zr(e,...t)},deployments:{create:(...t)=>Zp(e,...t),list:t=>ed(e,t),get:(...t)=>td(e,...t),logs:(...t)=>nd(e,...t),remove:(...t)=>sd(e,...t)},start:t=>rd(e,t),stop:t=>od(e,t),rollback:(...t)=>id(e,...t),machines:{list:t=>ad(e,t),start:(t,n)=>ld(e,t,n),stop:(t,n)=>ud(e,t,n),restart:(t,n)=>pd(e,t,n),destroy:(t,n)=>dd(e,t,n)},scale:(t,n)=>gd(e,t,n),exec:(...t)=>md(e,...t),volumes:{list:t=>fd(e,t),create:(...t)=>yd(e,...t),update:(...t)=>hd(e,...t),destroy:(...t)=>bd(e,...t),snapshots:(...t)=>_d(e,...t),snapshot:(...t)=>Pd(e,...t),restore:(...t)=>xd(e,...t),fork:(...t)=>Sd(e,...t)}}}}function Qy(e){return{list:()=>wi(e),invite:(...t)=>ki(e,...t),update:(...t)=>vi(e,...t),revoke:t=>Ai(e,t),pendingInvites:()=>Ri(e),resendInvite:(...t)=>Ci(e,...t),revokeInvite:(...t)=>Ii(e,...t),requests:()=>Pi(e),approveRequest:(...t)=>xi(e,...t),rejectRequest:(...t)=>Si(e,...t),groupGrants:()=>Ti(e),attachGroupGrant:(...t)=>Ei(e,...t),updateGroupGrant:(...t)=>Mi(e,...t),detachGroupGrant:t=>Oi(e,t),resourceGrants:{list:()=>Di(e),create:t=>ji(e,t),remove:t=>$i(e,t)}}}function Xy(e){return{tokens:{list:()=>xp(e),create:t=>Sp(e,t),revoke:t=>wp(e,t)},setupLinks:{requestSecret:t=>Mp(e,t),requestConnector:t=>Op(e,t)},validateManifest:t=>Xs(e,t),gitToken:()=>Js(e),agentIdentities:()=>ju(e),secrets:{list:()=>Ni(e),upsert:t=>Ki(e,t),setStrategy:(...t)=>qi(e,...t),broker:(...t)=>Gi(e,...t),remove:t=>Vi(e,t),setPersonal:(...t)=>zi(e,...t),removePersonal:t=>Yi(e,t),setGitCredential:t=>Hi(e,t),listProviderOAuth:()=>Bi(e),startProviderOAuth:(...t)=>Ar(e,...t),pollProviderOAuth:(...t)=>kr(e,...t),removeProviderOAuth:t=>Wi(e,t)},access:Qy(e)}}function Jy(e){return{list:()=>la(e),listAll:()=>ua(e),reconcile:(...t)=>pa(e,...t),reconcileMember:(...t)=>da(e,...t),updateCredential:(...t)=>ga(e,...t),revoke:(...t)=>ma(e,...t),activate:(...t)=>fa(e,...t),setDefault:(...t)=>ya(e,...t),rename:(...t)=>ha(e,...t),share:(...t)=>_a(e,...t),addComputer:(...t)=>ba(e,...t),pipedreamConnect:(...t)=>Pa(e,...t),pipedreamFinalize:(...t)=>xa(e,...t)}}function Co(e){return{catalog:t=>wt(e,t),tools:()=>Tr(e),search:(...t)=>ca(e,...t),describe:(...t)=>Er(e,...t),call:(...t)=>st(e,...t),callAction:(t,n,r,o)=>st(e,`${t}.${n}`,r,o),accounts:(...t)=>Mr(e,...t),uploadAttachment:(...t)=>Or(e,...t)}}function Pg(e,t){return{slug:t,run:(r,o,s)=>Fr(e,t,r,o,s),call:(r,o,s)=>st(e,`${t}.${r}`,o,s),describe:async r=>r!==void 0?Er(e,`${t}.${r}`):(await wt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(s=>s.slug===t)??null,accounts:()=>Mr(e,t),paginate:(r,o,s)=>qa(e,t,r,o,s),uploadAttachment:(r,o)=>Or(e,r,{...o,connector:t})}}var iI=100,aI=0,cI=new Set(["attachment_size_mismatch","attachment_failed"]),Zy=()=>new b("Attachment expired. Attach the file again.",{code:"attachment_expired"});function eh(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 xg(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,_){y.removalDeleted||(y.removalDeleted=!0,vt(e,_).catch(()=>{}))}function m(){c&&clearTimeout(c);let y=d().map(({item:x})=>x);(y.length!==p.attachments.length||y.some((x,M)=>x!==p.attachments[M]))&&(p={attachments:y});let _=Math.min(...y.filter(x=>x.status==="ready").map(x=>Date.parse(x.attachment.expires_at)));Number.isFinite(_)&&!a&&(c=setTimeout(()=>{for(let x of d())x.item.status==="ready"&&Date.parse(x.item.attachment.expires_at)<=Date.now()&&(x.item={...x.item,status:"error",error:Zy()});m()},Math.min(2147483647,Math.max(0,_-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let x of o)x();for(let x of[...s])x()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(y){f();let _=d();if(_.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(M=>!Number.isSafeInteger(M)||M<=0||M>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(_.reduce((M,w)=>M+w.item.size,0)+y.reduce((M,w)=>M+w,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function S(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let _=y.item.file;i++;let x=++y.generation,M=new AbortController;y.abort=M,y.item={...y.item,status:"uploading",error:void 0};let w=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===x,P,A=0,C,T=()=>{C=void 0,!(!w()||y.item.status!=="uploading"||P===void 0)&&(y.item={...y.item,receivedBytes:P},P=void 0,A=Date.now(),m())},N=$=>Math.floor($*100/y.item.size);yn(e,_,{resume:y.upload,signal:M.signal,onUpload:$=>{y.upload=$,y.removed&&(M.abort(),g(y,$.attachment_id))},onProgress:$=>{if(!w()||N($)===N(y.item.receivedBytes)||(P=$,C))return;let K=A+iI-Date.now();if(K<=0)return T();C=setTimeout(T,K),typeof C=="object"&&"unref"in C&&C.unref()},onProcessing:()=>{C&&clearTimeout(C),C=void 0,P=void 0,w()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then($=>{w()&&(y.item={...y.item,status:"ready",attachment:eh($),receivedBytes:$.size})}).catch($=>{$ instanceof b&&cI.has($.code??"")&&(y.upload=void 0),w()&&(y.item={...y.item,status:$ instanceof b&&$.code==="ABORTED"?"aborted":"error",error:$ instanceof Error?$:new Error(String($))})}).finally(()=>{i--,C&&clearTimeout(C),y.abort===M&&(y.abort=void 0),m(),S()})}m()}function D(y){h(y.map(x=>x.size));let _=y.map(x=>{let M=`attachment-${++aI}`;return r.set(M,{generation:0,item:{id:M,file:x,filename:x.name,mime:x.type||"application/octet-stream",size:x.size,status:"pending",receivedBytes:0}}),M});return m(),S(),_}function j(y){let _=r.get(y);!_||_.item.status==="ready"||(_.generation++,_.abort?.abort(),_.item={..._.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function L(y,{signal:_}={}){let x=[...y];return new Promise((M,w)=>{let P=()=>{s.delete(T),_?.removeEventListener("abort",C)},A=N=>{P(),w(N)},C=()=>A(me()),T=()=>{let N=!1;for(let K of x){let q=r.get(K);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"&&(N=!0)}if(N)return;let $;try{$=x.map(K=>{let q=eh(r.get(K).item.attachment);return{type:"file",attachment_id:q.attachment_id,filename:q.filename,mime:q.mime}})}catch(K){return A(K instanceof Error?K:new Error(String(K)))}P(),M($)};if(_?.aborted)return C();s.add(T),_?.addEventListener("abort",C,{once:!0}),T()})}return{add:y=>D([y])[0],addMany:D,retry(y){let _=r.get(y);if(_?.handedOff||f(),!(!_||_.item.status==="ready"||_.item.status==="uploading"||_.item.status==="processing"||_.item.status==="pending")){if(!_.item.file||_.upload&&Date.parse(_.upload.expires_at)<=Date.now())throw Zy();_.item={..._.item,status:"pending",error:void 0},S()}},async remove(y){let _=r.get(y);if(!_)return;_.removed=!0,_.generation++,r.delete(y);let x=_.upload?.attachment_id??_.item.attachment?.attachment_id;x&&_.abort?.abort(),m(),S(),x&&g(_,x)},abort:j,submit(y){if(!a){for(let _ of y){let x=r.get(_);x&&(x.handedOff=!0)}m()}},reclaim(y){if(!a){for(let _ of y){let x=r.get(_);x&&(x.handedOff=!1)}m()}},whenReady:L,forget(y=d().map(_=>_.item.id)){for(let _ of y){let x=r.get(_);x&&(x.generation++,x.abort?.abort(),r.delete(_))}m(),S()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let _=y.upload?.attachment_id??y.item.attachment?.attachment_id;_&&e&&vt(e,_).catch(()=>{})}o.clear(),m()}},getSnapshot:()=>p,subscribe(y){return o.add(y),()=>{o.delete(y)}}}}function th(e){return{attachments:{upload:(...t)=>yn(e,...t),delete:(...t)=>vt(e,...t),createController:t=>xg(e,t)},get:t=>on(e,t),detail:()=>sn(e),skills:{create:(...t)=>ii(e,...t)},audit:t=>kp(e,t),update:t=>ln(e,t),archive:()=>un(e),llmCatalog:()=>an(e),modelPicker:()=>cn(e),modelAccess:()=>vn(e),setModelAccess:t=>An(e,t),sandboxHealth:()=>dn(e),onboardingComplete:(...t)=>si(e,...t)}}function nh(e){return{sessions:{list:t=>it(e,t),listPage:t=>Cc(e,t),create:t=>at(e,t),ensureWarm:()=>Fc(e),claimWarm:t=>Lc(e,t)},review:{list:t=>ep(e,t),get:t=>tp(e,t),submit:t=>np(e,t),act:(...t)=>rp(e,...t),bulkAct:t=>op(e,t)},approvals:{list:t=>Ui(e,t),resolve:(...t)=>Li(e,...t),sessionsNeedingInput:t=>Fi(e,t)}}}function rh(e){return{files:{list:t=>ec(e,t),listDirectory:t=>tc(e,t),read:(t,n)=>rc(e,t,n),search:(...t)=>nc(e,...t),archive:(...t)=>oc(e,...t),archiveRequest:(...t)=>sc(e,...t),history:(...t)=>dc(e,...t)},git:{commits:()=>lc(e),commit:t=>uc(e,t),commitDiff:t=>pc(e,t),branches:()=>cc(e),versionDiff:(...t)=>gc(e,...t),inviteCollaborator:(...t)=>Qs(e,...t)},changeRequests:{list:()=>mc(e),get:t=>fc(e,t),update:(...t)=>vc(e,...t),diff:t=>yc(e,t),mergePreview:t=>hc(e,t),open:(...t)=>bc(e,...t),merge:(...t)=>_c(e,...t),close:(...t)=>Pc(e,...t),reopen:(...t)=>xc(e,...t),requestChanges:(...t)=>Sc(e,...t)},...nh(e)}}function oh(e){return{policies:{list:()=>Ga(e),set:(...t)=>Ba(e,...t)},reminders:{list:()=>fp(e),updateMany:(...t)=>gp(e,...t),removeMany:(...t)=>mp(e,...t)},triggers:{list:()=>al(e),eventApps:()=>ml(e),eventTypes:(...t)=>gl(e,...t),create:(...t)=>cl(e,...t),update:(...t)=>ll(e,...t),remove:(...t)=>ul(e,...t),fire:(...t)=>dl(e,...t),setActivation:(...t)=>pl(e,...t)},...rh(e)}}function sh(e,t){return{connectors:{...Co(e),list:()=>Sa(e),config:(...n)=>Ca(e,...n),create:(...n)=>Ma(e,...n),remove:(...n)=>Da(e,...n),sync:()=>wa(e),auth:{discover:(...n)=>Oa(e,...n)},setName:(...n)=>Ta(e,...n),setCredentialMode:(...n)=>va(e,...n),setAuthorizationStrategy:(...n)=>Aa(e,...n),setCredential:(...n)=>La(e,...n),deleteCredential:(...n)=>Na(e,...n),setSensitive:(...n)=>ka(e,...n),connections:t,policies:{get:(...n)=>Ra(e,...n),set:(...n)=>Ia(e,...n)},pipedream:{listApps:(...n)=>ja(e,...n),listSections:(...n)=>$a(e,...n),connect:(...n)=>Ea(e,...n),finalize:(...n)=>Ka(e,...n)},discover:{list:(...n)=>Dr(e,...n),sections:(...n)=>Ua(e,...n),detail:(...n)=>jr(e,...n)}},...oh(e)}}function ih(e){return{gateway:{logs:t=>pu(e,t),log:t=>du(e,t),overview:t=>gu(e,t),series:t=>mu(e,t),breakdown:t=>fu(e,t),sessions:t=>yu(e,t),errors:t=>hu(e,t),budgets:()=>bu(e),setBudget:t=>_u(e,t),deleteBudget:t=>Pu(e,t),keys:()=>xu(e),createKey:t=>Su(e,t),revokeKey:t=>wu(e,t),routing:{get:()=>au(e),set:t=>cu(e,t),reset:()=>lu(e),preview:t=>uu(e,t)},playground:(t,n,r)=>vu(e,t,n,r)}}}function ah(e){return{modelDefaults:{get:()=>hl(e),set:t=>bl(e,t),clear:t=>_l(e,t)},setDefaultAgent:t=>Sl(e,t),sandbox:{list:()=>Za(e),snapshots:()=>Ha(e),rebuildSnapshot:t=>Va(e,t),fixWithAgent:()=>za(e),createTemplate:t=>Ya(e,t),updateTemplate:(...t)=>Qa(e,...t),removeTemplate:t=>Xa(e,t),buildTemplate:t=>Ja(e,t),setProvider:t=>oi(e,t)},setAgentScope:(...t)=>Pl(e,...t)}}function ch(e){return{channels:{slack:{installation:()=>Hl(e),connect:t=>Vl(e,t),mode:()=>zl(e),completeInstall:t=>Yl(e,t),manifest:()=>Xl(e),disconnect:()=>Jl(e),getFile:t=>Zl(e,t),uploadFile:t=>eu(e,t)},teams:{completeInstall:t=>Ql(e,t)},email:{installation:t=>nu(e,t),mode:()=>ru(e),connect:t=>ou(e,t),disconnect:t=>su(e,t),updatePolicy:(...t)=>iu(e,...t)}},updateFeatureFlag:(...t)=>ni(e,...t),updateExperimentalFeature:(...t)=>ri(e,...t),...ah(e)}}function lI(){return He()}var lh=null,uh=!1;function uI(e){let t=lh;lh=e,!(uh||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(uh=!0,console.warn("[kortix] createKortix() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedKortix() from @kortix/sdk/server.")))}function ph(e,t){t?.global!==!1&&uI(e),gr(e,t);let n=Lf(e),{auth:r,accounts:o,iam:s,accountInvites:i}=Df(),{billing:a,sandboxShares:c}=Ef(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=Tf();function h(S){let D=Jy(S);return{...th(S),...Yy(S),...Xy(S),...sh(S,D),...ih(S),...ch(S),connector:j=>Pg(S,j),session:j=>_g(S,j,e,n)}}return{config:e,auth:r,accounts:o,iam:s,accountInvites:i,projects:p,connectors:Co(),connector:S=>Pg(void 0,S),project:h,session:(S,D)=>_g(S,D,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,notifications:{registerDeviceToken:vd,unregisterDeviceToken:Ad,list:kd,markRead:Rd,preferences:Id,updatePreferences:Cd,webPushPublicKey:Td,registerWebPushSubscription:Ed,unregisterWebPushSubscription:Md},validateToken:zs,runtime:lI}}function dh(){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 gh(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Bt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function mh(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function fh(e){if(Bt(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 yh(e){let t=Bt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function hh(e,t){let n=Bt(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 bh(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 _h(e,t){return Bt(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 Ph(e,t,n){return Bt(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 xh(e,t,n){let r=Bt(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 Sg={thinking:!1,toolDetails:!0,assistantMetadata:!0};function pI(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function dI(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 gI(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
19
|
+
`);a=d.pop()??"";for(let g of d){let m={},f=[];for(let b of g.split(`
|
|
20
|
+
`))if(b.startsWith("data:"))f.push(b.replace(/^data:\s*/,""));else if(b.startsWith("id:"))m.id=b.replace(/^id:\s*/,"");else if(b.startsWith("retry:")){let P=Number.parseInt(b.replace(/^retry:\s*/,""),10);Number.isNaN(P)||(m.retry=P)}f.length&&(m.data=f.join(`
|
|
21
|
+
`)),yield m}}}finally{r.removeEventListener("abort",i),s.releaseLock()}}}async function*ck(e,t,n){let r=e.eventTransport??rg(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 Kn(e){let t=o=>(s,i)=>ak(e,sk(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:ck(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 hy=200;async function lk(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 bt(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 h(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function by(e){let t=e.runtimeUrl.replace(/\/$/,""),n=Kn({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=P=>e.fetch(new Request(`${t}${P}${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 h(`Reading the session transcript failed: ${await lk(f)}`,{status:f.status,response:f});let b=await f.json();return{messages:b.messages??[],hasMore:b.has_more===!0}},i=await s(r.limit===void 0?void 0:Math.min(r.limit,hy),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await s(Math.min(r.limit-a.length,hy),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,o,s]=await Promise.all([n.session.status().then(i=>bt(i,"Reading the session status failed")),n.permission.list().then(i=>bt(i,"Reading permission requests failed")),n.question.list().then(i=>bt(i,"Reading questions failed"))]);return{statuses:r??{},permissions:o??[],questions:s??[]}},answerPermission:async(r,o,s)=>{bt(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){bt(await n.question.reject({requestID:r}),"Dismissing the question failed");return}bt(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 h("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return bt(await n.session.summarize({sessionID:e.rootId,providerID:o.providerID,modelID:o.modelID}),"Compacting the session failed"),o}}}function _y(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return by({runtimeUrl:r,rootId:n,fetch:E})}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 Py(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await dl(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Ft=BigInt(4096),Ue=BigInt(0xffffffffffff),xy=Ue+BigInt(1),uk=xy/BigInt(2),Qe=BigInt(3600*1e3)*Ft,Ro=120*1e3,Sy=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,pk=/^msg_([0-9a-f]{12})/,wy="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function _t(e){let t=pk.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function Nt(e){return BigInt(Math.trunc(e))*Ft&Ue}function Pt(e,t){let n=e-t&Ue;return n>=uk&&(n-=xy),n}function og(e){let t=null;for(let n of e)n!=null&&(t===null||Pt(n,t)>BigInt(0))&&(t=n);return t}function Ay(e,t){let n=_t(e);return n===null?!1:Pt(n,Nt(t))>Qe}function vy(e,t){let n=t===void 0?null:Nt(t);return ky(e,r=>n===null||Pt(r,n)<=Qe)}function ky(e,t){let n=[];for(let r of e){let o=_t(r);o!==null&&t(o)&&n.push(o)}return og(n)}function dk(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=wy[n%62])}return e}function sg(e){let t=e.random,n=Nt(e.nowMs-(e.backdateMs??Ro)),r=e.newestKnownTime??null;if(r!==null){let s=Pt(r,n);s>=BigInt(0)&&s<=Qe&&(n=r+BigInt(1)&Ue)}let o="";if(t)for(let s=0;s<14;s++)o+=wy[Math.min(61,Math.floor(t()*62))];else o=dk();return{id:`msg_${n.toString(16).padStart(12,"0")}${o}`,time:n}}function Co(e={}){let t=e.nowMs??Date.now(),n=Nt(t-Ro),r=ky(e.after??[],o=>{let s=Pt(o,n);return s>=BigInt(0)&&s<=Qe});return sg({nowMs:t,newestKnownTime:r}).id}function Ry(e){return{scope:()=>ul(e.projectId,e.sessionId),providerSecretPool:{list:()=>fa(e.projectId,e.sessionId),get:t=>ma(e.projectId,e.sessionId,t),set:(t,n)=>ya(e.projectId,e.sessionId,t,n)},rescope:t=>pl(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=Co(),p=await In(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 h("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var gk="kortix.transcript.v1",Cy=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function mk(e){return typeof e=="string"&&Cy.includes(e)}var fk=["once","always","reject"],yk=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var Iy=async function*(e){let t=v().eventStreamTransport;if(!t){yield*rg(((o,s)=>E(o,s,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await Er(e.url,e.headers);try{yield*t({...e,headers:n})}catch(o){throw o?.status===401&&r(),o}};function Le(){let e=gy();return e||(v().billingEnabled??!1?"":Mf())}async function ig(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function ag(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function cg(e){let t=ag(e),n=await E(`${t}/env`);if(!n.ok)throw new Error(await ig(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function lg(e,t,n){let r=ag(e),o=await E(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!o.ok)throw new Error(await ig(o,"Failed to save secret"))}async function ug(e,t){let n=ag(e),r=await E(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await ig(r,"Failed to delete secret"))}var Ty={list:cg,set:lg,delete:ug};async function Ey(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let o=await E(`${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 Io(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function qn(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return oe(e)}async function dg(e){let t=qn(e),n=await E(`${t}/kortix/pty`);if(!n.ok)throw new Error(await Io(n,"Failed to list terminals"));return n.json()}async function gg(e,t){let n=qn(e),r=await E(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await Io(r,"Failed to create terminal"));return r.json()}async function mg(e,t,n){let r=qn(e),o=await E(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(await Io(o,"Failed to update terminal"));return o.json()}async function fg(e,t){let n=qn(e),r=await E(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Io(r,"Failed to remove terminal"))}async function yg(e,t,n){let r=qn(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:"),oe(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await It();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${s}${s.includes("?")?"&":"?"}${c}`:s}function My(e){let t=e.reason.trim().toLowerCase();return t.includes("pty not found")?"replace":t.includes("pty exited")?"ended":e.hadError||t.includes("idle timeout")||t.includes("upstream error")||e.code!==1e3?"reconnect":"ended"}var Xe="\x1B",Oy="\x07",hk="\0",pg=`(?:${Oy}|${Xe}\\\\)`,bk=[new RegExp(`${Xe}\\]697;[^${Oy}${Xe}]*${pg}`,"g"),new RegExp(`${hk}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${Xe}\\][0-9]+;rgb:[0-9a-fA-F/]+${pg}`,"g"),new RegExp(`${Xe}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${pg}`,"g"),new RegExp(`${Xe}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${Xe}\\[\\d+;\\d+R`,"g"),new RegExp(`${Xe}\\[\\?[0-9;]*c`,"g")];function Dy(e){let t=e;for(let n of bk)t=t.replace(n,"");return t}var jy={list:dg,create:gg,update:mg,remove:fg,webSocketUrl:yg};async function R(e,t,n,r){let o=e;for(;o.endsWith("/");)o=o.slice(0,-1);let s=await E(`${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 _k(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return R(e,`/kortix/tasks${r}`)}async function Pk(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function xk(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function Sk(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function wk(e,t){return R(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function Ak(e,t,n){return R(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function vk(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function kk(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function Rk(e,t){return R(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Ck(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return R(e,`/kortix/tickets${n}`)}async function Ik(e,t){return R(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function Tk(e,t){return R(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function Ek(e,t){return R(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function Mk(e,t,n){return R(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function Ok(e,t,n){return R(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function Dk(e,t,n){return R(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function jk(e,t,n){return R(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function $k(e,t,n){return R(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function Uk(e,t){return R(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Lk(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function Fk(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function Nk(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function Kk(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function qk(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function Bk(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function Gk(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function Wk(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function Hk(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function Vk(e,t,n,r){return R(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function zk(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Yk(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function Qk(e,t,n=200){return R(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function Xk(e){return R(e,"/kortix/projects")}async function Jk(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function Zk(e,t){return R(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function eR(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function tR(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function nR(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function rR(e,t,n="all"){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function oR(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function sR(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function iR(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function aR(e,t,n,r){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function cR(e,t,n,r){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function lR(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function uR(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function pR(e,t){return R(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function dR(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function gR(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function mR(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function fR(e,t,n){return R(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var yR=1e4,hR={retryOnAuthError:!1};function Kt(e,t,n){return R(e,t,{signal:AbortSignal.timeout(yR),...n},hR)}async function bR(e,t=!1){return(await Kt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function _R(e){return(await Kt(e,"/kortix/services/templates")).templates??[]}async function PR(e,t){return(await Kt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function xR(e,t,n){let r=n==="delete",o=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return Kt(e,o,{method:r?"DELETE":"POST"})}async function SR(e,t){return Kt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function wR(e,t){return Kt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Fe=new Map,AR=256,qt=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function Je(){let e=Le();if(!e)throw new qt;return Se(e)}function Se(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Fe.get(e);if(t)return Fe.delete(e),Fe.set(e,t),t;if(!wr())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=Kn({baseUrl:e,fetch:E,eventTransport:Iy});return Fe.set(e,n),Fe.size>AR&&Fe.delete(Fe.keys().next().value),n}function vR(e){Fe.delete(e)}function kR(){Fe.clear()}var To=new Map;function RR(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=To.get(e);if(t)return t;let n=Kn({baseUrl:e,fetch});return To.set(e,n),n}function CR(e){To.delete(e)}function IR(){To.clear()}async function TR(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 ER(e){let t=Le();if(!t)throw new h("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await E(`${t}${n}`,{method:"POST"}),o=r.headers.get("content-type")??"",s=/^application\/([\w.+-]+\+)?json\b/i.test(o.trim());if(!r.ok)throw new h(`System reload failed (${r.status}): ${await TR(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!s)throw new h(`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 h(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var $y="frontend";function Eo(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${$y}] ${t}`,...n?[n]:[]);try{Je().app.log({service:$y,level:e,message:t,extra:n})}catch{}}var Ze={debug:(e,t)=>Eo("debug",e,t),info:(e,t)=>Eo("info",e,t),warn:(e,t)=>Eo("warn",e,t),error:(e,t)=>Eo("error",e,t)};function Uy(e){return{type:"heartbeat-gap",gapMs:e}}function Ly(e){switch(e.type){case"message.updated":return{type:"message.updated",sessionID:e.properties.sessionID,message:e.properties.info};case"message.removed":return{type:"message.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID};case"message.part.updated":return{type:"message.part.updated",sessionID:e.properties.sessionID,part:e.properties.part};case"message.part.removed":return{type:"message.part.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID,partID:e.properties.partID};case"session.status":return{type:"session.status",sessionID:e.properties.sessionID,status:e.properties.status};case"session.idle":return{type:"session.idle",sessionID:e.properties.sessionID};case"session.error":return{type:"session.error",sessionID:e.properties.sessionID,error:e.properties.error};case"question.asked":return{type:"question.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,questions:e.properties.questions,tool:e.properties.tool};case"question.replied":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"replied",answers:e.properties.answers};case"question.rejected":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"rejected"};case"permission.asked":return{type:"permission.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,permission:e.properties.permission,patterns:e.properties.patterns,tool:e.properties.tool};case"permission.replied":return{type:"permission.replied",sessionID:e.properties.sessionID,requestID:e.properties.requestID,reply:e.properties.reply};case"todo.updated":return{type:"todo.updated",sessionID:e.properties.sessionID,todos:e.properties.todos};case"server.connected":return{type:"connection",status:"connected"};default:return null}}var MR={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},OR=16,DR=8,jR=6e4,$R=5e3,UR=250,LR=1e3,FR=3e4,NR=5,KR=1e4,qR=4,BR=.5,GR=3e3,WR=3e4,HR=2e4,VR=2e3,zR=8;function YR(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function QR(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 Fy(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 Bn=new WeakMap;function XR(e,t,n){let r=t.timers??MR,o=t.connectTimeoutMs??HR,s=t.heartbeatTimeoutMs??jR,i=t.maxConsecutiveHardFailures??zR,a=new AbortController;function c(_,...w){for(let D of n){let T=_(D);if(T)try{T(...w)}catch(x){console.warn("[opencode-events] subscriber handler threw, skipping",x)}}}let p=null,d=!1,g=_=>{p!==_&&(p=_,_&&c(w=>w.onConnectionChange,_))},m=r.now(),f=null,b=[],P,j=0,L=new Map,N=()=>{if(P&&r.clearTimeout(P),P=void 0,b.length===0)return;let _=b;b=[],L.clear(),j=r.now(),m=r.now();for(let w of _)w&&c(D=>D.onEvent,w.event)},y=()=>{if(P)return;let _=r.now()-j;P=r.setTimeout(N,Math.max(0,OR-_))};return(async()=>{let _=0,w=0,D=0;for(;!a.signal.aborted;){let T=!1,x=!1,S,I,C=null,F=r.now(),M=new AbortController;g("connecting");let K=Fy(a.signal);K.promise.then(()=>M.abort());try{let X=await new Promise((At,it)=>{let ie=!1;I=r.setTimeout(()=>{ie||(ie=!0,Ze.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:o}),M.abort(),it(new Error(`SSE connect timed out after ${o}ms`)))},o),e.global.event({signal:M.signal,sseDefaultRetryDelay:GR,sseMaxRetryDelay:WR,sseMaxRetryAttempts:1}).then(Ce=>{ie||(ie=!0,r.clearTimeout(I),At(Ce))},Ce=>{ie||(ie=!0,r.clearTimeout(I),it(Ce))})}),{stream:ot}=X;if(f){let At=r.now()-f.lastActivityAt,it=f.eventful;f=null,(it||At>$R)&&c(ie=>ie.onGapRehydrate,At)}m=r.now();let st=()=>{r.clearTimeout(S),S=r.setTimeout(()=>{Ze.warn("SSE heartbeat timeout, forcing reconnect"),M.abort()},s)};st();let Pr=r.now(),OP=ot[Symbol.asyncIterator]();for(;!M.signal.aborted;){let At=OP.next().then(Ie=>({kind:"next",result:Ie}),Ie=>({kind:"error",error:Ie})),it=Fy(M.signal),ie=await Promise.race([At,it.promise.then(()=>({kind:"aborted"}))]);if(it.cleanup(),ie.kind==="aborted")break;if(ie.kind==="error")throw ie.error;if(ie.result.done)break;g("open"),st();let Ce=ie.result.value,vt=Ce&&typeof Ce=="object"&&"payload"in Ce?Ce.payload:Ce;if(!vt?.type)continue;vt.type!=="server.connected"&&(T=!0);let ds=QR(b[b.length-1]?.event,vt);if(ds)b[b.length-1]={type:ds.type,event:ds};else{let Ie=YR(vt);if(Ie){let $m=L.get(Ie);$m!==void 0&&(b[$m]=void 0),L.set(Ie,b.length)}b.push({type:vt.type,event:vt})}y(),!(r.now()-Pr<DR)&&(Pr=r.now(),await new Promise(Ie=>r.setTimeout(Ie,0)))}x=T}catch(X){if(a.signal.aborted)break;C=X;let ot=String(X),st=kt(X)||kt(X?.cause);if(Ze.error("SSE event stream error",{error:ot,retryCount:_,isAuthError:st}),st)try{Ur(),await $r(),Ze.info("SSE: refreshed auth token after auth error")}catch(Pr){Ze.error("SSE: failed to refresh auth token",{error:String(Pr)})}}finally{r.clearTimeout(S),r.clearTimeout(I),M.abort(),K.cleanup(),N()}if(a.signal.aborted)break;let q=r.now()-F,ge=C?.cause?.status;if(w=!T&&(typeof ge=="number"&&ge>=400||q<VR)?w+1:0,w>=i){Ze.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:w,lastError:String(C)}),p=null,d=!0,c(X=>X.onParked,{consecutiveFailures:w,lastError:C});break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||T},D=x&&q<KR?D+1:0;let ke=x&&D<=qR;ke?_=0:(_++,_>1&&Ze.warn("SSE event stream reconnecting",{retryCount:_}));let ln=ke?UR:Math.min(LR*2**Math.min(_-1,NR),FR),Re=Math.round(ln*(1+BR*(r.random?.()??0)));await new Promise(X=>{let ot=r.setTimeout(X,Re),st=()=>{r.clearTimeout(ot),X()};a.signal.addEventListener("abort",st,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),P&&r.clearTimeout(P)}}}function Mo(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o,signal:s}=e,i=e.client??(e.url?Se(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=Bn.get(i);if(c?.isParked()&&(Bn.delete(i),c=void 0),!c)c=XR(i,e,new Set([a])),Bn.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(),Bn.get(i)===p&&Bn.delete(i)))},m=()=>g();return s&&(s.aborted?g():s.addEventListener("abort",m,{once:!0})),{close:g}}function Ny(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Se(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Se(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Se(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return Mo({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Gy(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 h(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Wt(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??Le()).trim();if(!t)throw new qt;return t}async function Do(e,t){let n=await E(`${J(t)}${e}`);if(!n.ok)throw new h(await Wt(n),{status:n.status,response:n});return n.json()}var jo=["/workspace","/tmp","/home","/opt"],JR=jo.filter(e=>e!=="/workspace");function _g(e){return jo.some(t=>e===t||e.startsWith(`${t}/`))}function Ht(e){return _g(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function et(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(JR.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Pg=et;async function Vt(e,t){let n=J(t),r=et(e)||".";return(await Do(`/file?path=${encodeURIComponent(r)}`,n)).map(s=>({...s,path:s.absolute||`/workspace/${s.path}`}))}async function zt(e,t){let n=J(t),r=et(e),o=await E(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!o.ok)throw new h(await Wt(o),{status:o.status,response:o});return o.json()}async function ZR(e,t,n){let r=J(n),o=et(e),s=await E(`${r}/file/raw?path=${encodeURIComponent(o)}`);if(!s.ok)throw new h(await Wt(s),{status:s.status,response:s});if((s.headers.get("content-type")||"").includes("text/html"))throw new h("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}var eC=8,Oo=0,Wy=[];async function tC(){if(Oo<eC){Oo++;return}await new Promise(e=>Wy.push(e)),Oo++}function nC(){Oo--,Wy.shift()?.()}function Hy(e,t){let n=J(t);return xn(`${n}/file/raw?path=${encodeURIComponent(et(e))}`)}async function Yt(e,t){await tC();try{let n=J(t);try{return await ZR(e,void 0,n)}catch{}let r=await zt(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"})}finally{nC()}}async function Hn(e){return Do("/file/status",J(e))}async function Vn(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)),Do(`/find/file?${o.toString()}`,r)}async function zn(e,t){let n=J(t);return(await Do(`/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 Gn=[400,1200],rC=e=>e===408||e===429||e===502||e===503||e===504,Ky=e=>new Promise(t=>setTimeout(t,e));function oC(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var hg=3e4,Vy=15*6e4,sC=256;function Bt(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return hg;let t=hg+e/sC;return Math.min(Vy,Math.max(hg,Math.round(t)))}async function iC(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 Wn(e,t){let n;for(let o=0;o<=Gn.length;o++){let s;try{s=await t(e())}catch(a){if(n=a,oC(a)||o===Gn.length)break;await Ky(Gn[o]);continue}if(s.ok)return s.json();let i=await iC(s);if(n=new h(`Upload failed (${s.status}): ${i}`,{status:s.status,response:s}),!rC(s.status)||o===Gn.length)throw n;await Ky(Gn[o])}if(n instanceof h)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new h(`Upload failed: ${r}`)}var bg=8*1024*1024;function aC(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new h(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function qy(e,t){try{e?.onProgress?.(t)}catch{}}function By(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 cC(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function Qt(e,t,n,r,o){let s=typeof r=="string"?r:void 0,i=typeof r=="string"?o:r,a=J(s),c=Bt(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=bg){let f=await Wn(()=>By(e,t,p),b=>E(`${a}/file/upload`,{method:"POST",body:b},{timeoutMs:c}));return aC(f[0],e.size),qy(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await Wn(()=>By(new Blob([],{type:e.type}),t,p),f=>E(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:Bt(0)})))[0]?.path;if(!g)throw new h("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=cC(g);if(!m.name)throw new h(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=bg){let b=Math.min(e.size,f+bg),P=e.slice(f,b,e.type),j=await Wn(()=>{let L=new FormData;return m.parent&&L.append("path",m.parent),L.append("filename",m.name),L.append("first",f===0?"true":"false"),L.append("offset",String(f)),L.append("file",P,m.name),L},L=>E(`${a}/file/append`,{method:"POST",body:L},{timeoutMs:Bt(P.size)}));if(j.path!==g||j.size!==b)throw new h(`Upload verification failed for ${g}: expected ${b} bytes, received ${j.size}`,{code:"UPLOAD_SIZE_MISMATCH"});qy(i,{loadedBytes:b,totalBytes:e.size})}}catch(f){throw await xt(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function zy(e,t,n){let r=J(n);return Wn(()=>{let o=new FormData;return t&&o.append("path",t),o.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),o},o=>E(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:lC}))}var lC=Vy;function uC(e,t,n){let r=J(n),o=Bt(t.size);return Wn(()=>{let s=new FormData;return s.append(e,t,e.split("/").pop()||"file"),s},s=>E(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:o}))}var Gt=class extends h{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 Yn(e,t){let n=J(t),r=e.trim(),s=(r.startsWith("/")?r:`/${r}`).split("/"),i=s.pop()||"untitled",a=s.join("/")||"/workspace",c=Ht(`${a}/${i}`),p=[];try{p=await Vt(Yy(c),n)}catch(g){if(!(g instanceof h&&g.status===404))throw g}if(p.some(g=>g.name===Qy(c)))throw new Gt(c);let d=await Xy(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function Qn(e,t,n){let r=J(n);return uC(t,await Yt(e,r),r)}function pC(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Yy(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Qy(e){return e.slice(e.lastIndexOf("/")+1)}function dC(){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 Xn(e,t,n){let r=J(n),o=Ht(pC(e.trim()));return Xy(o,t,r,{overwrite:!0})}async function Xy(e,t,n,r){let o=Qy(e);if(!o)throw new h(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let s=Yy(e);await Xt(s,n).catch(()=>{});let i=dC(),a=await Qt(t,s,`.${o}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new h(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=Ht(c);try{await Jy(p,e,n,r.overwrite)}catch(g){throw await xt(p,n).catch(()=>{}),!r.overwrite&&g instanceof h&&g.status===409?new Gt(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function xt(e,t){let n=await E(`${J(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new h(`Delete failed (${n.status}): ${await Wt(n)}`,{status:n.status,response:n});return n.json()}async function Xt(e,t){let n=await E(`${J(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new h(`Mkdir failed (${n.status}): ${await Wt(n)}`,{status:n.status,response:n});return n.json()}async function Jn(e,t,n){return Jy(e,t,J(n),!0)}async function Jy(e,t,n,r){let o=await E(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!o.ok)throw new h(`Rename failed (${o.status}): ${await Wt(o)}`,{status:o.status,response:o});return o.json()}async function xg(){return Gy(await Je().project.current())}async function $o(){return Gy(await Je().global.health())}async function Sg(){try{return(await $o()).healthy===!0}catch{return!1}}var Zy={list:Vt,read:zt,readBlob:Yt,status:Hn,findFiles:Vn,findText:zn,upload:Qt,write:Xn,create:Yn,copy:Qn,remove:xt,mkdir:Xt,rename:Jn,currentProject:xg,health:$o,isReachable:Sg,toDaemonPath:et,toSandboxAbsolutePath:Ht,toWorkspaceRelative:Pg};function eh(e){return{list:async t=>Vt(t,(await e()).runtimeUrl),read:async t=>zt(t,(await e()).runtimeUrl),readBlob:async t=>Yt(t,(await e()).runtimeUrl),status:async()=>Hn((await e()).runtimeUrl),findFiles:async(t,n)=>Vn(t,n,(await e()).runtimeUrl),findText:async t=>zn(t,(await e()).runtimeUrl),upload:async(t,n,r,o)=>Qt(t,n,r,(await e()).runtimeUrl,o),write:async(t,n)=>Xn(t,n,(await e()).runtimeUrl),create:async t=>Yn(t,(await e()).runtimeUrl),copy:async(t,n)=>Qn(t,n,(await e()).runtimeUrl),remove:async t=>xt(t,(await e()).runtimeUrl),mkdir:async t=>Xt(t,(await e()).runtimeUrl),rename:async(t,n)=>Jn(t,n,(await e()).runtimeUrl)}}function th(e){return{get:t=>Cn(e.projectId,e.sessionId,t),presence:(t,n)=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>On(e.sessionId,{projectId:e.projectId}),update:t=>sl(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),il(e.projectId,e.sessionId)),start:(...t)=>We(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>vl(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Tn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),En(e.projectId,e.sessionId)),configState:()=>al(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),cl(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),ll(e.projectId,e.sessionId,...t)),setSharing:t=>Fc(e.projectId,e.sessionId,t),previews:()=>Bc(e.projectId,e.sessionId),participants:()=>Nc(e.projectId,e.sessionId),watch:()=>Kc(e.projectId,e.sessionId),setWatch:t=>qc(e.projectId,e.sessionId,t),commit:t=>Mc(e.projectId,e.sessionId,t),publicShares:{list:()=>Gc(e.projectId,e.sessionId),create:(...t)=>Wc(e.projectId,e.sessionId,...t),revoke:(...t)=>Hc(e.projectId,e.sessionId,...t)}}}function nh(e){return{reminders:{list:()=>Pp(e.projectId,e.sessionId),create:t=>xp(e.projectId,e.sessionId,t),update:(t,n)=>oo(e.projectId,e.sessionId,t,n),remove:t=>so(e.projectId,e.sessionId,t)},audit:(t,n)=>Yc(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Yd(e.projectId,e.sessionId,t,n),read:(t,n)=>Qd(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Qc(e.projectId,e.sessionId,t),messageAuthors:()=>ml(e.projectId,e.sessionId),modelUsage:()=>fl(e.projectId,e.sessionId),transcriptSync:t=>Xc(e.projectId,e.sessionId,t),turn:()=>Jc(e.projectId,e.sessionId),prompts:{create:t=>In(e.projectId,e.sessionId,t),list:()=>Zc(e.projectId,e.sessionId),remove:t=>el(e.projectId,e.sessionId,t),retry:t=>rl(e.projectId,e.sessionId,t),edit:(t,n)=>tl(e.projectId,e.sessionId,t,n),interrupt:t=>nl(e.projectId,e.sessionId,t),hold:t=>ol(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function rh(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var mC=["control_plane","provider_ingress","daemon","upstream_port"];function wg(e){return typeof e=="string"&&mC.includes(e)?e:null}function Ag(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 vg(e,t){let n=(e===void 0?Le():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await E(`${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=wg(r.headers.get("X-Kortix-Proxy-Hop"))??wg(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 oh=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,sh=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,ih=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,ah=new Set([22,4096,parseInt($e.KORTIX_MASTER,10)]);function fC(e){return sh.test(e)}function Uo(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 yC(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var hC=new Set(["'",'"',"`","<","(","["]),bC=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function _C(e){let t=0,n=e.length;for(;t<n&&(e[t]===" "||e[t]===" ");)t++;for(;n>t&&(e[n-1]===" "||e[n-1]===" ");)n--;for(;t<n&&hC.has(e[t]);)t++;for(;n>t&&bC.has(e[n-1]);)n--;return e.slice(t,n)}function PC(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var xC=/^\/proxy\/(\d{1,5})(\/.*)?$/,SC=/^\/(connectors|settings|dashboard|projects|agents|skills|tools|commands|support|changelog|files|p|browser|desktop|terminal|sessions|services|workspace|channels|scheduled-tasks|marketplace|templates|tunnel|admin|auth)(\/|$|\?)/;function ch(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:SC.test(t.pathname)}catch{return!1}}function er(e){if(!e)return null;let t=_C(yC(e.trim())),n=Rg(t);if(n){let r=Uo(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($e.KORTIX_MASTER,10);if(o===i){let c=r.pathname.match(xC);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return o=p,s=Uo(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${o}${s}`,port:o,path:s}}}let a=Uo(s);return{originalUrl:`${r.protocol}//${r.hostname}:${o}${a}`,port:o,path:a}}catch{let r=PC(e);return r&&r!==e?er(r):null}}function wC(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 AC(e,t){return t.some(([n,r])=>e>=n&&e<r)}function lh(e){let t=[],n=new Set,r=wC(e);oh.lastIndex=0;let o;for(;(o=oh.exec(e))!==null;){let s=er(o[0]);if(!s)continue;let{originalUrl:i,port:a,path:c}=s;a<1||a>65535||ah.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:AC(o.index,r)}))}return t}function vC(e){return lh(e).length>0}function kC(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function uh(e){return e.trim().toLowerCase().split("_").join("-")}function ph(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function RC(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(uh(n.sandboxId));return`${ph(o)}${t}`}function dh(e){return e.sandboxId.trim().length>0}function tt(e,t,n){let r=Uo(t);if(!dh(n))return yh(e,r);let o=RC(e,r,n);return o||(kC(n.apiBaseUrl)?`http://p${e}-${uh(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${ph(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function CC(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(o=>encodeURIComponent(o)).join("/");return tt(3211,`/open?path=/workspace/${r}`,t)}function gh(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function IC(e){return`http://localhost:3211${gh(e)}`}function mh(){return"/health"}function TC(e){return tt(3211,mh(),e)}function EC(e,t){return tt(e,"/",t)}function fh(e){let t=er(e);return!(!t||ah.has(t.port)||ch(e))}function kg(e,t){if(!e)return e;let n=er(e);return n?fh(n.originalUrl)?tt(n.port,n.path,t):n.originalUrl:e}function yh(e,t="/"){return`http://localhost:${e}${t}`}var hh=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function Rg(e){let t=e.match(sh);if(t)return{port:parseInt(t[1],10),sandboxId:t[2],backendPort:t[3]?parseInt(t[3],10):80,path:t[4]||"/"};let n=e.match(ih);if(n){let 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(hh);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 MC(e){try{let t=Rg(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function OC(e){return fC(e)||ih.test(e)||hh.test(e)}function DC(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Zn="/web-proxy/";function jC(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),o=`${Zn}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,s=parseInt($e.KORTIX_MASTER,10);return`${tt(s,"/",t).replace(/\/$/,"")}${o}`}catch{return null}}function $C(e){try{let t=new URL(e),n=t.pathname.indexOf(Zn);if(n===-1)return null;let o=t.pathname.slice(n+Zn.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 UC(e){try{return new URL(e).pathname.includes(Zn)}catch{return e.includes(Zn)}}function LC(e){if(!e)return!1;let t=e.trim();return!!(/^https?:\/\/(?!localhost|127\.0\.0\.1)/i.test(t)||/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t))}function FC(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t)?`https://${t}`:null:null}function bh(e){return{health:t=>vg(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>tt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>kg(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ge(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Cg(e,t,n,r){let o,s,{persistedPromptDefaults:i,clearPersistedDefaults:a}=uy(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=fy(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return o},set model(f){o=f},get agent(){return s},set agent(f){s=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...th(m),...nh(m),...bh(m),...Py(m),...Ry(m),...Ny(m),files:eh(c),..._y(m),get runtime(){return Se(d("runtime").runtimeUrl)}}}function _h(e){return{apps:{list:()=>Xp(e),create:t=>Jp(e,t),get:t=>io(e,t),update:(...t)=>Zp(e,...t),access:{get:(...t)=>rd(e,...t),update:(...t)=>sd(e,...t),session:(...t)=>id(e,...t),agents:t=>od(e,t)},remove:t=>ed(e,t),token:t=>td(e,t),authEnv:t=>nd(e,t),artifacts:{register:t=>ao(e,t),uploadArchive:(...t)=>ad(e,...t),finalize:(...t)=>co(e,...t)},deployments:{create:(...t)=>cd(e,...t),list:t=>ld(e,t),get:(...t)=>ud(e,...t),logs:(...t)=>pd(e,...t),remove:(...t)=>md(e,...t)},start:t=>dd(e,t),stop:t=>gd(e,t),rollback:(...t)=>fd(e,...t),machines:{list:t=>yd(e,t),start:(t,n)=>bd(e,t,n),stop:(t,n)=>_d(e,t,n),restart:(t,n)=>Pd(e,t,n),destroy:(t,n)=>xd(e,t,n)},scale:(t,n)=>Sd(e,t,n),exec:(...t)=>wd(e,...t),volumes:{list:t=>Ad(e,t),create:(...t)=>vd(e,...t),update:(...t)=>kd(e,...t),destroy:(...t)=>Rd(e,...t),snapshots:(...t)=>Cd(e,...t),snapshot:(...t)=>Id(e,...t),restore:(...t)=>Td(e,...t),fork:(...t)=>Ed(e,...t)}}}}function Ph(e){return{list:()=>Mi(e),invite:(...t)=>ji(e,...t),update:(...t)=>Oi(e,...t),revoke:t=>Di(e,t),pendingInvites:()=>$i(e),resendInvite:(...t)=>Li(e,...t),revokeInvite:(...t)=>Ui(e,...t),requests:()=>Ii(e),approveRequest:(...t)=>Ti(e,...t),rejectRequest:(...t)=>Ei(e,...t),groupGrants:()=>Fi(e),attachGroupGrant:(...t)=>Ni(e,...t),updateGroupGrant:(...t)=>Ki(e,...t),detachGroupGrant:t=>qi(e,t),resourceGrants:{list:()=>Bi(e),create:t=>Gi(e,t),remove:t=>Wi(e,t)}}}function xh(e){return{tokens:{list:()=>Tp(e),create:t=>Ep(e,t),revoke:t=>Mp(e,t)},setupLinks:{requestSecret:t=>Kp(e,t),requestConnector:t=>qp(e,t)},validateManifest:t=>ii(e,t),gitToken:()=>ai(e),agentIdentities:()=>Gu(e),secrets:{list:()=>Yi(e),upsert:t=>Qi(e,t),setStrategy:(...t)=>Xi(e,...t),broker:(...t)=>Ji(e,...t),remove:t=>na(e,t),setPersonal:(...t)=>ra(e,...t),removePersonal:t=>oa(e,t),setGitCredential:t=>ta(e,t),listProviderOAuth:()=>Zi(e),startProviderOAuth:(...t)=>Dr(e,...t),pollProviderOAuth:(...t)=>jr(e,...t),removeProviderOAuth:t=>ea(e,t)},access:Ph(e)}}function Sh(e){return{list:()=>ba(e),listAll:()=>_a(e),reconcile:(...t)=>Pa(e,...t),reconcileMember:(...t)=>xa(e,...t),updateCredential:(...t)=>Sa(e,...t),revoke:(...t)=>wa(e,...t),activate:(...t)=>Aa(e,...t),setDefault:(...t)=>va(e,...t),rename:(...t)=>ka(e,...t),share:(...t)=>Ca(e,...t),addComputer:(...t)=>Ra(e,...t),pipedreamConnect:(...t)=>Ia(e,...t),pipedreamFinalize:(...t)=>Ta(e,...t)}}function Lo(e){return{catalog:t=>Tt(e,t),tools:()=>Fr(e),search:(...t)=>ha(e,...t),describe:(...t)=>Nr(e,...t),call:(...t)=>pt(e,...t),callAction:(t,n,r,o)=>pt(e,`${t}.${n}`,r,o),accounts:(...t)=>Kr(e,...t),uploadAttachment:(...t)=>qr(e,...t)}}function Ig(e,t){return{slug:t,run:(r,o,s)=>Vr(e,t,r,o,s),call:(r,o,s)=>pt(e,`${t}.${r}`,o,s),describe:async r=>r!==void 0?Nr(e,`${t}.${r}`):(await Tt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(s=>s.slug===t)??null,accounts:()=>Kr(e,t),paginate:(r,o,s)=>Xa(e,t,r,o,s),uploadAttachment:(r,o)=>qr(e,r,{...o,connector:t})}}var NC=100,KC=0,qC=new Set(["attachment_size_mismatch","attachment_failed"]),wh=()=>new h("Attachment expired. Attach the file again.",{code:"attachment_expired"});function Ah(e){if(!e||typeof e.attachment_id!="string"||!e.attachment_id||typeof e.filename!="string"||!e.filename||typeof e.mime!="string"||!e.mime||!Number.isSafeInteger(e.size)||e.size<=0||e.size>52428800||!Number.isFinite(Date.parse(e.expires_at))||Date.parse(e.expires_at)<=Date.now())throw new Error("Attachment metadata is invalid or expired. Attach the file again.");return{attachment_id:e.attachment_id,filename:e.filename,mime:e.mime,size:e.size,expires_at:e.expires_at}}function Tg(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,_){y.removalDeleted||(y.removalDeleted=!0,Et(e,_).catch(()=>{}))}function m(){c&&clearTimeout(c);let y=d().map(({item:w})=>w);(y.length!==p.attachments.length||y.some((w,D)=>w!==p.attachments[D]))&&(p={attachments:y});let _=Math.min(...y.filter(w=>w.status==="ready").map(w=>Date.parse(w.attachment.expires_at)));Number.isFinite(_)&&!a&&(c=setTimeout(()=>{for(let w of d())w.item.status==="ready"&&Date.parse(w.item.attachment.expires_at)<=Date.now()&&(w.item={...w.item,status:"error",error:wh()});m()},Math.min(2147483647,Math.max(0,_-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let w of o)w();for(let w of[...s])w()}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 b(y){f();let _=d();if(_.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(D=>!Number.isSafeInteger(D)||D<=0||D>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(_.reduce((D,T)=>D+T.item.size,0)+y.reduce((D,T)=>D+T,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function P(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let _=y.item.file;i++;let w=++y.generation,D=new AbortController;y.abort=D,y.item={...y.item,status:"uploading",error:void 0};let T=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===w,x,S=0,I,C=()=>{I=void 0,!(!T()||y.item.status!=="uploading"||x===void 0)&&(y.item={...y.item,receivedBytes:x},x=void 0,S=Date.now(),m())},F=M=>Math.floor(M*100/y.item.size);An(e,_,{resume:y.upload,signal:D.signal,onUpload:M=>{y.upload=M,y.removed&&(D.abort(),g(y,M.attachment_id))},onProgress:M=>{if(!T()||F(M)===F(y.item.receivedBytes)||(x=M,I))return;let K=S+NC-Date.now();if(K<=0)return C();I=setTimeout(C,K),typeof I=="object"&&"unref"in I&&I.unref()},onProcessing:()=>{I&&clearTimeout(I),I=void 0,x=void 0,T()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then(M=>{T()&&(y.item={...y.item,status:"ready",attachment:Ah(M),receivedBytes:M.size})}).catch(M=>{M instanceof h&&qC.has(M.code??"")&&(y.upload=void 0),T()&&(y.item={...y.item,status:M instanceof h&&M.code==="ABORTED"?"aborted":"error",error:M instanceof Error?M:new Error(String(M))})}).finally(()=>{i--,I&&clearTimeout(I),y.abort===D&&(y.abort=void 0),m(),P()})}m()}function j(y){b(y.map(w=>w.size));let _=y.map(w=>{let D=`attachment-${++KC}`;return r.set(D,{generation:0,item:{id:D,file:w,filename:w.name,mime:w.type||"application/octet-stream",size:w.size,status:"pending",receivedBytes:0}}),D});return m(),P(),_}function L(y){let _=r.get(y);!_||_.item.status==="ready"||(_.generation++,_.abort?.abort(),_.item={..._.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function N(y,{signal:_}={}){let w=[...y];return new Promise((D,T)=>{let x=()=>{s.delete(C),_?.removeEventListener("abort",I)},S=F=>{x(),T(F)},I=()=>S(he()),C=()=>{let F=!1;for(let K of w){let q=r.get(K);if(!q)return S(new Error("Attachment was removed before it was sent"));if(a&&!q.handedOff)return S(new Error("Attachment controller is disposed"));if(q.item.status==="error"||q.item.status==="aborted")return S(q.item.error??new Error("Attachment upload failed"));q.item.status!=="ready"&&(F=!0)}if(F)return;let M;try{M=w.map(K=>{let q=Ah(r.get(K).item.attachment);return{type:"file",attachment_id:q.attachment_id,filename:q.filename,mime:q.mime}})}catch(K){return S(K instanceof Error?K:new Error(String(K)))}x(),D(M)};if(_?.aborted)return I();s.add(C),_?.addEventListener("abort",I,{once:!0}),C()})}return{add:y=>j([y])[0],addMany:j,retry(y){let _=r.get(y);if(_?.handedOff||f(),!(!_||_.item.status==="ready"||_.item.status==="uploading"||_.item.status==="processing"||_.item.status==="pending")){if(!_.item.file||_.upload&&Date.parse(_.upload.expires_at)<=Date.now())throw wh();_.item={..._.item,status:"pending",error:void 0},P()}},async remove(y){let _=r.get(y);if(!_)return;_.removed=!0,_.generation++,r.delete(y);let w=_.upload?.attachment_id??_.item.attachment?.attachment_id;w&&_.abort?.abort(),m(),P(),w&&g(_,w)},abort:L,submit(y){if(!a){for(let _ of y){let w=r.get(_);w&&(w.handedOff=!0)}m()}},reclaim(y){if(!a){for(let _ of y){let w=r.get(_);w&&(w.handedOff=!1)}m()}},whenReady:N,forget(y=d().map(_=>_.item.id)){for(let _ of y){let w=r.get(_);w&&(w.generation++,w.abort?.abort(),r.delete(_))}m(),P()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let _=y.upload?.attachment_id??y.item.attachment?.attachment_id;_&&e&&Et(e,_).catch(()=>{})}o.clear(),m()}},getSnapshot:()=>p,subscribe(y){return o.add(y),()=>{o.delete(y)}}}}function vh(e){return{attachments:{upload:(...t)=>An(e,...t),delete:(...t)=>Et(e,...t),createController:t=>Tg(e,t)},get:t=>gn(e,t),detail:()=>mn(e),skills:{create:(...t)=>fi(e,...t)},audit:t=>jp(e,t),update:t=>hn(e,t),archive:()=>bn(e),llmCatalog:()=>fn(e),modelPicker:()=>yn(e),modelAccess:()=>Dn(e),setModelAccess:t=>jn(e,t),sandboxHealth:()=>Pn(e),onboardingComplete:(...t)=>mi(e,...t)}}function kh(e){return{sessions:{list:t=>gt(e,t),listPage:t=>Lc(e,t),create:t=>mt(e,t),ensureWarm:()=>Vc(e),claimWarm:t=>zc(e,t)},review:{list:t=>lp(e,t),get:t=>up(e,t),submit:t=>pp(e,t),act:(...t)=>dp(e,...t),bulkAct:t=>gp(e,t)},approvals:{list:t=>Hi(e,t),resolve:(...t)=>zi(e,...t),sessionsNeedingInput:t=>Vi(e,t)}}}function Rh(e){return{files:{list:t=>lc(e,t),listDirectory:t=>uc(e,t),read:(t,n)=>dc(e,t,n),search:(...t)=>pc(e,...t),archive:(...t)=>gc(e,...t),archiveRequest:(...t)=>mc(e,...t),history:(...t)=>xc(e,...t)},git:{commits:()=>bc(e),commit:t=>_c(e,t),commitDiff:t=>Pc(e,t),branches:()=>hc(e),versionDiff:(...t)=>Sc(e,...t),inviteCollaborator:(...t)=>si(e,...t)},changeRequests:{list:()=>wc(e),get:t=>Ac(e,t),update:(...t)=>Oc(e,...t),diff:t=>vc(e,t),mergePreview:t=>kc(e,t),open:(...t)=>Rc(e,...t),merge:(...t)=>Cc(e,...t),close:(...t)=>Ic(e,...t),reopen:(...t)=>Tc(e,...t),requestChanges:(...t)=>Ec(e,...t)},...kh(e)}}function Ch(e){return{policies:{list:()=>Ja(e),set:(...t)=>Za(e,...t)},reminders:{list:()=>Ap(e),updateMany:(...t)=>Sp(e,...t),removeMany:(...t)=>wp(e,...t)},triggers:{list:()=>yl(e),eventApps:()=>wl(e),eventTypes:(...t)=>Sl(e,...t),create:(...t)=>hl(e,...t),update:(...t)=>bl(e,...t),remove:(...t)=>_l(e,...t),fire:(...t)=>xl(e,...t),setActivation:(...t)=>Pl(e,...t)},...Rh(e)}}function Ih(e,t){return{connectors:{...Lo(e),list:()=>Ea(e),config:(...n)=>La(e,...n),create:(...n)=>Ka(e,...n),remove:(...n)=>Ba(e,...n),sync:()=>Ma(e),auth:{discover:(...n)=>qa(e,...n)},setName:(...n)=>Fa(e,...n),setCredentialMode:(...n)=>Oa(e,...n),setAuthorizationStrategy:(...n)=>Da(e,...n),setCredential:(...n)=>za(e,...n),deleteCredential:(...n)=>Ya(e,...n),setSensitive:(...n)=>ja(e,...n),connections:t,policies:{get:(...n)=>$a(e,...n),set:(...n)=>Ua(e,...n)},pipedream:{listApps:(...n)=>Ga(e,...n),listSections:(...n)=>Wa(e,...n),connect:(...n)=>Na(e,...n),finalize:(...n)=>Qa(e,...n)},discover:{list:(...n)=>Br(e,...n),sections:(...n)=>Ha(e,...n),detail:(...n)=>Gr(e,...n)}},...Ch(e)}}function Th(e){return{gateway:{logs:t=>Pu(e,t),log:t=>xu(e,t),overview:t=>Su(e,t),series:t=>wu(e,t),breakdown:t=>Au(e,t),sessions:t=>vu(e,t),errors:t=>ku(e,t),budgets:()=>Ru(e),setBudget:t=>Cu(e,t),deleteBudget:t=>Iu(e,t),keys:()=>Tu(e),createKey:t=>Eu(e,t),revokeKey:t=>Mu(e,t),routing:{get:()=>yu(e),set:t=>hu(e,t),reset:()=>bu(e),preview:t=>_u(e,t)},playground:(t,n,r)=>Ou(e,t,n,r)}}}function Eh(e){return{modelDefaults:{get:()=>kl(e),set:t=>Rl(e,t),clear:t=>Cl(e,t)},setDefaultAgent:t=>El(e,t),sandbox:{list:()=>cc(e),snapshots:()=>tc(e),rebuildSnapshot:t=>nc(e,t),fixWithAgent:()=>rc(e),createTemplate:t=>oc(e,t),updateTemplate:(...t)=>sc(e,...t),removeTemplate:t=>ic(e,t),buildTemplate:t=>ac(e,t),setProvider:t=>gi(e,t)},setAgentScope:(...t)=>Il(e,...t)}}function Mh(e){return{channels:{slack:{installation:()=>tu(e),connect:t=>nu(e,t),mode:()=>ru(e),completeInstall:t=>ou(e,t),manifest:()=>iu(e),disconnect:()=>au(e),getFile:t=>cu(e,t),uploadFile:t=>lu(e,t)},teams:{completeInstall:t=>su(e,t)},email:{installation:t=>pu(e,t),mode:()=>du(e),connect:t=>gu(e,t),disconnect:t=>mu(e,t),updatePolicy:(...t)=>fu(e,...t)}},updateFeatureFlag:(...t)=>pi(e,...t),updateExperimentalFeature:(...t)=>di(e,...t),...Eh(e)}}async function Eg(e){let t=e?.fetch??v().fetch??((o,s)=>fetch(o,s)),n=e?.backendUrl??v().backendUrl,r=await t(`${ft(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new h(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var BC=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function GC(e,t){let n=s=>{let i=BC.exec(s.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),o=n(t);if(!r||!o)return null;for(let s=0;s<3;s++)if(r[s]!==o[s])return r[s]<o[s]?-1:1;return 0}function WC(){return Je()}var Oh=null,Dh=!1;function HC(e){let t=Oh;Oh=e,!(Dh||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(Dh=!0,console.warn("[kortix] createKortix() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedKortix() from @kortix/sdk/server.")))}function jh(e,t){t?.global!==!1&&HC(e),Sr(e,t);let n=ly(e),{auth:r,accounts:o,iam:s,accountInvites:i}=oy(),{billing:a,sandboxShares:c}=ty(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=ey();function b(P){let j=Sh(P);return{...vh(P),..._h(P),...xh(P),...Ih(P,j),...Th(P),...Mh(P),connector:L=>Ig(P,L),session:L=>Cg(P,L,e,n)}}return{config:e,auth:r,accounts:o,iam:s,accountInvites:i,projects:p,connectors:Lo(),connector:P=>Ig(void 0,P),project:b,session:(P,j)=>Cg(P,j,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,notifications:{registerDeviceToken:Od,unregisterDeviceToken:Dd,list:jd,markRead:$d,preferences:Ud,updatePreferences:Ld,webPushPublicKey:Fd,registerWebPushSubscription:Nd,unregisterWebPushSubscription:Kd},mobileClientPolicy:Eg,validateToken:ri,runtime:WC}}function $h(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);if(e?.getRandomValues)e.getRandomValues(t);else for(let r=0;r<16;r++)t[r]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;let n=[...t].map(r=>r.toString(16).padStart(2,"0"));return`${n[0]}${n[1]}${n[2]}${n[3]}-${n[4]}${n[5]}-${n[6]}${n[7]}-${n[8]}${n[9]}-${n.slice(10).join("")}`}function Uh(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Jt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function Lh(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function Fh(e){if(Jt(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 Nh(e){let t=Jt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function Kh(e,t){let n=Jt(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 qh(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 Bh(e,t){return Jt(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 Gh(e,t,n){return Jt(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 Wh(e,t,n){let r=Jt(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 Mg={thinking:!1,toolDetails:!0,assistantMetadata:!0};function VC(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function zC(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 YC(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
22
22
|
|
|
23
23
|
`;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
|
|
24
24
|
>
|
|
@@ -51,15 +51,15 @@ ${o}
|
|
|
51
51
|
${e.state.error}
|
|
52
52
|
\`\`\`
|
|
53
53
|
`),n+=`
|
|
54
|
-
`,n}return""}function
|
|
54
|
+
`,n}return""}function QC(e,t){if(!t)return`## Assistant
|
|
55
55
|
|
|
56
|
-
`;let n=e.agent?
|
|
56
|
+
`;let n=e.agent?VC(e.agent):"Assistant",r=e.modelID||"",o="";e.time?.completed&&e.time?.created&&(o=zC(e.time.completed-e.time.created));let s=[r,o].filter(Boolean).join(" \xB7 ");return s?`## ${n} (${s})
|
|
57
57
|
|
|
58
58
|
`:`## ${n}
|
|
59
59
|
|
|
60
|
-
`}function
|
|
60
|
+
`}function XC(e,t,n){let r="";e.role==="user"?r+=`## User
|
|
61
61
|
|
|
62
|
-
`:r+=
|
|
62
|
+
`:r+=QC(e,n.assistantMetadata);for(let o of t)r+=YC(o,n);return r}function Hh(e,t,n=Mg){let r=`# ${e.title||"Untitled Session"}
|
|
63
63
|
|
|
64
64
|
`;r+=`**Session ID:** \`${e.id}\`
|
|
65
65
|
`,r+=`**Created:** ${new Date(e.time.created).toLocaleString()}
|
|
@@ -67,30 +67,30 @@ ${e.state.error}
|
|
|
67
67
|
|
|
68
68
|
`,r+=`---
|
|
69
69
|
|
|
70
|
-
`;for(let o of t)r+=
|
|
70
|
+
`;for(let o of t)r+=XC(o.info,o.parts,n),r+=`---
|
|
71
71
|
|
|
72
|
-
`;return r}function
|
|
72
|
+
`;return r}function Vh(e,t){return`session-${e}.md`}var Og="An error occurred";var JC=["message","error","detail","error_description","msg","errors","data"];function Dg(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 Zt(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function ZC(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=Zt(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function eI(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=tI(e,t);if(n)return n;let r=rI(e,t);return r?r.slice(0,200):void 0}function Xh(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function zh(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function tI(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let o=r+6;if(!Xh(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 nI=["script","style"];function rI(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=nI.find(i=>t.startsWith(`<${i}`,o)&&Xh(t.charCodeAt(o+i.length+1)));if(s){let i=t.indexOf(`</${s}`,o);r=i===-1?e.length:zh(e,i);continue}r=zh(e,o)}return n.join(" ").replace(/\s+/g," ").trim()}function oI(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 sI(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function Yh(e,t,n){if(typeof e=="string")return Fo(e,t,n);if(e&&typeof e=="object")return No(e,t,n)}function Fo(e,t,n=new WeakSet){let r=Dg(e);if(!r)return;if(t>=4)return r;let o=oI(r);if(o)return o;let s=Zt(r);if(s!==void 0)return typeof s=="string"?Fo(s,t+1,n):s&&typeof s=="object"?No(s,t+1,n):String(s);let i=Jh(r);if(i){let a=Zt(i);if(a&&typeof a=="object"){let c=No(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=ZC(r);if(a)return Fo(a,t+1,n)??a}return eI(r)??r}function No(e,t,n=new WeakSet){if(t>=4||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let i of e){let a=Yh(i,t,n);if(a)return a}return}let r=e;for(let i of JC){let a=Yh(r[i],t,n);if(a)return a}let o=r.type??r.code;if(typeof o=="string"&&o.trim())return sI(o);let s=r.status??r.statusCode??r.upstream_status;if(typeof s=="number"&&Number.isFinite(s))return`Request failed with status ${s}`}function fe(e){return e?typeof e=="string"?Fo(e,0)??Og:typeof e=="object"?No(e,0)??Og:String(e):Og}function jg(e){let t=iI(e)?.trim();if(!t)return;let n=fe(e);if(!(t===n||Dg(t)===n))return t}function iI(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
|
|
75
|
-
`||e==="\r"||e==="\u2028"||e==="\u2029"}function
|
|
74
|
+
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function Jh(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function aI(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(typeof t.message=="string"&&t.message)return t.message;if(typeof t.error=="string"&&t.error)return t.error;let n=t.data;if(typeof n?.message=="string")return n.message;let r=t.error;if(typeof r?.message=="string")return r.message}function cI(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 Qh(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=cI(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||aI(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:o,requestId:s,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function ye(e){if(e==null)return;if(typeof e=="string"){let a=Dg(e),c=Zt(a)??Zt(Jh(a));return c!==void 0?ye(c):void 0}if(typeof e!="object")return;let t=e,n=Qh(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let o=t.error;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Qh(o);if(a)return a}let s=t.data;if(s&&typeof s.responseBody=="string"){let a=Zt(s.responseBody);if(a!==void 0){let c=ye(a);if(c)return c}}if(s&&typeof s.message=="string"){let a=ye(s.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let c=ye(a);if(c)return c}}return n}var Zh={};function V(e,t){for(let n of t)Zh[n]=e}V("read",["read"]);V("list",["list","ls"]);V("glob",["glob"]);V("grep",["grep"]);V("write",["write"]);V("edit",["edit","multiedit","morph_edit"]);V("apply_patch",["apply_patch","patch"]);V("bash",["bash"]);V("web_search",["web_search","websearch","image_search"]);V("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);V("media",["image_gen","video_gen"]);V("show",["show","show_user","presentation_gen"]);V("task",["task"]);V("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"]);V("todowrite",["todowrite","todo_write","todoread"]);V("question",["question","ask"]);V("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);V("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"]);V("automations",["triggers"]);V("skill",["skill"]);V("context",["prune","distill","compress","context_info"]);V("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var lI=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function se(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=Zh[t];if(n)return n;for(let[r,o]of lI)if(t.startsWith(r))return o;return"other"}function Ne(e){for(let t of[e?.filePath,e?.file_path,e?.path])if(typeof t=="string"&&t)return t}var uI=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function pI(){return new RegExp(`(^|\\s)([-+]?)(${uI.join("|")}):("[^"]*"|\\S+)`,"gi")}function dI(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function gI(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function mI(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function fI(e){return mI(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function eb(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function tr(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(pI(),(o,s,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=fI(c);p&&!n.includes(p)&&n.push(p)}return s});return r=r.replace(dI(),"$1").replace(gI(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${eb(n)}`:r:n.length>0?eb(n):t}var yI=/\s/,hI=/\w/;function le(e){return e!==void 0&&yI.test(e)}function nr(e){return e===`
|
|
75
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function $g(e){return e!==void 0&&hI.test(e)}function St(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(bI(n.charCodeAt(0))):n;return t}function bI(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 Ke(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function tb(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Ke(e.slice(t))}function rr(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 Ug(e,t){let n=rr(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 Ig(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 Mh(e,t){let n=Ig(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function Oh(e,t){let n=Ig(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 Dh(e,t){let n=`</${t}>`,r="",o=0;for(;;){let s=Ig(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 jh(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 Yn(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 $h(e,t,n){let r=mt(t),o=mt(n);for(let s of mt(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 Uh(e,t){let n=mt(e),r=t.map(mt),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(Vn(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&&!Vn(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(!Vn(e[m]))return e[m];return null}}a=i(c)}return null}function Fh(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++;kg(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]+(Vn(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&&kg(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(!Vn(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function Lh(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||!kg(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 Nh(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 Kh(e){return Nh(e,!0)}function qh(e){return Nh(e,!1)}function UI(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Gh(e,t){let n=mt(e),r=mt(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(UI(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var Bh=new Set(["read","glob","grep","list"]);function V(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function FI(e){return Bh.has(te(e))}function LI(e){let t=0,n=0,r=0;for(let o of e){let s=te(o.tool);s==="read"?t++:s==="glob"||s==="grep"?n++:s==="list"&&r++}return{read:t,search:n,list:r}}function Cg(e){if(!e)return"";let t=je(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Mo(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Oo(e){let n=(e.state??{}).input??{};switch(V(e.tool)){case"read":case"edit":case"write":case"morph_edit":{let s=n.filePath??n.file_path??n.path;return s?Cg(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?`"${Mo(String(s),40)}" in ${Cg(String(i))}`:s?`"${Mo(String(s),60)}"`:""}case"list":return n.path?Cg(String(n.path)):"";case"bash":return Mo(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 Mo(s==="query"&&Hn(i)||i,60)}return""}var Wh={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 NI(e,t={}){let n={...Wh,...t},r=V(e.tool),o=Oo(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 _e(e){return e.type==="text"}function Pe(e){return e.type==="reasoning"}function J(e){return e.type==="tool"}function Eg(e){return e.type==="file"}function KI(e){return e.type==="agent"}function qI(e){return e.type==="compaction"}function GI(e){return e.type==="snapshot"}function BI(e){return e.type==="patch"}function WI(e){return e.type==="step-start"||e.type==="step-finish"}function HI(e){if(_e(e)||Pe(e))return e.text}function VI(e){if(!Eg(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function zI(e){let t=[],n=[];for(let r of e)Eg(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function YI(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function QI(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var XI=new Set(["todoread","context_info"]);function Hh(e){return!XI.has(e.tool)}var JI=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 Mg(e){let t=e.tool||"";if(t.startsWith("oc-"))return;let n=te(t);if(n==="task"||n==="delegate"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r;if(n==="task"&&e.state?.status==="error")return e.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return ZI(t,e.state)}function ZI(e,t){let n=V(e);if(JI.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 eC(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return pe(n.error)}}function tC(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)J(r)&&Hh(r)&&t.push(r);return t}function nC(e,t={}){switch(V(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:Yh(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 rC(e,t)}}function rC(e,t){switch(te(e)){case"read":return{icon:"glasses",title:"Read",subtitle:Vh(De(t))};case"list":return{icon:"list",title:"List",subtitle:zh(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:Tg(De(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Tg(De(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function Vh(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Tg(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 zh(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function oC(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 Qn(e,t=120){if(typeof e!="string")return"";let n=e.split(`
|
|
78
|
-
`).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function
|
|
79
|
-
`))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function
|
|
80
|
-
|
|
81
|
-
`)}var ab=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),tT={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 nT(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Hn(t)||t}function rT(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 nT(r,o.trim())}}function Kg(e){if(Pe(e))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!J(e))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let t=ue(e.tool),n=tT[t],r=e.state?.input;return n?{verb:n.verb,running:n.running,object:rT(r,n.objectKeys),tier:ab.has(t)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:t,tier:"primary"}}function oT(e){let t=0,n=0,r=!1,o=!1;for(let s of e){if(Kg(s).tier==="plumbing"){r=!0;continue}if(Pe(s)){if(!s.text?.trim())continue;o||(o=!0,t+=1);continue}o=!1,t+=1,J(s)&&Ng(s)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function qg(e){return`${e} ${e===1?"step":"steps"}`}function sT(e,t){let{total:n,failed:r,completed:o,hasPlumbing:s}=e;return t?n===0?"Working":`Working \xB7 ${qg(n)}`:n===0?s?"Housekeeping":"Worked":r===0?`Completed ${qg(n)}`:o===0?`${qg(n)} failed`:`Completed ${o} of ${n} steps \xB7 ${r} failed`}function iT(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 aT(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function cT(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 lT(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=Kh(n),n=qh(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 uT(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=Yn(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 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,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(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 cb(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 No(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 Gg(e){if(!e)return[];let t=cb(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)?No(o.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=No(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)?No(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=No(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 Ko(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function pT(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Ko(e)}}function dT(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function gT(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 lb(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 ub(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let o=Gh(n,r)?.trim()||n;return{url:r,success:!1,error:o}})}function mT(e,t){let n=pb(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?ub(r,lb(t)):[]}function pb(e){if(!e)return null;let t=cb(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 fT(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 yT={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 qo(e){return yT[te(e)]}function er(e){let t=V(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var hT={run:"Terminal",memory:"Memory"};function bT(e){let t=qo(e);return(t==="hidden"?void 0:hT[t])??er(e)}function Zn(e,t,n){return e===1?t:n}function Bg(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 mb(e){return e.length?Oo(e[0]):""}function xe(e){return(e.state??{}).input??{}}var _T={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 PT(e){let t=V(e.tool);if(t==="agent_task_update"||t==="task_update")switch(xe(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return _T[t]??"message"}function db(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 xT(e){let t=V(e.tool);if(t==="triggers"){let r=xe(e).action||"list";return db(r)}let n=t.match(/^trigger_(.+)$/);return db(n?n[1]:"list")}var ST={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 wT(e){return ST[V(e.tool)]??"read"}var vT={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function AT(e){return vT[V(e.tool)]??"open"}function Ht(e){return e.every(t=>t===e[0])}var kT={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function RT(e){if(V(e.tool)!=="memory")return"read";let n=xe(e).command;return n&&kT[n]||"unknown"}var IT={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},CT={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 TT(e){let t=je(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function ET(e){let t=xe(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 MT(r,60);let o=typeof t.path=="string"?t.path:"";if(o)return TT(o);let s=typeof t.url=="string"?t.url:"";if(s){let i=fT(s);return i?Ko(i):"a link"}return""}function MT(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function OT(e){let t=xe(e).action;return t&&IT[t]||"Worked on an image"}function DT(e){let t=xe(e).action;return t&&CT[t]||"Worked on a presentation"}function jT(e){return e.slice(0,e.indexOf(":"))}var $T={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},UT={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 FT(e){let t=V(e.tool);if(t==="image_gen"){let n=xe(e).action;return n&&$T[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=xe(e).action;return n&&UT[n]||"presentation:unknown"}return"shown:result"}var LT=new Set(["create_slide","export_pdf","export_pptx"]);function NT(e){let t=V(e.tool);if(t==="image_gen")return"image";if(t==="video_gen")return"video";if(t==="presentation_gen"){let n=xe(e).action;return n?LT.has(n)?"presentation":null:"presentation"}return null}var KT={"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`},gb={image:"image",video:"video",presentation:"presentation",shown:"result"};function qT(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[jT(r)]++;let n=[];return Object.keys(t).forEach(r=>{let o=t[r];o&&n.push(`${o} ${Zn(o,gb[r],`${gb[r]}s`)}`)}),`Worked on ${Bg(n)}`}function Wg(e,t){let n=t.length,r=mb(t);switch(e){case"explore":{let o=t.filter(s=>V(s.tool)==="read").length;return o===n?`Read ${n} ${Zn(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=>De(xe(i))).filter(Boolean)).size||n,s=t.every(i=>V(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=V(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} ${Zn(n,"query","queries")}`;if(s===0)return`Read ${n} ${Zn(n,"page","pages")}`;let i=new Set;for(let c of t)if(o(c)){let p=c.state?.output;for(let d of Gg(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} ${Zn(a,"source","sources")}`}case"create":{if(n===1){let s=t[0],i=V(s.tool);if(i==="image_gen")return OT(s);if(i==="video_gen")return"Made a video";if(i==="presentation_gen")return DT(s);let a=ET(s);return a?`Showed you ${a}`:"Showed you the result"}let o=t.map(FT);return Ht(o)?KT[o[0]](n):qT(o)}case"plan":return n===1?"Planned the work":`Planned the work \xB7 ${n} steps`;case"delegate":{let o=t.map(PT);if(Ht(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(RT);if(Ht(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(wT);if(Ht(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(xT);if(Ht(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(AT);if(Ht(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 ${er(t[0].tool)}`;let o=Array.from(new Set(t.map(s=>er(s.tool))));return o.length===1?`Used ${o[0]} \xB7 ${n} times`:`Used ${Bg(o)}`}}}function Hg(e,t){let n=mb(t);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(t.length===1){let r=V(t[0].tool)==="write"?"write":"update";return n?`Couldn't ${r} ${n}`:`Couldn't ${r} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let r=t.filter(i=>i.state?.status==="error"),o=r.length?r:t,s=Array.from(new Set(o.map(i=>er(i.tool))));return`Couldn't finish using ${Bg(s)}`}}}function GT(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function BT(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 fb(e,t){let n=GT(t);return{id:t[0].callID,family:e,label:n==="error"?Hg(e,t):Wg(e,t),parts:t,status:n,durationMs:n==="running"?void 0:BT(t)}}function Vg(e){let t=[],n=null,r=[],o=()=>{n&&r.length&&t.push(fb(n,r)),n=null,r=[]};for(let s of e){let i=qo(s.tool);if(i!=="hidden"&&!eo(s)){if(Dd(s.tool)){o(),t.push(fb(i,[s]));continue}i!==n&&(o(),n=i),r.push(s)}}return o(),t}function yb(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function WT(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 Vg(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(Pe(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=yb(a);continue}if(s(),J(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 HT=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function VT(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 zT(e){let t=e.flatMap(o=>{let s=VT(o);return s?[s]:[]}).join(" ").trim();return t?HT.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function xb(e){return e?.info?.time??{}}function YT(e){let t=xb(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Go=6e4,QT=10080*Go,hb=1440;function bb(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 XT(e,t){let n=t.getTime()-e.getTime(),r=n/Go,o=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return o(Math.round(r),"minute");if(r<hb)return o(Math.round(r/60),"hour");let s=(n-(bb(t)-bb(e)))/Go;return o(Math.round(s/hb),"day")}function Sb(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 _b=new Map;function JT(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,o=_b.get(r);return o||(o=new Intl.DateTimeFormat(t.locale,n),_b.set(r,o)),o}function Bo(e,t,n){return JT(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?ZT(r.value,n):r.value).join("")}function ZT(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function Pb(e,t){return Bo(e,{year:"numeric"},t)}function eE(e,t,n={}){let r=Sb(e);if(!r)return"";let o=i=>Bo(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<Go?"just now":s<QT?XT(r,new Date(t)):o(Pb(r,n)!==Pb(new Date(t),n))}function tE(e,t={}){let n=Sb(e);if(!n)return"";let r=Bo(n,{month:"long",day:"numeric",year:"numeric"},t),o=Bo(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${o}`}function nE(e,t={}){let n=[],r=[],o=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let s of e)if(!jd(s)){if(_e(s)){o(),n.push({kind:"text",part:s});continue}if(J(s)&&($d(s.tool)||!!t.standaloneCallIds?.has(s.callID))){o(),n.push({kind:"standalone",part:s});continue}r.push(s)}return o(),n}function rE(e){let t=ue(e);return t==="show"||t==="show_user"}function oE(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"&&rE(s.part.tool)&&!t.standaloneCallIds?.has(s.part.callID)){r.push(s);continue}o(),n.push(s)}return o(),n}var sE=["title","description","path","url","content","language","aspect_ratio","attachment"];function wb(e,t){if(!t||typeof t!="object")return null;let n=t;if(kn(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let o of sE){let s=n[o];typeof s=="string"&&s&&(r[o]=s)}return r}function iE(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 aE(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=iE(o.items),i=s?s.map(a=>wb(n.callID,a)).filter(a=>!!a):[wb(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 zg(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var cE=e=>e.time?.completed;function lE(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function uE(e,t){let n=e.userMessage.info.id;return t.pendingTurnIds.has(n)||e.assistantMessages.length===0&&t.pendingPromptIds.has(n)}function pE(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=>uE(r,e));return n<=0?null:e.turns[n-1].userMessage.info.id}function dE(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function gE(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function mE(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:zg({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function fE(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 yE(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(!cE(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 vb(e){let t=e.userMessage.parts;if(t.length===0||!t.every(s=>_e(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 J(o)&&o.tool==="bash"}function hE(e){if(vb(e))return e.assistantMessages[0].parts[0]}function bE(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 _E(e,t){return!t||!e?!1:e.type!=="idle"}function PE(e,t){return!e&&!!t}function xE(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ge(n.error)?.message||pe(n.error)}}function SE(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Ag(n.error)}}function wE(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ge(n.error)}}function Yg(e){if(e){if(J(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(Pe(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(_e(e))return"Gathering thoughts..."}}function vE(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,o=J(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=Yg(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let s=Yg(r);if(s)return s}return"Figuring out what\u2019s next..."}function AE(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 Qg=1.2;function Ab(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 Xg(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function kb(e,t,n,r){if(Xg(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?Ab(e.tokens,s):0}function Rb(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function kE(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}=Rb(d.info);n+=kb(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=Ib(g,t),f=g.tokens&&Xg(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*Qg,tokens:{input:r,output:o,reasoning:s,cacheRead:i,cacheWrite:a}}}function Ib(e,t){if(Xg(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?Ab({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function RE(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let o=r.info,{providerID:s,modelID:i}=Rb(o),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=kb(p,s,i,t));c||(a+=Ib(o,t)),n+=a}return n*Qg}function IE(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function CE(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function TE(e){if(!e||e.type!=="retry")return;let t=e,n=pe(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:ge(t.message)}}function EE(e){if(!(!e||e.type!=="retry"))return pe(e.message)}function ME(e){return(e.info.summary?.diffs?.length??0)>0}function OE(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=Dh(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 DE(e){return e?e.split(`
|
|
82
|
-
`).filter(n=>n.trim()).length<=3:!1}function
|
|
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
|
|
84
|
-
`).filter(r=>r.trim());for(let r of n){let o=
|
|
85
|
-
`),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1);if(
|
|
77
|
+
`)&&(n=n.slice(0,-1)),n)}function Lg(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 nb(e,t){let n=Lg(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function rb(e,t){let n=Lg(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 ob(e,t){let n=`</${t}>`,r="",o=0;for(;;){let s=Lg(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 sb(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 or(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&&le(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function ib(e,t,n){let r=St(t),o=St(n);for(let s of St(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 ab(e,t){let n=St(e),r=t.map(St),o=e.length,s=c=>{let p=c;for(;p<o&&le(e[p]);)p++;return p},i=c=>{for(let p=c;p<o;p++)if(nr(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&&!nr(e[m]);)m++;for(;m>g+1&&le(e[m-1]);)m--;return e.slice(g,m)}for(let m=o-1;m>d;m--)if(!nr(e[m]))return e[m];return null}}a=i(c)}return null}function cb(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=le(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"||!le(e[a-1]))continue;let c=a+1;if(le(e[c])){for(;c<t&&le(e[c]);)c++;$g(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]+(nr(e[a])?1:0);let s=(a,c)=>o[c]===o[a],i=a=>{let c=a+1;for(;le(e[c]);)c++;let p=c;for(;p<t&&$g(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&&le(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(!nr(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function lb(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&le(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&le(e[i]);)i++;n=i}let r=e.slice(n),o="",s=0;for(;s<r.length;){if(t(r,s)&&(s===0||!$g(r[s-1]))){let i=s,a=0;for(;t(r,i);){for(i+=6;i<r.length&&le(r[i]);)i++;a++}if(a>=2){s=i;continue}}o+=r[s],s++}return o}function ub(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 pb(e){return ub(e,!0)}function db(e){return ub(e,!1)}function _I(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function gb(e,t){let n=St(e),r=St(t),o=e.length,s=i=>{let a=i;for(;a<o&&le(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(!le(e[p])){p++;continue}let d=s(p);if(_I(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var mb=new Set(["read","glob","grep","list"]);function Y(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function PI(e){return mb.has(se(e))}function xI(e){let t=0,n=0,r=0;for(let o of e){let s=se(o.tool);s==="read"?t++:s==="glob"||s==="grep"?n++:s==="list"&&r++}return{read:t,search:n,list:r}}function Fg(e){if(!e)return"";let t=Ke(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ko(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function qo(e){let n=(e.state??{}).input??{};switch(Y(e.tool)){case"read":case"edit":case"write":case"morph_edit":{let s=n.filePath??n.file_path??n.path;return s?Fg(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?`"${Ko(String(s),40)}" in ${Fg(String(i))}`:s?`"${Ko(String(s),60)}"`:""}case"list":return n.path?Fg(String(n.path)):"";case"bash":return Ko(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 Ko(s==="query"&&tr(i)||i,60)}return""}var fb={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 SI(e,t={}){let n={...fb,...t},r=Y(e.tool),o=qo(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 we(e){return e.type==="text"}function Ae(e){return e.type==="reasoning"}function ne(e){return e.type==="tool"}function Kg(e){return e.type==="file"}function wI(e){return e.type==="agent"}function AI(e){return e.type==="compaction"}function vI(e){return e.type==="snapshot"}function kI(e){return e.type==="patch"}function RI(e){return e.type==="step-start"||e.type==="step-finish"}function CI(e){if(we(e)||Ae(e))return e.text}function II(e){if(!Kg(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function TI(e){let t=[],n=[];for(let r of e)Kg(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function EI(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function MI(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var OI=new Set(["todoread","context_info"]);function yb(e){return!OI.has(e.tool)}var DI=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 qg(e){let t=e.tool||"";if(t.startsWith("oc-"))return;let n=se(t);if(n==="task"||n==="delegate"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r;if(n==="task"&&e.state?.status==="error")return e.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return jI(t,e.state)}function jI(e,t){let n=Y(e);if(DI.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 $I(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return fe(n.error)}}function UI(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)ne(r)&&yb(r)&&t.push(r);return t}function LI(e,t={}){switch(Y(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:_b(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"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 FI(e,t)}}function FI(e,t){switch(se(e)){case"read":return{icon:"glasses",title:"Read",subtitle:hb(Ne(t))};case"list":return{icon:"list",title:"List",subtitle:bb(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:Ng(Ne(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Ng(Ne(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function hb(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Ng(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 bb(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function NI(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 sr(e,t=120){if(typeof e!="string")return"";let n=e.split(`
|
|
78
|
+
`).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function _b(e){let t=sr(e.description);if(t)return t;let n=sr(e.title,80);if(n)return n;let r=sr(e.message);if(r)return r;let o=sr(e.prompt);if(o)return o;let s=sr(e.agent_id,40);return s?`Agent ${s}`:"Worker task"}function KI(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function qI(e,t){return e.find(n=>n.tool?.callID===t)}function BI(e,t){return e.find(n=>n.tool?.callID===t)}var GI=/\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 WI(e){return e?e.replace(GI,""):""}var HI={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"},VI={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 zI(e){return e.replace(/^oc[-_]/,"")}function Bg(e){return zI(e).replace(/-/g,"_")}function Gg(e){return Bg(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Bo(e){return{label:HI[Bg(e)]??Gg(e),category:VI[se(e)]}}var YI=256*1024;function QI(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function XI(e){if(e===void 0)return{};if(e.length>YI)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function JI(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?fe(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var re=e=>typeof e=="string"?e:void 0,Go=e=>typeof e=="number"?e:void 0,Wo=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function Wg(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var ZI=new Set(["add","update","delete","move"]);function eT(e,t,n){if(e==="apply_patch"){let c=(Array.isArray(n.files)?n.files:[]).flatMap(p=>{let d=Wo(p),g=d&&(re(d.relativePath)||re(d.filePath));if(!d||!g)return[];let m=re(d.type);return[Wg({path:g,type:m&&ZI.has(m)?m:void 0,before:re(d.before),after:re(d.after),patch:re(d.patch)??re(d.diff),additions:Go(d.additions),deletions:Go(d.deletions),movePath:re(d.movePath)})]});return c.length?c:void 0}let r=Ne(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[Wg({path:r,after:re(t.content)})];if(e!=="edit")return;let o=Wo(n.filediff),s=o?void 0:re(n.patch),i=s?tT(s):void 0;return[Wg({path:r,before:re(o?.before)??re(t.oldString),after:re(o?.after)??re(t.newString),patch:s,additions:Go(o?.additions)??i?.additions,deletions:Go(o?.deletions)??i?.deletions})]}function tT(e){let t=0,n=0;for(let r of e.split(`
|
|
79
|
+
`))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function nT(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function Pb(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:o,outputText:s}=XI(r),i=QI(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=JI(o);m&&(i="error",a=m)}let c=se(e),p=t.input??{},d="metadata"in t&&Wo(t.metadata)||{},g=Wo(d.diagnostics);return{name:e,kind:c,title:n||Bo(e).label,status:i,input:t.input,output:r,outputParsed:o,outputText:s,error:a,files:eT(c,p,d),diff:re(d.patch)??re(d.diff),diagnostics:g,answers:c==="question"?nT(d):void 0,childSessionId:qg({tool:e,state:t})}}function rT(e){return Pb(e.tool,e.state)}function oT(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function sT(e){return{kind:"reasoning",id:e.id,text:e.text}}function iT(e){return{kind:"tool",id:e.id,tool:Pb(e.tool,e.state)}}function aT(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 cT(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function lT(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function uT(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function pT(e){return{kind:"agent",id:e.id,name:e.name}}function dT(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:fe(e.error),createdAt:e.time.created}}function gT(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function mT(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function fT(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Hg(e){switch(e.type){case"text":return oT(e);case"reasoning":return sT(e);case"tool":return iT(e);case"file":return aT(e);case"subtask":return cT(e);case"patch":return lT(e);case"snapshot":return uT(e);case"agent":return pT(e);case"retry":return dT(e);case"compaction":return gT(e);case"step-start":return mT(e);case"step-finish":return fT(e);default:return{kind:"unknown",raw:e}}}function yT(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=ye(e);return{name:t,message:n?.message||fe(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function hT(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function xb(e){let t=e.parts.map(Hg),n=e.info.role==="assistant"?e.info.error:void 0,r=yT(n),o=!r&&!t.some(hT);return{parts:t,error:r,isEmpty:o}}var Vg=Ue+BigInt(1),Sb=Vg/BigInt(2);function Ho(e){return BigInt(Math.trunc(e))*Ft}function zg(e,t){let r=t-(t&Ue)+e;return r-t>Sb?r-=Vg:t-r>Sb&&(r+=Vg),r}function wb(e,t){let n=_t(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return zg(n,t);let o=Ho(r),s=zg(n,o);return(s>o?s-o:o-s)<=Qe?s:o}function Ab(e){return _t(e)===null?1:0}function vb(e,t){return e<t?-1:e>t?1:0}function bT(e,t){return kb(e,t,Ho(Date.now()))}function _T(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 Ho(t??Date.now())}function kb(e,t,n){let r=Ab(e.info.id),o=Ab(t.info.id);if(r!==o)return r-o;if(r===0){let a=wb(e,n),c=wb(t,n);return a!==c?a<c?-1:1:vb(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:vb(e.info.id,t.info.id)}function PT(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=_T(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:kb(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:ST(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 ir=new Map,xT=256;function ST(e,t){let n=t.info,r=n.time?.created,o=`${n.sessionID??""}|${e}|${r??""}`,s=ir.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(ir.size>=xT){let a=ir.keys().next().value;a!==void 0&&ir.delete(a)}return ir.set(o,i),i}function wT(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function AT(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(we(n)&&n.text?.trim())return n}}function vT(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function kT(e,t,n){if(n)return[];let r=[];for(let o of e.assistantMessages)for(let s of o.parts){if(!ne(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 RT(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 CT(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 Rb(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(...Rb(e,o));return r}function Cb(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function IT(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&&Cb(n.error)}return!1}function Vo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Yg(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 TT(e){return!!e&&(Yg(e)||Tb(e)!==null)}function Qg(e){let t=Ib.get(e);if(t&&t.state===e.state)return t.outcome;let n=ET(e);return Ib.set(e,{state:e.state,outcome:n}),n}var Ib=new WeakMap;function ET(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(Yg(n))return"failed";let r=MT(n);return r===void 0?"ok":OT(r)?"failed":DT(r)}function MT(e){try{return JSON.parse(e)}catch{return}}function OT(e){return Vo(e)&&e.success===!1&&typeof e.error=="string"}function DT(e){let t=Vo(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 Tb(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Vo(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=or(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 jT(e){return lb(e).replace(/\s+/g," ").trim()||e.trim()}function $T(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Vo(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=or(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
|
+
|
|
81
|
+
`)}var Eb=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),UT={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 LT(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&tr(t)||t}function FT(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 LT(r,o.trim())}}function Xg(e){if(Ae(e))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!ne(e))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let t=ce(e.tool),n=UT[t],r=e.state?.input;return n?{verb:n.verb,running:n.running,object:FT(r,n.objectKeys),tier:Eb.has(t)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:t,tier:"primary"}}function NT(e){let t=0,n=0,r=!1,o=!1;for(let s of e){if(Xg(s).tier==="plumbing"){r=!0;continue}if(Ae(s)){if(!s.text?.trim())continue;o||(o=!0,t+=1);continue}o=!1,t+=1,ne(s)&&Qg(s)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function Jg(e){return`${e} ${e===1?"step":"steps"}`}function KT(e,t){let{total:n,failed:r,completed:o,hasPlumbing:s}=e;return t?n===0?"Working":`Working \xB7 ${Jg(n)}`:n===0?s?"Housekeeping":"Worked":r===0?`Completed ${Jg(n)}`:o===0?`${Jg(n)} failed`:`Completed ${o} of ${n} steps \xB7 ${r} failed`}function qT(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 BT(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function GT(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 WT(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=pb(n),n=db(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 HT(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=or(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 ar(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function zo(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(ar(i[1]),ar(i[2]),i[3]?ar(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(ar(i[2]),ar(i[1])),n.length>=t)return n}return n}function Mb(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 Yo(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 Zg(e){if(!e)return[];let t=Mb(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)?Yo(o.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=Yo(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)?Yo(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=Yo(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=zo(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function Qo(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function VT(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Qo(e)}}function zT(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function YT(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 Ob(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 Db(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let o=gb(n,r)?.trim()||n;return{url:r,success:!1,error:o}})}function QT(e,t){let n=jb(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?Db(r,Ob(t)):[]}function jb(e){if(!e)return null;let t=Mb(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=zo(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 XT(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 JT={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 Xo(e){return JT[se(e)]}function lr(e){let t=Y(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var ZT={run:"Terminal",memory:"Memory"};function eE(e){let t=Xo(e);return(t==="hidden"?void 0:ZT[t])??lr(e)}function cr(e,t,n){return e===1?t:n}function em(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 Lb(e){return e.length?qo(e[0]):""}function ve(e){return(e.state??{}).input??{}}var tE={agent_spawn:"spawn",agent_task:"spawn",agent_task_create:"spawn",agent_task_start:"spawn",task:"spawn",task_create:"spawn",task_start:"spawn",session_spawn:"spawn",session_start_background:"spawn",agent_message:"message",agent_task_message:"message",task_message:"message",session_message:"message",agent_status:"status",agent_task_list:"status",agent_task_get:"status",task_list:"status",task_get:"status",agent_stop:"stop",agent_task_cancel:"stop",task_cancel:"stop",agent_task_approve:"done",task_approve:"done",task_done:"done",task_delete:"delete"};function nE(e){let t=Y(e.tool);if(t==="agent_task_update"||t==="task_update")switch(ve(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return tE[t]??"message"}function $b(e){switch(e){case"create":return"create";case"update":return"update";case"delete":return"delete";case"test":return"test";case"pause":case"resume":return"control";case"list":case"get":return"read";default:return"unknown"}}function rE(e){let t=Y(e.tool);if(t==="triggers"){let r=ve(e).action||"list";return $b(r)}let n=t.match(/^trigger_(.+)$/);return $b(n?n[1]:"list")}var oE={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 sE(e){return oE[Y(e.tool)]??"read"}var iE={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function aE(e){return iE[Y(e.tool)]??"open"}function en(e){return e.every(t=>t===e[0])}var cE={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function lE(e){if(Y(e.tool)!=="memory")return"read";let n=ve(e).command;return n&&cE[n]||"unknown"}var uE={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},pE={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 dE(e){let t=Ke(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function gE(e){let t=ve(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 mE(r,60);let o=typeof t.path=="string"?t.path:"";if(o)return dE(o);let s=typeof t.url=="string"?t.url:"";if(s){let i=XT(s);return i?Qo(i):"a link"}return""}function mE(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function fE(e){let t=ve(e).action;return t&&uE[t]||"Worked on an image"}function yE(e){let t=ve(e).action;return t&&pE[t]||"Worked on a presentation"}function hE(e){return e.slice(0,e.indexOf(":"))}var bE={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},_E={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 PE(e){let t=Y(e.tool);if(t==="image_gen"){let n=ve(e).action;return n&&bE[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=ve(e).action;return n&&_E[n]||"presentation:unknown"}return"shown:result"}var xE=new Set(["create_slide","export_pdf","export_pptx"]);function SE(e){let t=Y(e.tool);if(t==="image_gen")return"image";if(t==="video_gen")return"video";if(t==="presentation_gen"){let n=ve(e).action;return n?xE.has(n)?"presentation":null:"presentation"}return null}var wE={"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`},Ub={image:"image",video:"video",presentation:"presentation",shown:"result"};function AE(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[hE(r)]++;let n=[];return Object.keys(t).forEach(r=>{let o=t[r];o&&n.push(`${o} ${cr(o,Ub[r],`${Ub[r]}s`)}`)}),`Worked on ${em(n)}`}function tm(e,t){let n=t.length,r=Lb(t);switch(e){case"explore":{let o=t.filter(s=>Y(s.tool)==="read").length;return o===n?`Read ${n} ${cr(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=>Ne(ve(i))).filter(Boolean)).size||n,s=t.every(i=>Y(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=Y(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} ${cr(n,"query","queries")}`;if(s===0)return`Read ${n} ${cr(n,"page","pages")}`;let i=new Set;for(let c of t)if(o(c)){let p=c.state?.output;for(let d of Zg(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} ${cr(a,"source","sources")}`}case"create":{if(n===1){let s=t[0],i=Y(s.tool);if(i==="image_gen")return fE(s);if(i==="video_gen")return"Made a video";if(i==="presentation_gen")return yE(s);let a=gE(s);return a?`Showed you ${a}`:"Showed you the result"}let o=t.map(PE);return en(o)?wE[o[0]](n):AE(o)}case"plan":return n===1?"Planned the work":`Planned the work \xB7 ${n} steps`;case"delegate":{let o=t.map(nE);if(en(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(lE);if(en(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(sE);if(en(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(rE);if(en(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(aE);if(en(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 ${lr(t[0].tool)}`;let o=Array.from(new Set(t.map(s=>lr(s.tool))));return o.length===1?`Used ${o[0]} \xB7 ${n} times`:`Used ${em(o)}`}}}function nm(e,t){let n=Lb(t);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(t.length===1){let r=Y(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=>lr(i.tool))));return`Couldn't finish using ${em(s)}`}}}function vE(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function kE(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 Fb(e,t){let n=vE(t);return{id:t[0].callID,family:e,label:n==="error"?nm(e,t):tm(e,t),parts:t,status:n,durationMs:n==="running"?void 0:kE(t)}}function rm(e){let t=[],n=null,r=[],o=()=>{n&&r.length&&t.push(Fb(n,r)),n=null,r=[]};for(let s of e){let i=Xo(s.tool);if(i!=="hidden"&&!lo(s)){if(Bd(s.tool)){o(),t.push(Fb(i,[s]));continue}i!==n&&(o(),n=i),r.push(s)}}return o(),t}function Nb(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function RE(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 rm(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(Ae(a)){let c=a.text?.trim();if(!c)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(c);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=Nb(a);continue}if(s(),ne(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 CE=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function IE(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 TE(e){let t=e.flatMap(o=>{let s=IE(o);return s?[s]:[]}).join(" ").trim();return t?CE.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function Wb(e){return e?.info?.time??{}}function EE(e){let t=Wb(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Jo=6e4,ME=10080*Jo,Kb=1440;function qb(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 OE(e,t){let n=t.getTime()-e.getTime(),r=n/Jo,o=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return o(Math.round(r),"minute");if(r<Kb)return o(Math.round(r/60),"hour");let s=(n-(qb(t)-qb(e)))/Jo;return o(Math.round(s/Kb),"day")}function Hb(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 Bb=new Map;function DE(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,o=Bb.get(r);return o||(o=new Intl.DateTimeFormat(t.locale,n),Bb.set(r,o)),o}function Zo(e,t,n){return DE(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?jE(r.value,n):r.value).join("")}function jE(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function Gb(e,t){return Zo(e,{year:"numeric"},t)}function $E(e,t,n={}){let r=Hb(e);if(!r)return"";let o=i=>Zo(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<Jo?"just now":s<ME?OE(r,new Date(t)):o(Gb(r,n)!==Gb(new Date(t),n))}function UE(e,t={}){let n=Hb(e);if(!n)return"";let r=Zo(n,{month:"long",day:"numeric",year:"numeric"},t),o=Zo(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${o}`}function LE(e,t={}){let n=[],r=[],o=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let s of e)if(!Gd(s)){if(we(s)){o(),n.push({kind:"text",part:s});continue}if(ne(s)&&(Wd(s.tool)||!!t.standaloneCallIds?.has(s.callID))){o(),n.push({kind:"standalone",part:s});continue}r.push(s)}return o(),n}function FE(e){let t=ce(e);return t==="show"||t==="show_user"}function NE(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"&&FE(s.part.tool)&&!t.standaloneCallIds?.has(s.part.callID)){r.push(s);continue}o(),n.push(s)}return o(),n}var KE=["title","description","path","url","content","language","aspect_ratio","attachment"];function Vb(e,t){if(!t||typeof t!="object")return null;let n=t;if($n(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let o of KE){let s=n[o];typeof s=="string"&&s&&(r[o]=s)}return r}function qE(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 BE(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=qE(o.items),i=s?s.map(a=>Vb(n.callID,a)).filter(a=>!!a):[Vb(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 om(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var GE=e=>e.time?.completed;function WE(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function HE(e,t){let n=e.userMessage.info.id;return t.pendingTurnIds.has(n)||e.assistantMessages.length===0&&t.pendingPromptIds.has(n)}function VE(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=>HE(r,e));return n<=0?null:e.turns[n-1].userMessage.info.id}function zE(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function YE(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function QE(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:om({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function XE(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 JE(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(!GE(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 ZE(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 eM(e,t){return!t||!e?!1:e.type!=="idle"}function tM(e,t){return!e&&!!t}function nM(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ye(n.error)?.message||fe(n.error)}}function rM(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return jg(n.error)}}function oM(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ye(n.error)}}function sm(e){if(e){if(ne(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(Ae(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(we(e))return"Gathering thoughts..."}}function sM(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,o=ne(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=sm(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let s=sm(r);if(s)return s}return"Figuring out what\u2019s next..."}function im(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 am=1.2;function zb(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 cm(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function Yb(e,t,n,r){if(cm(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?zb(e.tokens,s):0}function Qb(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function iM(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}=Qb(d.info);n+=Yb(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=Xb(g,t),f=g.tokens&&cm(g.providerID,g.modelID);if(m<=0&&!f)continue;c=!0,n+=m;let b=g.tokens;b&&(r+=b.input??0,o+=b.output??0,s+=b.reasoning??0,i+=b.cache?.read??0,a+=b.cache?.write??0)}}if(c)return{cost:n*am,tokens:{input:r,output:o,reasoning:s,cacheRead:i,cacheWrite:a}}}function Xb(e,t){if(cm(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?zb({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function aM(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let o=r.info,{providerID:s,modelID:i}=Qb(o),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=Yb(p,s,i,t));c||(a+=Xb(o,t)),n+=a}return n*am}function cM(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function lM(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function uM(e){if(!e||e.type!=="retry")return;let t=e,n=fe(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:ye(t.message)}}function pM(e){if(!(!e||e.type!=="retry"))return fe(e.message)}function dM(e){return(e.info.summary?.diffs?.length??0)>0}function Jb(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=ce(e.part.tool);return t==="show"||t==="show_user"}function gM(e){return e.kind==="text"&&!e.part.text?.trim()}function mM(e,t){if(t.working)return null;let n=-1;for(let o=e.length-1;o>=0;o--){let s=e[o];if(!(Jb(s)||gM(s))){s.kind==="text"&&(n=o);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((o,s)=>{s===n?r.final.push(o):Jb(o)?r.hoisted.push(o):r.work.push(o)}),r.work.length>0?r:null}function fM(e){let t=e==null?"":im(e);return t?`Worked for ${t}`:"Worked"}function Zb(e){let t=e.userMessage.parts;if(t.length===0||!t.every(s=>we(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 ne(o)&&o.tool==="bash"}function yM(e){if(Zb(e))return e.assistantMessages[0].parts[0]}function hM(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=ob(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 bM(e){return e?e.split(`
|
|
82
|
+
`).filter(n=>n.trim()).length<=3:!1}function _M(e){if(!e)return null;let n=e.split(`
|
|
83
|
+
`).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function PM(e){if(!e)return[];let t=[],n=e.split(`
|
|
84
|
+
`).filter(r=>r.trim());for(let r of n){let o=cb(r);if(o){let s=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...o,sessionId:s?.[0]})}}return t}var nt={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 xM(e,t){let n=nt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function SM(e,t){return t?"failed":e?"running":"done"}var wM={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function AM(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function vM(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(ib(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 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
|
|
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 kM={add:{...nt.write,icon:"create"},delete:{...nt.delete,icon:"delete"},move:{...nt.rename,icon:"edit"},update:{...nt.edit,icon:"edit"}},e_={...nt.change,icon:"edit"};function RM(e){if(e.length===0)return e_;let t=t_(e[0]);for(let n=1;n<e.length;n++)if(t_(e[n])!==t)return e_;return kM[t]}function t_(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function CM(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 IM(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 TM(e){if(!e)return null;let t=rr(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=Ug(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=
|
|
91
|
-
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:s}}return null}function
|
|
92
|
-
\u2026`:e}function
|
|
90
|
+
`);return{path:n,type:"file",content:s}}let o=Ug(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 EM(e){let t=rb(e,"skill_content");return t!==null?t.trim():e}function n_(e){let t=rr(e,"<skill_files>","</skill_files>");return t===null?[]:sb(t,"<file>","</file>").map(n=>n.trim())}function MM(e){let t=nb(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 OM(e){return ab(e,["Base directory","Directory","Skill directory"])?.trim()??""}function r_(e){return Ke(MM(e)||OM(e))}function DM(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Ke(n.trim())}return""}var jM="skills";function $M(e){let t=tb(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?`${jM}/${r}`:""}function UM(e,t,n){let o=Ke(t?.trim()??"")||r_(e)||$M(n),s=n_(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 LM=4e3;function ur(e,t=LM){return e.length>t?`${e.slice(0,t)}
|
|
92
|
+
\u2026`:e}function o_(e){if(e!==void 0)try{return ur(JSON.stringify(e,null,2))}catch{return}}function W(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function wt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function FM(e){let t=W(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=wt(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=wt(s)??{};return{title:W(i.title)??"",url:W(i.url,i.link)??"",snippet:W(i.snippet,i.description,i.source)}});return{kind:"web-search",query:W(n.query)??t,results:o.length>0?o:void 0,answer:W(n.answer)}}var NM=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function um(e){let t=e.match(NM);return t?Number(t[1]):void 0}function KM(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 qM=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function BM(e){let t=-1;for(let n of qM){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var GM=/\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 WM(e){return e.replace(GM,"")}function HM(e){let t=W(e.input?.command)??"",n=e.output??"",r=um(n),s=WM(BM(KM(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 pm(e){return W(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function VM(e){let t=e.status==="error"?e.error:e.output&&ur(e.output)||void 0;return{kind:"file-read",path:pm(e),preview:t}}function zM(e){let t=W(e.input?.content),n=e.status==="error"?e.error:ur(t??e.output??"")||void 0;return{kind:"file-write",path:pm(e),preview:n}}var YM=256*1024;function QM(e,t){if(e.length+t.length>YM)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 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
|
|
95
|
-
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function bM(e){let t=W(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=jb.test(e.output.trim())?yM(e.output):hM(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function _M(e){let t=W(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=W(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function Jg(e){let t=ft(e)??{};return{content:W(t.content)??"",status:W(t.status)??"pending",priority:W(t.priority)}}function PM(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(Jg)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(Jg)};let n=ft(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(Jg)}:{kind:"todo",items:[]}}function xM(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let o=ft(r)??{},i=(Array.isArray(o.options)?o.options:[]).flatMap(a=>{let c=ft(a),p=c&&W(c.label);return p?[{label:p,description:c?W(c.description):void 0}]:[]});return{question:W(o.question)??"",header:W(o.header),options:i}})}}function SM(e){let n=e.input&&Object.keys(e.input).length>0?Ob(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?tr(e.outputParsed):Ob(e.outputParsed):e.outputText!==void 0?r=tr(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function $b(e){switch(te(e.name)){case"web_search":return tM(e);case"bash":return cM(e);case"read":return lM(e);case"write":return uM(e);case"edit":return mM(e);case"grep":case"glob":return bM(e);case"task":return _M(e);case"todowrite":return PM(e);case"question":return xM(e);default:return SM(e)}}var wM=new Set(["AbortError","MessageAbortedError"]),vM=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],AM=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function Ub(e){let t=e.toLowerCase();return AM.some(n=>t.includes(n))?!1:vM.some(n=>t.includes(n))}function kM(e){let t=e.data,n=t&&typeof t=="object"?t.message:void 0;return typeof n=="string"?n:typeof e.message=="string"?e.message:void 0}function nr(e){if(typeof e=="string")return Ub(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&wM.has(n))return!0;let r=kM(t);return typeof r=="string"?Ub(r):!1}var Fb=["user","runtime-disposed","orphan-finalized","wake"],RM=["orphan-finalized","wake"];function IM(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 Fb.includes(n)?n:void 0}var rr="kortix-active-instance",Lb=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function Nb(e){return Lb.some(t=>e===t||e.startsWith(`${t}/`))}function Vt(e){let t=e.match(/^\/instances\/([^/]+)(?:\/(.*))?$/);if(!t)return null;let n=decodeURIComponent(t[1]),r=t[2]??"";return{instanceId:n,innerPath:r?`/${r}`:""}}function CM(e){let t=Vt(e);return!!t&&t.innerPath===""}function TM(e){let t=Vt(e);return!t||!t.innerPath?e:t.innerPath}function Kb(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=Vt(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return Nb(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function qb(e){return e?Vt(e)?.instanceId??null:null}function EM(){return typeof window>"u"?null:qb(window.location.pathname)||Gb()}function Gb(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${rr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function MM(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${rr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${rr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${rr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function OM(e,t){return t?Kb(t,e):e}function DM(e){let t=Vt(e);return t?t.innerPath||"/dashboard":e}function sr(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 tm(e){let t=sr(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 jM=tm;function Wo(e){let t=tm(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var $M=Wo;function Bb(e){return Wo(e)!==null}var UM=Bb,FM=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],LM=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],NM=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function Wb(e){return NM.test(sr(e))}function zt(e){let t=sr(e);return t?Wb(t)||FM.some(n=>n.test(t)):!1}var KM=/server url not ready|sandbox is still loading/i;function qM(e){return KM.test(sr(e))||zt(e)}var or=class extends Error{constructor(t){let n=t?.trim();super(n&&zt(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function Hb(e){let t=Wo(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=sr(e);return zt(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var GM=Hb;function nm(e){if(!e.external_id){if(e.base_url)return e.base_url;throw new Error(`Cannot build sandbox URL: missing external_id for ${e.provider} sandbox "${e.sandbox_id}"`)}return`${qe()}/p/${e.external_id}/${Te.KORTIX_MASTER}`}function BM(e,t){return e.external_id?`${qe()}/p/${e.external_id}/${t}`:null}async function WM(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function Vb(e){let t=await ct();if(t)return{sandbox:t.sandbox,created:!1};let r=(await ot())[0];if(!r)throw new Error("Create a project before starting a sandbox");let o=await at(r.project_id,{...e?.provider?{provider:e.provider}:{}}),s=(await Le(r.project_id,o.session_id))?.sandbox??null;return{sandbox:Bd(r,o,s),created:!0}}async function HM(){return(await ct().catch(()=>null))?.sandbox??null}async function VM(e){return{sandbox:(await Vb(e)).sandbox}}async function zM(e){let t=In(e);return t?(await ct(t).catch(()=>null))?.sandbox??null:null}async function YM(e,t){throw await ct(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function QM(e){let t=In(e);return(await Wd().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function XM(){return null}async function JM(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await ct(e);if(!t)throw new Error("Project session sandbox not found");await Pn(t.project.project_id,t.session.session_id)}async function ZM(e){if(!e)throw new Error("No sandbox selected to stop");let t=await ct(e);if(!t)throw new Error("Project session sandbox not found");await xn(t.project.project_id,t.session.session_id)}async function eO(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function tO(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function rm(e,t,n){let r=nm(e),o=await E(`${ee(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 nO(e,t){return rm(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function rO(e,t,n,r="member"){await rm(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function oO(e,t,n){await rm(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var om="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function sO(e){throw F("getInvite",om)}async function iO(e){throw F("acceptInvite",om)}async function aO(e){throw F("declineInvite",om)}async function cO(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function lO(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function uO(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function pO(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function dO(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function gO(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var zb=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function mO(e){return zb.includes(e)}async function fO(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 yO(e){let t=e?`?channel=${e}`:"",r=await(await ke(`${qe()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let o=await Yb(e||"stable");r.changelog=o.find(s=>s.version===r.version)??o[0]??null}catch{r.changelog=null}return r}async function Yb(e){let t=e?`?channel=${e}`:"";return(await(await ke(`${qe()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function hO(){return(await ke(`${qe()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function bO(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function _O(e){}async function PO(e){}async function xO(e){return{serverTypes:[],location:e||"hel1"}}async function SO(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function wO(e){throw F("deleteInstance")}async function vO(e,t){}async function AO(){throw F("claimComputer")}async function kO(e){return null}function RO(e,t){throw F("getSandboxProvisionStreamUrl")}var ir=class extends Error{constructor(n,r,o){super(n);this.status=r;this.body=o;this.name="HostBoundaryError"}status;body};function Qb(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 Xb(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Jb(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function z(e,t,n){let r=n?.body!==void 0,o=await fetch(`${Cn(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:Qb(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 Xb(o);if(!o.ok)throw new ir(Jb(o,s),o.status,s);return s}function IO(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 CO(e,t){return z(`/marketplace/items${IO(t)}`,e)}function TO(e){return z("/marketplace/marketplaces",e)}function EO(e,t){return z(`/marketplace/items/${encodeURIComponent(e)}`,t)}function MO(e,t,n){return z(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function OO(e,t){return z("/access/check-email",t,{method:"POST",body:{email:e}})}function DO(e,t){return z("/access/request-access",t,{method:"POST",body:e})}function jO(e){return z("/auth/logout",e,{method:"POST",body:{}})}function $O(e,t){return z(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function UO(e,t){return z("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function FO(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function LO(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function NO(e,t,n={}){return z(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function KO(e,t){return z(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function qO(e,t,n,r){return z(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function GO(e,t){return z(`/p/public-share/${encodeURIComponent(e)}`,t)}function BO(e,t,n){return z(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function WO(e){return z("/system/maintenance",e)}function HO(e,t){return z("/system/maintenance",t,{method:"PUT",body:e})}function VO(e){return z("/user-roles",e)}function zO(e,t){return z("/system/demo-request",t,{method:"POST",body:e})}async function YO(e,t,n){let r=await fetch(`${Cn(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${kt(t)}`,{headers:Qb(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let o=await Xb(r);throw new ir(Jb(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 QO(e,t){throw F("openStressTestStream")}function XO(e,t){throw F("buildPublicTemplateUrl")}async function JO(e,t,n){throw F("getPublicTemplate")}var ZO="kortix:connect-link:";function sm(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`${ZO}${t.toString(36)}${n.toString(36)}`}function eD(e,{storage:t}={}){let n=new Map,r=new Map,o=i=>{if(t)try{let a=t.getItem(sm(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(sm(i));return}return c}catch{return}},s=(i,a)=>{if(t)try{t.setItem(sm(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 Zb="Could not start the connect flow.";async function tD(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:Zb}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:Zb};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var e_=3e3,t_=5e3,n_=5*6e4;function nD(e,t){let n=e===0?e_:t_;return t+n>n_?null:n}function rD(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 oD(){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 sD(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 iD(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 aD(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 cD(){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 b1="1";var lD="kortix.query-cache";function o_(e){return!!e&&typeof e.then=="function"}function r_(e){return o_(e)?e:Promise.resolve()}function uD(e){if(e[0]!=="kx")return!1;let t=e[1];if(t==="accounts")return e.length===3&&typeof e[2]=="string"&&e[2]!=="anonymous";if(t==="projects")return e.length===3;if(t!=="project"||typeof e[2]!="string")return!1;let n=e[3];if(e.length===4)return n==="summary"||n==="detail";if(n!=="sessions")return!1;if(e.length===6)return e[4]==="list-paged";if(e.length===7&&e[4]==="list-paged"){let r=e[6];return typeof r=="object"&&r!==null&&!r.q}return e.length===7&&e[4]==="list-children"?e[6]==="":e.length===5&&e[4]!=="list"&&e[4]!=="list-paged"}function pD(e){let{storage:t,userId:n,shouldPersist:r,version:o="1",maxAgeMs:s=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=lD,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),S=()=>{try{return r_(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},D=(w,P)=>{if(!P)return 0;let A;try{A=JSON.parse(P)}catch{return S(),0}if(!A||A.v!==o||A.user!==n||!Array.isArray(A.queries)||p()-A.at>s)return S(),0;let C=0;for(let T of A.queries){if(!T||!Array.isArray(T.k)||T.d===void 0||typeof T.t!="number"||p()-T.t>s||!r(T.k))continue;let N=w.getQueryState(T.k);N&&N.data!==void 0&&N.dataUpdatedAt>=T.t||(w.setQueryData(T.k,T.d,{updatedAt:T.t}),w.invalidateQueries?.({queryKey:T.k,exact:!0,refetchType:"none"}),C+=1)}return C},j=w=>w.getQueryCache().getAll().filter(P=>P.state.data!==void 0&&r(P.queryKey)).map(P=>({k:P.queryKey,d:P.state.data,t:P.state.dataUpdatedAt})).sort((P,A)=>A.t-P.t),L=(w,P)=>{let A=[],C=0;for(let T of w){let N=JSON.stringify(T).length+1;C+N>P||(A.push(T),C+=N)}return A},y=async w=>{let P=L(j(w),i);for(;;){let A={v:o,user:n,at:p(),queries:P};try{await r_(t.setItem(d,JSON.stringify(A)));return}catch{if(P.length===0)return;P=P.slice(0,Math.floor(P.length/2))}}},_=()=>{f!==null&&(clearTimeout(f),f=null)},x=()=>{_();let w=g;return!w||!m||(m=!1,h=h.then(()=>y(w)).catch(()=>{})),h},M=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,x()},a))};return{storageKey:d,restore(w){let P;try{P=t.getItem(d)}catch{return 0}return o_(P)?P.then(A=>D(w,A)).catch(()=>0):D(w,P)},persist(w){g=w,m=!0;let P=w.getQueryCache().subscribe(A=>{A.type!=="updated"&&A.type!=="removed"&&A.type!=="added"||r(A.query.queryKey)&&M()});return()=>{P(),g===w&&(g=null,_())}},flush(){return x()},async clear(){_(),g=null,m=!1,await h,await S()}}}function dD(){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 s_="/kortix/part/";function i_(e){return typeof e=="string"&&e.startsWith(s_)}async function gD(e){if(!i_(e))throw new Error(`not an attachment part reference: ${e}`);let t=Me();if(!t)throw new Error("runtime url not bound");let n=await E(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function a_(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 mD(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 im(e,t){return mD(e,t)?(t?a_(t):null)??a_(e):null}function ar(e){try{let{hostname:t}=new URL(e);return/^p\d+-[^.]+\./.test(t)||/^(?:dev|staging|prod|preview)-p\d+-[a-z0-9-]+\./i.test(t)}catch{return!1}}function am(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var fD=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function yD(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hD(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(yD).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${s}$`).test(e)}function bD(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function c_(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function _D(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:fD.test(n.hostname)?t.backendUrls.some(r=>{let o=bD(r);return o!==null&&c_(o)===c_(n)}):t.templates.some(r=>hD(n.origin,r))}async function l_(e,t={}){if(!ar(e))return!1;let n=k().backendUrl;n&&await Ge(n).catch(()=>null);let r=[n,t.serverUrl].filter(o=>typeof o=="string"&&o.length>0);return _D(e,{templates:$f(),backendUrls:r})}async function u_(e,t={}){let n=im(e,t.serverUrl||k().backendUrl||void 0);if(!n)return!1;let r=await St();if(!r)return!1;try{return(await fetch(n,{method:"POST",credentials:"include",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).ok}catch{return!1}}async function PD(e,t={}){if(ar(e)){if(!await l_(e,t))return e;let n=await St();return n?am(e,n):e}return await u_(e,t),e}var xD=3e3;function p_(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 SD(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 p_(s.status)}catch{return"unknown"}finally{clearTimeout(o),t?.signal?.removeEventListener("abort",r)}}function wD(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function vD(e,t){throw F("buildPresentationTemplatePdfUrl")}function AD(e,t){throw F("buildPresentationTemplateImageUrl")}function d_(e,t){return`${wD(e)}/presentation/convert-to-${t}`}async function kD(e,t,n,r){let o=d_(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,S)=>{let D=setTimeout(h,s);r?.signal?.addEventListener("abort",()=>{clearTimeout(D),S(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let h=JSON.parse(m);f=String(h.error||h.detail||h.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function RD(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 ID(e){return e==="unreachable"}function CD(e){return!e||e.status===0?"unknown":e.ok&&fg(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var g_=1e4,TD={connection:"unknown",faultSinceMs:null};function ED(e,t,n,r=g_){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 m_({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<Yo;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:c,abortFloor:c?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=Vo,streamFresh:!!o&&i-o.atMs<=Yt,inboxFresh:!!n&&i-n.atMs<=zo,activityFresh:!!s&&i-s.atMs<=Yt}}function Qt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function cm(e,t,n){if(!t)return!1;let r=Qt(e.started_at);if(r===null||r>=t.atMs)return!1;let o=n?.lastEnded,s=Qt(o?.ended_at);return!(o&&s!==null&&Math.abs(s-t.atMs)<=1e3&&o.turn_token!==e.turn_token)}function MD(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"&&!cm(d,n,s))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:r}:null}function OD(e,t,n,r){let{server:o,stream:s}=e,{serverFresh:i,abortFloor:a}=t,c=i?o.turns.filter(g=>!cm(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:Qt(p.started_at)??o.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function DD(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 jD(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,S=c&&!n&&o.atMs>=p,D=d&&s.atMs>=g&&(s.type==="idle"||s.atMs>=m);if(S&&(!s||o.atMs>=s.atMs))return{state:"idle",source:"server",turnId:null,since:Qt(o.lastEnded?.ended_at)??o.atMs,serverOpenTurnToken:r};if(D)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 j=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:j.source,turnId:null,since:j.atMs,serverOpenTurnToken:r}}function f_(e){let t=m_(e),{server:n,stream:r}=e,o=r&&r.type==="idle"&&r.origin!=="local"?r:null,s=n?.turns[0]?.turn_token??null,i=MD(e,t,o,s);if(i)return i;let{result:a,openTurn:c}=OD(e,t,o,s);return a??DD(e,t,s)??jD(e,t,c,s)}var Ho=6e4,Vo=45e3,Yt=45e3,zo=1e4,$D=3e3,Yo=15e3;function UD(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function FD(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 LD(e){return f_(e)}function ND(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+Yo:null,r?r.atMs+zo:null,o?o.atMs+Vo:null,s?s.atMs+Yt:null,i?i.atMs+Yt:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function y_(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||nr({name:o.name??void 0,message:o.message})?null:o}var KD="SandboxMemoryGuard";function qD(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=y_(e,t);if(r?.message){if(r.name!==KD)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 GD=6e4;function BD(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function WD(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var h_=9e4;function HD(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+h_}var VD=75e3,zD=2,YD=2e4;function lm(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function QD(e){return e.filter(t=>t!=null).join("|")}function XD(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function JD(e,t,n={}){let r=n.noProgressMs??75e3,o=n.maxRestarts??2,s=n.cooldownMs??2e4;if(t.runtimeReachable)return{...lm(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...lm(),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=XD(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 ZD={"retry-start":"retrying",restart:"restarting"};function ej(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${ZD[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function tj(e){return e===1?"once":e===2?"twice":`${e} times`}function nj(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 ${tj(t)}`),`Tried: ${r.join(", then ")}.`}var rj={"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 b_(e){return!!(e.metadata??{}).legacy_migration}function oj(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 b_(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function sj(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 ij={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 aj(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function Qo(e){return e.runtime_sessions??e.opencode_sessions??[]}function __(e){let t=Qo(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function cj(e){let t=__(e);return t?Qo(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function lj(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>Qo(r).some(o=>o.id===t))??null)}var uj=new Set;function P_(e){for(let t of[...uj])try{t(e)}catch{}}function pj(e){return e==="TIMEOUT"||e==="request_deadline"}function dj(e){let t=S_(e)?e.code:void 0;return typeof t=="string"?t:void 0}var S_=e=>typeof e=="object"&&e!==null;function x_(e){let t=e?.metadata;return!!S_(t)&&t.warm===!0}var gj=5,mj=2e3,fj=e=>new Promise(t=>setTimeout(t,e));async function yj(e,{attempts:t=gj,delayMs:n=mj,sleep:r=fj}={}){for(let o=0;o<t;o++){o>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function hj(e,t){let n=new Map,r=new Set,o=new Set,s=new Set,i=0,a=(c,p,d)=>{if(r.has(c)||n.has(c))return Promise.resolve();r.add(c);let g=i,m=(async()=>{let f=null;try{let h=await e.ensure(c,p);if(g!==i)return;o.has(h.sessionId)?f=h.sessionId:n.set(c,h)}catch{}finally{g===i&&r.delete(c)}f&&d>0&&await a(c,f,d-1)})();return s.add(m),m.finally(()=>s.delete(m)),m};return{ensure:(c,p)=>a(c,p?.excludeSessionId,1),take:(c,p,{replenish:d})=>{let g=n.get(c);return g?(n.delete(c),o.add(g.sessionId),d&&a(c,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(c,p,d)=>{try{return await e.claim(c,d),!0}catch(g){return pj(dj(g))?yj(async()=>!x_(await e.read(c,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:c=>{for(let[p,d]of n)if(d.sessionId===c)return n.delete(p),o.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(x_(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),o.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),o.clear()},settled:async()=>{for(;s.size>0;)await Promise.all([...s])}}}var bj=12e4,Xo=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},_j=1e3,Pj=15e3,w_=100,xj=50,Sj=10;function v_(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 or(`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 A_(e){return wj(v_(e))}function k_(e){return new um({...e,loadPage:v_(e)})}async function wj(e){let t=[],n=new Set,r;do{let i=await e({limit:w_,...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 vj={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},um=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??vj,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??bj,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof Xo;if(!r&&nr(n))return;if(r||this.update({freshness:zt(n)?"loading":"error"}),n instanceof b&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(_j*2**this.retryAttempt,Pj);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"?xj:w_,...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 Xo(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<Sj&&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||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let 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 R_(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 I_(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function Aj(e){throw F("buildTunnelEventStreamUrl")}function kj(e){let{url:t,token:n,method:r="GET",body:o,onEvent:s,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(y,_){s?.(y,_);let x=d.get(y);if(x)for(let M of x)try{M(_)}catch{}}async function S(){if(m)return;let y=new AbortController;g=y,p&&(p.aborted?y.abort():p.addEventListener("abort",()=>y.abort(),{once:!0}));let _=y.signal;try{let x={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&o!==void 0&&(x["Content-Type"]="application/json"),f&&(x["Last-Event-ID"]=f);let M=await fetch(t,{method:r,headers:x,body:r!=="GET"&&o!==void 0?JSON.stringify(o):void 0,signal:_,credentials:"include"});if(!M.ok)throw new Error(`SSE connection failed: ${M.status} ${M.statusText}`);if(!M.body)throw new Error("SSE response has no body");i?.();let w=M.body.getReader(),P=new TextDecoder,A="",C="message",T=[],N=K=>{if(K===""){T.length>0&&h(C,T.join(`
|
|
96
|
-
`)),C="message",T=[];return}if(K.startsWith(":"))return;let q=K.indexOf(":"),de=q===-1?K:K.slice(0,q),le=q===-1?"":K.slice(q+1);le.startsWith(" ")&&(le=le.slice(1)),de==="event"?C=le.trim()||"message":de==="data"?T.push(le):de==="id"&&!le.includes("\0")&&(f=le)},$=K=>{let q="";!K&&A.endsWith("\r")&&(q="\r",A=A.slice(0,-1));let de=A.split(/\r\n|\n|\r/);A=(de.pop()??"")+q;for(let le of de)N(le)};for(;!m;){let{done:K,value:q}=await w.read();if(K)break;A+=P.decode(q,{stream:!0}),$(!1)}m||(A+=P.decode(),$(!0),c?.())}catch(x){if(m||x instanceof DOMException&&x.name==="AbortError")return;a?.(x instanceof Error?x:new Error(String(x)))}}function D(){m=!0,g?.abort(),g=null,d.clear()}function j(y,_){let x=d.get(y)??new Set;x.add(_),d.set(y,x)}function L(y,_){d.get(y)?.delete(_)}return{connect:S,close:D,addEventListener:j,removeEventListener:L}}function Rj(e,t){throw F("createTunnelEventStream")}var C_="/_kortix/viewer",Jo=6e4,Xt=new Map;function T_(){Xt.clear(),cr.clear()}async function Ij(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 pm(e={}){let t=e.path??C_,n=e.fetch??((s,i)=>fetch(s,i)),r=Xt.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let o=Ij(t,n).then(s=>{let i=s?.expires_at?Date.parse(s.expires_at):Number.NaN,a=Number.isFinite(i)?i-Jo:Date.now()+Jo;return Xt.set(t,{session:s,expiresAt:a}),s});return Xt.set(t,{session:r?.session??null,expiresAt:0,inflight:o}),o}function E_(e={}){let t=e.path??C_;return Object.assign(async()=>(await pm(e))?.access_token??null,{invalidate:n=>{let r=Xt.get(t);r&&!r.inflight&&r.session?.access_token===n&&Xt.delete(t)}})}var cr=new Map;async function Cj(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let s=await n.json().catch(()=>null);s?.error==="app_not_linked"&&console.warn(`[kortix] ${String(s.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let o=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return cr.set(e,{token:r.token,refreshAt:Number.isFinite(o)?o-Jo:Date.now()+Jo}),r.token}catch{return null}}function dm(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((o,s)=>fetch(o,s));return async(o={})=>{let s=cr.get(n);if(s instanceof Promise)return s;if(s&&!o.forceRefreshToken&&s.refreshAt>Date.now())return s.token;let i=Cj(n,r).then(a=>(a===null&&cr.delete(n),a));return cr.set(n,i),i}}function M_(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("kortixBinding needs the App origin: pass { origin } outside a browser.");return{url:`${ee(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:dm({audience:e,fetch:t.fetch})}}var Xe=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},ce=e=>typeof e=="string"&&e.length>0?e:null;function O_(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Zo(e){if(!e||typeof e!="object")return null;let t=e,n=ce(t.sub)??ce(t.subject)??ce(t.user_id)??ce(t.userId);return n?{userId:n,email:ce(t.email),name:ce(t.name),picture:ce(t.picture)??ce(t.pictureUrl),groups:O_(t.groups),groupIds:O_(t.group_ids??t.groupIds),role:ce(t.role),accountId:ce(t.account_id)??ce(t.accountId),projectId:ce(t.project_id)??ce(t.projectId)}:null}function j_(e,t={}){let n=Zo(e);if(!n)throw new Xe("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:o}=t;if(r&&!r.some(s=>n.groups.includes(s)||n.groupIds.includes(s)))throw new Xe("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(o&&!o.some(s=>n.role===s))throw new Xe("forbidden",`Only ${o.join(" or ")||"no role"} members may do this.`);return n}var Tj=60,gm=new Map;function $_(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function D_(e){return JSON.parse(new TextDecoder().decode($_(e)))}async function Ej(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),o=e.slice(n+1),s=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(o),i=>i.charCodeAt(0))):decodeURIComponent(o);return JSON.parse(s)}if(/^https?:\/\//.test(e)){let n=gm.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>gm.delete(e)),gm.set(e,n)),n}return JSON.parse(e)}async function U_(e,t={}){let n=y=>{throw new Xe("unauthenticated",`Kortix sign-in token refused: ${y}.`)},r=t.jwks??Ke("KORTIX_AUTH_JWKS"),o=t.issuer??Ke("KORTIX_AUTH_ISSUER"),s=t.audience??Ke("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(s!==!1&&!s)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,c,p]=i,d,g;try{d=D_(a),g=D_(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await Ej(r,t.fetch??((y,_)=>fetch(y,_)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(y=>y.kty==="EC"&&(d.kid===void 0||y.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${c}`),S;try{S=$_(p)}catch{return n("malformed")}let D=!1;for(let y of f)try{let{kid:_,alg:x,use:M,key_ops:w,...P}=y,A=await crypto.subtle.importKey("jwk",P,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},A,S,h)){D=!0;break}}catch{}if(!D)return n("bad signature");let j=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+Tj<j)return n("expired");if(o&&g.iss!==o)return n("wrong issuer");if(s){let y=g.aud;if(!(y===s||Array.isArray(y)&&y.includes(s)))return n("wrong audience")}let L=Zo(g);return L||n("no subject")}function mm(e){let t=e.agents.map(Mj),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 Mj(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function fm(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>no(n?{...r,mode:null}:r))}function F_(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=fm(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 L_=mm;function N_(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function ym(e){return{providerID:"kortix",modelID:e}}function K_(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 ym(n)}var hm=[{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 bm(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function Dj(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function q_(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 G_(e){return e.reduce((t,n)=>{let r=bm(n)??0,o=bm(t)??0;return r!==o?r>o?n:t:se(n.id)>se(t.id)?n:t})}function _m(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,o=new Set;for(let[,s]of q_(e,Dj)){let a=[...q_(s,p=>p.family||p.id).values()].map(G_),c=a.filter(p=>{let d=bm(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[G_(a)])o.add(p.id)}return o}function es(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 lr(e){let t;for(let n of es(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 jj={"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 B_(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var $j=(()=>{let e=new Map;for(let{id:n,env:r}of hm)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=>B_(s)===n)??o[0])}return t})();function W_(e){let t=jj[e.id];if(t)return t;let n=e.env??[],r=n.length===1?$j.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[B_(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function xm(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var Uj=["low","medium","high"];function H_(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:[...Uj]}: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 V_=hm;var Pm={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var ts=[{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"],...Pm,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"],...Pm,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"],...Pm,max_price:{prompt:3.3,completion:16.5}}}],UW=new Map(ts.map(e=>[e.id,e]));var z_=ts.map(e=>e.id),Y_=(ts.find(e=>e.tier==="flagship")??ts[0]).id,Q_="deepseek-v4.1-flash";var J_=V_.map(e=>({id:e.id,authRequirement:W_(e)})),ur=new Set(["kortix"]),Sm=new Set(["kortix"]);function Jt(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 Fj(e){if(!e)return!1;let t=Jt(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 Lj(e){let t=Jt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(o=>!Sm.has(o.id)),connected:r.filter(o=>!Sm.has(o))}}function Nj(e,t,n){let r=Jt(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)&&xm(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 Kj=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function qj(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var wm="opencode";function Gj(e){return e.cost?.input===0&&e.cost?.output===0}function X_(e){return e===wm?Number.MAX_SAFE_INTEGER:Kj.get(e)??Number.MAX_SAFE_INTEGER-1}function Bj(e,t){let n=Hj(t),r={},o=(e.providers??[]).map(s=>{let i=(s.models??[]).filter(a=>a.status!=="deprecated");return s.id===wm&&!n.has(wm)?{...s,models:i.filter(Gj),keyless:!0}:{...s,models:i,keyless:!1}}).filter(s=>(s.keyless||n.has(s.id))&&!Sm.has(s.id)&&(s.models?.length??0)>0).sort((s,i)=>X_(s.id)-X_(i.id)).map(s=>{let i=[...s.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||se(p.id)-se(c.id)),a=lr(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=qj(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 Wj(e,t){if(!e)return t;if(!t)return e;let n=Jt(e),r=Jt(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 Hj(e){let t=new Set;for(let n of J_)xm(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function Vj(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,o])=>{if(o.variants&&Object.keys(o.variants).length>0)return[r,o];let s=H_({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 zj(e,t){return Lj(Nj(Jt(e),t,J_))}function Z_(e){if(e.gatewayEnabled)return e.modelPicker?Vj(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?zj(e.runtimeProviders,t):void 0;return Wj(e.llmCatalogProviders?Bj(e.llmCatalogProviders,t):void 0,Fj(n)?n:void 0)}function Yj(e){return"capabilities"in e&&e.capabilities!=null}function ns(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function eP(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"?!ur.has(i.id):ur.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(Yj(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:N_({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 tP(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var Qj=new Set([Y_]),Xj="kortix",nP="codex",Jj=new Set(z_);function Zj(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Zt(e){return Qj.has(e.modelID)}function e$(e){return _m(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function rP(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=e$(e.catalogModels),o=tP(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===Xj){let d=Zj(i.modelID,i.provider),g=d===nP?t?.has(nP)??!1:t?.has(d)??!1;if(Jj.has(i.modelID))return!n||i.modelID===Q_;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=o.get(a);if(!m?.releaseDate)return Zt(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Zt(i)}catch{return Zt(i)}return!1}if(c==="show"||r.has(a))return!0;let p=o.get(a);if(!p?.releaseDate)return Zt(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Zt(i)}catch{return Zt(i)}return!1}}function oP(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 sP(e,t){if(!e||ur.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??lr(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!s||s===e.modelID?e:{...e,modelID:s}}function iP(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?ym(n):void 0}function aP(e){let{models:t,providers:n}=e,r=c=>ns(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 es(Object.keys(m.models).map(S=>({id:S})))){let S={providerID:m.id,modelID:h.id};if(r(S))return S}}}})(),i=o(e.picks??[]),a=i??o([e.serverDefault,e.globalDefault,e.agentModel,s]);return{model:sP(a,t),explicit:i,fallback:s}}return mP(t$);})();
|
|
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 XM(e){let t=W(e?.oldString),n=W(e?.newString);return t!==void 0&&n!==void 0?[[t,n]]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(o=>{let s=wt(o),i=s&&W(s.oldText),a=s&&W(s.newText);return i!==void 0&&a!==void 0?[[i,a]]:[]})}function JM(e){let t=XM(e.input),n=t.map(([o,s])=>QM(o,s)),r=t.length&&n.every(Boolean)?n.flatMap(o=>o??[]):void 0;return{kind:"file-edit",path:pm(e),diff:r}}var i_=/^Found\s+(\d+)\s+match/i,ZM=/^(\/[^:]+?):\s*/,s_=/Line\s+(\d+):/g;function eO(e){let t=e.trim(),n=t.match(i_),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(ZM);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(s_.lastIndex=0;(g=s_.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,b=p.slice(d[m].contentStart,f).trim();o.push({path:c,line:d[m].line,content:b.endsWith(";")?b.slice(0,-1):b})}}return o}function tO(e){return e.trim().split(`
|
|
95
|
+
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function nO(e){let t=W(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=i_.test(e.output.trim())?eO(e.output):tO(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function rO(e){let t=W(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=W(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function lm(e){let t=wt(e)??{};return{content:W(t.content)??"",status:W(t.status)??"pending",priority:W(t.priority)}}function oO(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(lm)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(lm)};let n=wt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(lm)}:{kind:"todo",items:[]}}function sO(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let o=wt(r)??{},i=(Array.isArray(o.options)?o.options:[]).flatMap(a=>{let c=wt(a),p=c&&W(c.label);return p?[{label:p,description:c?W(c.description):void 0}]:[]});return{question:W(o.question)??"",header:W(o.header),options:i}})}}function iO(e){let n=e.input&&Object.keys(e.input).length>0?o_(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?ur(e.outputParsed):o_(e.outputParsed):e.outputText!==void 0?r=ur(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function a_(e){switch(se(e.name)){case"web_search":return FM(e);case"bash":return HM(e);case"read":return VM(e);case"write":return zM(e);case"edit":return JM(e);case"grep":case"glob":return nO(e);case"task":return rO(e);case"todowrite":return oO(e);case"question":return sO(e);default:return iO(e)}}var aO=new Set(["AbortError","MessageAbortedError"]),cO=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],lO=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function c_(e){let t=e.toLowerCase();return lO.some(n=>t.includes(n))?!1:cO.some(n=>t.includes(n))}function uO(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 pr(e){if(typeof e=="string")return c_(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&aO.has(n))return!0;let r=uO(t);return typeof r=="string"?c_(r):!1}var l_=["user","runtime-disposed","orphan-finalized","wake"],pO=["orphan-finalized","wake"];function dO(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 l_.includes(n)?n:void 0}var dr="kortix-active-instance",u_=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function p_(e){return u_.some(t=>e===t||e.startsWith(`${t}/`))}function tn(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 gO(e){let t=tn(e);return!!t&&t.innerPath===""}function mO(e){let t=tn(e);return!t||!t.innerPath?e:t.innerPath}function d_(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=tn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return p_(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function g_(e){return e?tn(e)?.instanceId??null:null}function fO(){return typeof window>"u"?null:g_(window.location.pathname)||m_()}function m_(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${dr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function yO(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${dr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${dr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${dr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function hO(e,t){return t?d_(t,e):e}function bO(e){let t=tn(e);return t?t.innerPath||"/dashboard":e}function mr(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 dm(e){let t=mr(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 _O=dm;function es(e){let t=dm(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var PO=es;function f_(e){return es(e)!==null}var xO=f_,SO=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],wO=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],AO=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function y_(e){return AO.test(mr(e))}function nn(e){let t=mr(e);return t?y_(t)||SO.some(n=>n.test(t)):!1}var vO=/server url not ready|sandbox is still loading/i;function kO(e){return vO.test(mr(e))||nn(e)}var gr=class extends Error{constructor(t){let n=t?.trim();super(n&&nn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function h_(e){let t=es(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=mr(e);return nn(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 RO=h_;function gm(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`${ze()}/p/${e.external_id}/${$e.KORTIX_MASTER}`}function CO(e,t){return e.external_id?`${ze()}/p/${e.external_id}/${t}`:null}async function IO(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function b_(e){let t=await yt();if(t)return{sandbox:t.sandbox,created:!1};let r=(await ut())[0];if(!r)throw new Error("Create a project before starting a sandbox");let o=await mt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),s=(await We(r.project_id,o.session_id))?.sandbox??null;return{sandbox:Zd(r,o,s),created:!0}}async function TO(){return(await yt().catch(()=>null))?.sandbox??null}async function EO(e){return{sandbox:(await b_(e)).sandbox}}async function MO(e){let t=Ln(e);return t?(await yt(t).catch(()=>null))?.sandbox??null:null}async function OO(e,t){throw await yt(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function DO(e){let t=Ln(e);return(await eg().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function jO(){return null}async function $O(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await yt(e);if(!t)throw new Error("Project session sandbox not found");await Tn(t.project.project_id,t.session.session_id)}async function UO(e){if(!e)throw new Error("No sandbox selected to stop");let t=await yt(e);if(!t)throw new Error("Project session sandbox not found");await En(t.project.project_id,t.session.session_id)}async function LO(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function FO(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function mm(e,t,n){let r=gm(e),o=await E(`${oe(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 NO(e,t){return mm(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function KO(e,t,n,r="member"){await mm(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function qO(e,t,n){await mm(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var fm="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function BO(e){throw U("getInvite",fm)}async function GO(e){throw U("acceptInvite",fm)}async function WO(e){throw U("declineInvite",fm)}async function HO(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function VO(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function zO(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function YO(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function QO(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function XO(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var __=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function JO(e){return __.includes(e)}async function ZO(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 eD(e){let t=e?`?channel=${e}`:"",r=await(await Te(`${ze()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let o=await P_(e||"stable");r.changelog=o.find(s=>s.version===r.version)??o[0]??null}catch{r.changelog=null}return r}async function P_(e){let t=e?`?channel=${e}`:"";return(await(await Te(`${ze()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function tD(){return(await Te(`${ze()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function nD(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function rD(e){}async function oD(e){}async function sD(e){return{serverTypes:[],location:e||"hel1"}}async function iD(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function aD(e){throw U("deleteInstance")}async function cD(e,t){}async function lD(){throw U("claimComputer")}async function uD(e){return null}function pD(e,t){throw U("getSandboxProvisionStreamUrl")}var fr=class extends Error{constructor(n,r,o){super(n);this.status=r;this.body=o;this.name="HostBoundaryError"}status;body};function x_(e,t){let n=new Headers(e.headers);return n.set("Accept","application/json"),t&&n.set("Content-Type","application/json"),e.accessToken&&n.set("Authorization",`Bearer ${e.accessToken}`),n}async function S_(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function w_(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 Q(e,t,n){let r=n?.body!==void 0,o=await fetch(`${ft(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:x_(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 S_(o);if(!o.ok)throw new fr(w_(o,s),o.status,s);return s}function dD(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 gD(e,t){return Q(`/marketplace/items${dD(t)}`,e)}function mD(e){return Q("/marketplace/marketplaces",e)}function fD(e,t){return Q(`/marketplace/items/${encodeURIComponent(e)}`,t)}function yD(e,t,n){return Q(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function hD(e,t){return Q("/access/check-email",t,{method:"POST",body:{email:e}})}function bD(e,t){return Q("/access/request-access",t,{method:"POST",body:e})}function _D(e){return Q("/auth/logout",e,{method:"POST",body:{}})}function PD(e,t){return Q(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function xD(e,t){return Q("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function SD(e,t){return Q(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function wD(e,t){return Q(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function AD(e,t,n={}){return Q(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function vD(e,t){return Q(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function kD(e,t,n,r){return Q(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function RD(e,t){return Q(`/p/public-share/${encodeURIComponent(e)}`,t)}function CD(e,t,n){return Q(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function ID(e){return Q("/system/maintenance",e)}function TD(e,t){return Q("/system/maintenance",t,{method:"PUT",body:e})}function ED(e){return Q("/user-roles",e)}function MD(e,t){return Q("/system/demo-request",t,{method:"POST",body:e})}async function OD(e,t,n){let r=await fetch(`${ft(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Dt(t)}`,{headers:x_(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let o=await S_(r);throw new fr(w_(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 DD(e,t){throw U("openStressTestStream")}function jD(e,t){throw U("buildPublicTemplateUrl")}async function $D(e,t,n){throw U("getPublicTemplate")}var UD="kortix:connect-link:";function ym(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`${UD}${t.toString(36)}${n.toString(36)}`}function LD(e,{storage:t}={}){let n=new Map,r=new Map,o=i=>{if(t)try{let a=t.getItem(ym(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(ym(i));return}return c}catch{return}},s=(i,a)=>{if(t)try{t.setItem(ym(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 A_="Could not start the connect flow.";async function FD(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:A_}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:A_};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var v_=3e3,k_=5e3,R_=5*6e4;function ND(e,t){let n=e===0?v_:k_;return t+n>R_?null:n}function KD(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 qD(){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 BD(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 GD(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 WD(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 HD(){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 yW="1";var VD="kortix.query-cache";function I_(e){return!!e&&typeof e.then=="function"}function C_(e){return I_(e)?e:Promise.resolve()}function zD(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 YD(e){let{storage:t,userId:n,shouldPersist:r,version:o="1",maxAgeMs:s=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=VD,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,b=Promise.resolve(),P=()=>{try{return C_(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},j=(T,x)=>{if(!x)return 0;let S;try{S=JSON.parse(x)}catch{return P(),0}if(!S||S.v!==o||S.user!==n||!Array.isArray(S.queries)||p()-S.at>s)return P(),0;let I=0;for(let C of S.queries){if(!C||!Array.isArray(C.k)||C.d===void 0||typeof C.t!="number"||p()-C.t>s||!r(C.k))continue;let F=T.getQueryState(C.k);F&&F.data!==void 0&&F.dataUpdatedAt>=C.t||(T.setQueryData(C.k,C.d,{updatedAt:C.t}),T.invalidateQueries?.({queryKey:C.k,exact:!0,refetchType:"none"}),I+=1)}return I},L=T=>T.getQueryCache().getAll().filter(x=>x.state.data!==void 0&&r(x.queryKey)).map(x=>({k:x.queryKey,d:x.state.data,t:x.state.dataUpdatedAt})).sort((x,S)=>S.t-x.t),N=(T,x)=>{let S=[],I=0;for(let C of T){let F=JSON.stringify(C).length+1;I+F>x||(S.push(C),I+=F)}return S},y=async T=>{let x=N(L(T),i);for(;;){let S={v:o,user:n,at:p(),queries:x};try{await C_(t.setItem(d,JSON.stringify(S)));return}catch{if(x.length===0)return;x=x.slice(0,Math.floor(x.length/2))}}},_=()=>{f!==null&&(clearTimeout(f),f=null)},w=()=>{_();let T=g;return!T||!m||(m=!1,b=b.then(()=>y(T)).catch(()=>{})),b},D=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,w()},a))};return{storageKey:d,restore(T){let x;try{x=t.getItem(d)}catch{return 0}return I_(x)?x.then(S=>j(T,S)).catch(()=>0):j(T,x)},persist(T){g=T,m=!0;let x=T.getQueryCache().subscribe(S=>{S.type!=="updated"&&S.type!=="removed"&&S.type!=="added"||r(S.query.queryKey)&&D()});return()=>{x(),g===T&&(g=null,_())}},flush(){return w()},async clear(){_(),g=null,m=!1,await b,await P()}}}function QD(){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 T_="/kortix/part/";function E_(e){return typeof e=="string"&&e.startsWith(T_)}async function XD(e){if(!E_(e))throw new Error(`not an attachment part reference: ${e}`);let t=Le();if(!t)throw new Error("runtime url not bound");let n=await E(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function M_(e){try{let t=new URL(e);if(/^\/proxy\/\d+(?:\/|$)/.test(t.pathname))return`${t.origin}/v1/p/auth`;let n=t.pathname.indexOf("/p/");return n!==-1?`${t.origin}${t.pathname.slice(0,n)}/p/auth`:`${t.origin}/v1/p/auth`}catch{return null}}function JD(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 hm(e,t){return JD(e,t)?(t?M_(t):null)??M_(e):null}function yr(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 bm(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var ZD=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function ej(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function tj(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(ej).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${s}$`).test(e)}function nj(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function O_(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function rj(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:ZD.test(n.hostname)?t.backendUrls.some(r=>{let o=nj(r);return o!==null&&O_(o)===O_(n)}):t.templates.some(r=>tj(n.origin,r))}async function D_(e,t={}){if(!yr(e))return!1;let n=v().backendUrl;n&&await Ye(n).catch(()=>null);let r=[n,t.serverUrl].filter(o=>typeof o=="string"&&o.length>0);return rj(e,{templates:iy(),backendUrls:r})}async function j_(e,t={}){let n=hm(e,t.serverUrl||v().backendUrl||void 0);if(!n)return!1;let r=await It();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 oj(e,t={}){if(yr(e)){if(!await D_(e,t))return e;let n=await It();return n?bm(e,n):e}return await j_(e,t),e}var sj=3e3;function $_(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 ij(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 $_(s.status)}catch{return"unknown"}finally{clearTimeout(o),t?.signal?.removeEventListener("abort",r)}}function aj(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function cj(e,t){throw U("buildPresentationTemplatePdfUrl")}function lj(e,t){throw U("buildPresentationTemplateImageUrl")}function U_(e,t){return`${aj(e)}/presentation/convert-to-${t}`}async function uj(e,t,n,r){let o=U_(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 b=await p.blob();if(b.size===0)throw new Error("Downloaded file is empty");return b}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((b,P)=>{let j=setTimeout(b,s);r?.signal?.addEventListener("abort",()=>{clearTimeout(j),P(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let b=JSON.parse(m);f=String(b.error||b.detail||b.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function pj(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 dj(e){return e==="unreachable"}function gj(e){return!e||e.status===0?"unknown":e.ok&&Ag(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var L_=1e4,mj={connection:"unknown",faultSinceMs:null};function fj(e,t,n,r=L_){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 F_({optimistic:e,abort:t,inbox:n,server:r,stream:o,activity:s,nowMs:i}){let a=!!e&&i-e.atMs<ts,c=!!t&&i-t.atMs<os;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<=ns,streamFresh:!!o&&i-o.atMs<=rn,inboxFresh:!!n&&i-n.atMs<=rs,activityFresh:!!s&&i-s.atMs<=rn}}function on(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function _m(e,t,n){if(!t)return!1;let r=on(e.started_at);if(r===null||r>=t.atMs)return!1;let o=n?.lastEnded,s=on(o?.ended_at);return!(o&&s!==null&&Math.abs(s-t.atMs)<=1e3&&o.turn_token!==e.turn_token)}function yj(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"&&!_m(d,n,s))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:r}:null}function hj(e,t,n,r){let{server:o,stream:s}=e,{serverFresh:i,abortFloor:a}=t,c=i?o.turns.filter(g=>!_m(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:on(p.started_at)??o.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function bj(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 _j(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:b}=t,P=c&&!n&&o.atMs>=p,j=d&&s.atMs>=g&&(s.type==="idle"||s.atMs>=m);if(P&&(!s||o.atMs>=s.atMs))return{state:"idle",source:"server",turnId:null,since:on(o.lastEnded?.ended_at)??o.atMs,serverOpenTurnToken:r};if(j)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:b,since:i.atMs,serverOpenTurnToken:r};let L=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:L.source,turnId:null,since:L.atMs,serverOpenTurnToken:r}}function N_(e){let t=F_(e),{server:n,stream:r}=e,o=r&&r.type==="idle"&&r.origin!=="local"?r:null,s=n?.turns[0]?.turn_token??null,i=yj(e,t,o,s);if(i)return i;let{result:a,openTurn:c}=hj(e,t,o,s);return a??bj(e,t,s)??_j(e,t,c,s)}var ts=6e4,ns=45e3,rn=45e3,rs=1e4,Pj=3e3,os=15e3;function xj(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function Sj(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 wj(e){return N_(e)}function Aj(e){let{optimistic:t,abort:n,inbox:r,server:o,stream:s,activity:i,nowMs:a}=e,c=[null,t?t.atMs+ts:null,n?n.atMs+os:null,r?r.atMs+rs:null,o?o.atMs+ns:null,s?s.atMs+rn:null,i?i.atMs+rn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function K_(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||pr({name:o.name??void 0,message:o.message})?null:o}var vj="SandboxMemoryGuard";function kj(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=K_(e,t);if(r?.message){if(r.name!==vj)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 Rj=6e4;function Cj(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function Ij(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var q_=9e4;function Tj(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+q_}var Ej=75e3,Mj=2,Oj=2e4;function Pm(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function Dj(e){return e.filter(t=>t!=null).join("|")}function jj(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function $j(e,t,n={}){let r=n.noProgressMs??75e3,o=n.maxRestarts??2,s=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Pm(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Pm(),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=jj(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 Uj={"retry-start":"retrying",restart:"restarting"};function Lj(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${Uj[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function Fj(e){return e===1?"once":e===2?"twice":`${e} times`}function Nj(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 ${Fj(t)}`),`Tried: ${r.join(", then ")}.`}var Kj={"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 B_(e){return!!(e.metadata??{}).legacy_migration}function qj(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 B_(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function Bj(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 Gj={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 Wj(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function ss(e){return e.runtime_sessions??e.opencode_sessions??[]}function G_(e){let t=ss(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 Hj(e){let t=G_(e);return t?ss(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 Vj(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=>ss(r).some(o=>o.id===t))??null)}var zj=new Set;function W_(e){for(let t of[...zj])try{t(e)}catch{}}function Yj(e){return e==="TIMEOUT"||e==="request_deadline"}function Qj(e){let t=V_(e)?e.code:void 0;return typeof t=="string"?t:void 0}var V_=e=>typeof e=="object"&&e!==null;function H_(e){let t=e?.metadata;return!!V_(t)&&t.warm===!0}var Xj=5,Jj=2e3,Zj=e=>new Promise(t=>setTimeout(t,e));async function e$(e,{attempts:t=Xj,delayMs:n=Jj,sleep:r=Zj}={}){for(let o=0;o<t;o++){o>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function t$(e,t){let n=new Map,r=new Set,o=new Set,s=new Set,i=0,a=(c,p,d)=>{if(r.has(c)||n.has(c))return Promise.resolve();r.add(c);let g=i,m=(async()=>{let f=null;try{let b=await e.ensure(c,p);if(g!==i)return;o.has(b.sessionId)?f=b.sessionId:n.set(c,b)}catch{}finally{g===i&&r.delete(c)}f&&d>0&&await a(c,f,d-1)})();return s.add(m),m.finally(()=>s.delete(m)),m};return{ensure:(c,p)=>a(c,p?.excludeSessionId,1),take:(c,p,{replenish:d})=>{let g=n.get(c);return g?(n.delete(c),o.add(g.sessionId),d&&a(c,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(c,p,d)=>{try{return await e.claim(c,d),!0}catch(g){return Yj(Qj(g))?e$(async()=>!H_(await e.read(c,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:c=>{for(let[p,d]of n)if(d.sessionId===c)return n.delete(p),o.add(c),p;return null},revalidate:async c=>{let p=n.get(c);if(!p)return!1;try{if(H_(await e.read(c,p.sessionId)))return!1}catch{return!1}return n.get(c)?.sessionId!==p.sessionId?!1:(n.delete(c),o.add(p.sessionId),!0)},held:c=>n.get(c)??null,reset:()=>{i+=1,n.clear(),r.clear(),o.clear()},settled:async()=>{for(;s.size>0;)await Promise.all([...s])}}}var n$=12e4,is=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},r$=1e3,o$=15e3,z_=100,s$=50,i$=10;function Y_(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 gr(`session ${c.status}`):new h(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function Q_(e){return a$(Y_(e))}function X_(e){return new xm({...e,loadPage:Y_(e)})}async function a$(e){let t=[],n=new Set,r;do{let i=await e({limit:z_,...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 c$={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},xm=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??c$,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??n$,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof is;if(!r&&pr(n))return;if(r||this.update({freshness:nn(n)?"loading":"error"}),n instanceof h&&(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(r$*2**this.retryAttempt,o$);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"?s$:z_,...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 is(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<i$&&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||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let 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 J_(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 Z_(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function l$(e){throw U("buildTunnelEventStreamUrl")}function u$(e){let{url:t,token:n,method:r="GET",body:o,onEvent:s,onOpen:i,onError:a,onClose:c,signal:p}=e,d=new Map,g=null,m=!1,f="";function b(y,_){s?.(y,_);let w=d.get(y);if(w)for(let D of w)try{D(_)}catch{}}async function P(){if(m)return;let y=new AbortController;g=y,p&&(p.aborted?y.abort():p.addEventListener("abort",()=>y.abort(),{once:!0}));let _=y.signal;try{let w={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&o!==void 0&&(w["Content-Type"]="application/json"),f&&(w["Last-Event-ID"]=f);let D=await fetch(t,{method:r,headers:w,body:r!=="GET"&&o!==void 0?JSON.stringify(o):void 0,signal:_,credentials:"include"});if(!D.ok)throw new Error(`SSE connection failed: ${D.status} ${D.statusText}`);if(!D.body)throw new Error("SSE response has no body");i?.();let T=D.body.getReader(),x=new TextDecoder,S="",I="message",C=[],F=K=>{if(K===""){C.length>0&&b(I,C.join(`
|
|
96
|
+
`)),I="message",C=[];return}if(K.startsWith(":"))return;let q=K.indexOf(":"),ge=q===-1?K:K.slice(0,q),me=q===-1?"":K.slice(q+1);me.startsWith(" ")&&(me=me.slice(1)),ge==="event"?I=me.trim()||"message":ge==="data"?C.push(me):ge==="id"&&!me.includes("\0")&&(f=me)},M=K=>{let q="";!K&&S.endsWith("\r")&&(q="\r",S=S.slice(0,-1));let ge=S.split(/\r\n|\n|\r/);S=(ge.pop()??"")+q;for(let me of ge)F(me)};for(;!m;){let{done:K,value:q}=await T.read();if(K)break;S+=x.decode(q,{stream:!0}),M(!1)}m||(S+=x.decode(),M(!0),c?.())}catch(w){if(m||w instanceof DOMException&&w.name==="AbortError")return;a?.(w instanceof Error?w:new Error(String(w)))}}function j(){m=!0,g?.abort(),g=null,d.clear()}function L(y,_){let w=d.get(y)??new Set;w.add(_),d.set(y,w)}function N(y,_){d.get(y)?.delete(_)}return{connect:P,close:j,addEventListener:L,removeEventListener:N}}function p$(e,t){throw U("createTunnelEventStream")}var eP="/_kortix/viewer",as=6e4,sn=new Map;function tP(){sn.clear(),hr.clear()}async function d$(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 Sm(e={}){let t=e.path??eP,n=e.fetch??((s,i)=>fetch(s,i)),r=sn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let o=d$(t,n).then(s=>{let i=s?.expires_at?Date.parse(s.expires_at):Number.NaN,a=Number.isFinite(i)?i-as:Date.now()+as;return sn.set(t,{session:s,expiresAt:a}),s});return sn.set(t,{session:r?.session??null,expiresAt:0,inflight:o}),o}function nP(e={}){let t=e.path??eP;return Object.assign(async()=>(await Sm(e))?.access_token??null,{invalidate:n=>{let r=sn.get(t);r&&!r.inflight&&r.session?.access_token===n&&sn.delete(t)}})}var hr=new Map;async function g$(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let s=await n.json().catch(()=>null);s?.error==="app_not_linked"&&console.warn(`[kortix] ${String(s.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let o=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return hr.set(e,{token:r.token,refreshAt:Number.isFinite(o)?o-as:Date.now()+as}),r.token}catch{return null}}function wm(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((o,s)=>fetch(o,s));return async(o={})=>{let s=hr.get(n);if(s instanceof Promise)return s;if(s&&!o.forceRefreshToken&&s.refreshAt>Date.now())return s.token;let i=g$(n,r).then(a=>(a===null&&hr.delete(n),a));return hr.set(n,i),i}}function rP(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("kortixBinding needs the App origin: pass { origin } outside a browser.");return{url:`${oe(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:wm({audience:e,fetch:t.fetch})}}var rt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},de=e=>typeof e=="string"&&e.length>0?e:null;function oP(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function cs(e){if(!e||typeof e!="object")return null;let t=e,n=de(t.sub)??de(t.subject)??de(t.user_id)??de(t.userId);return n?{userId:n,email:de(t.email),name:de(t.name),picture:de(t.picture)??de(t.pictureUrl),groups:oP(t.groups),groupIds:oP(t.group_ids??t.groupIds),role:de(t.role),accountId:de(t.account_id)??de(t.accountId),projectId:de(t.project_id)??de(t.projectId)}:null}function iP(e,t={}){let n=cs(e);if(!n)throw new rt("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:o}=t;if(r&&!r.some(s=>n.groups.includes(s)||n.groupIds.includes(s)))throw new rt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(o&&!o.some(s=>n.role===s))throw new rt("forbidden",`Only ${o.join(" or ")||"no role"} members may do this.`);return n}var m$=60,Am=new Map;function aP(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function sP(e){return JSON.parse(new TextDecoder().decode(aP(e)))}async function f$(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),o=e.slice(n+1),s=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(o),i=>i.charCodeAt(0))):decodeURIComponent(o);return JSON.parse(s)}if(/^https?:\/\//.test(e)){let n=Am.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>Am.delete(e)),Am.set(e,n)),n}return JSON.parse(e)}async function cP(e,t={}){let n=y=>{throw new rt("unauthenticated",`Kortix sign-in token refused: ${y}.`)},r=t.jwks??Ve("KORTIX_AUTH_JWKS"),o=t.issuer??Ve("KORTIX_AUTH_ISSUER"),s=t.audience??Ve("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(s!==!1&&!s)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,c,p]=i,d,g;try{d=sP(a),g=sP(c)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await f$(r,t.fetch??((y,_)=>fetch(y,_)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(y=>y.kty==="EC"&&(d.kid===void 0||y.kid===d.kid));if(f.length===0)return n("unknown key");let b=new TextEncoder().encode(`${a}.${c}`),P;try{P=aP(p)}catch{return n("malformed")}let j=!1;for(let y of f)try{let{kid:_,alg:w,use:D,key_ops:T,...x}=y,S=await crypto.subtle.importKey("jwk",x,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},S,P,b)){j=!0;break}}catch{}if(!j)return n("bad signature");let L=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+m$<L)return n("expired");if(o&&g.iss!==o)return n("wrong issuer");if(s){let y=g.aud;if(!(y===s||Array.isArray(y)&&y.includes(s)))return n("wrong audience")}let N=cs(g);return N||n("no subject")}function vm(e){let t=e.agents.map(y$),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 y$(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function km(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>po(n?{...r,mode:null}:r))}function lP(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=km(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 uP=vm;function pP(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Rm(e){return{providerID:"kortix",modelID:e}}function dP(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 Rm(n)}var Cm=[{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"poe",env:["POE_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"infer",env:["INFER_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"bee",env:["BEE_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]}];function Im(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function b$(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function gP(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 ue(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 mP(e){return e.reduce((t,n)=>{let r=Im(n)??0,o=Im(t)??0;return r!==o?r>o?n:t:ue(n.id)>ue(t.id)?n:t})}function Tm(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,o=new Set;for(let[,s]of gP(e,b$)){let a=[...gP(s,p=>p.family||p.id).values()].map(mP),c=a.filter(p=>{let d=Im(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[mP(a)])o.add(p.id)}return o}function ls(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=>ue(r.id)>0)?n.filter(r=>ue(r.id)>0):n}function br(e){let t;for(let n of ls(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&ue(n.id)>ue(t.id))&&(t=n)}return t}var _$={"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 fP(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var P$=(()=>{let e=new Map;for(let{id:n,env:r}of Cm)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=>fP(s)===n)??o[0])}return t})();function yP(e){let t=_$[e.id];if(t)return t;let n=e.env??[],r=n.length===1?P$.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[fP(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function Mm(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var x$=["low","medium","high"];function hP(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:[...x$]}: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 bP=Cm;var Em={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var us=[{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"],...Em,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"],...Em,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"],...Em,max_price:{prompt:3.3,completion:16.5}}}],UH=new Map(us.map(e=>[e.id,e]));var _P=us.map(e=>e.id),PP=(us.find(e=>e.tier==="flagship")??us[0]).id,xP="deepseek-v4.1-flash";var wP=bP.map(e=>({id:e.id,authRequirement:yP(e)})),_r=new Set(["kortix"]),Om=new Set(["kortix"]);function an(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 S$(e){if(!e)return!1;let t=an(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 w$(e){let t=an(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(o=>!Om.has(o.id)),connected:r.filter(o=>!Om.has(o))}}function A$(e,t,n){let r=an(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)&&Mm(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 v$=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function k$(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 Dm="opencode";function R$(e){return e.cost?.input===0&&e.cost?.output===0}function SP(e){return e===Dm?Number.MAX_SAFE_INTEGER:v$.get(e)??Number.MAX_SAFE_INTEGER-1}function C$(e,t){let n=T$(t),r={},o=(e.providers??[]).map(s=>{let i=(s.models??[]).filter(a=>a.status!=="deprecated");return s.id===Dm&&!n.has(Dm)?{...s,models:i.filter(R$),keyless:!0}:{...s,models:i,keyless:!1}}).filter(s=>(s.keyless||n.has(s.id))&&!Om.has(s.id)&&(s.models?.length??0)>0).sort((s,i)=>SP(s.id)-SP(i.id)).map(s=>{let i=[...s.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||ue(p.id)-ue(c.id)),a=br(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=k$(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 I$(e,t){if(!e)return t;if(!t)return e;let n=an(e),r=an(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 T$(e){let t=new Set;for(let n of wP)Mm(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 E$(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=hP({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 M$(e,t){return w$(A$(an(e),t,wP))}function AP(e){if(e.gatewayEnabled)return e.modelPicker?E$(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?M$(e.runtimeProviders,t):void 0;return I$(e.llmCatalogProviders?C$(e.llmCatalogProviders,t):void 0,S$(n)?n:void 0)}function O$(e){return"capabilities"in e&&e.capabilities!=null}function ps(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function vP(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"?!_r.has(i.id):_r.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(O$(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:pP({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 kP(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var D$=new Set([PP]),j$="kortix",RP="codex",$$=new Set(_P);function U$(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function cn(e){return D$.has(e.modelID)}function L$(e){return Tm(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function CP(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=L$(e.catalogModels),o=kP(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===j$){let d=U$(i.modelID,i.provider),g=d===RP?t?.has(RP)??!1:t?.has(d)??!1;if($$.has(i.modelID))return!n||i.modelID===xP;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=o.get(a);if(!m?.releaseDate)return cn(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return cn(i)}catch{return cn(i)}return!1}if(c==="show"||r.has(a))return!0;let p=o.get(a);if(!p?.releaseDate)return cn(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return cn(i)}catch{return cn(i)}return!1}}function IP(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 TP(e,t){if(!e||_r.has(e.providerID)||ue(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>ue(i.modelID)>0))return e;let r=i=>ue(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??br(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!s||s===e.modelID?e:{...e,modelID:s}}function EP(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??e?.platformDefault;return n?Rm(n):void 0}function MP(e){let{models:t,providers:n}=e,r=c=>ps(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 b={providerID:m.id,modelID:f};if(r(b))return b}for(let b of ls(Object.keys(m.models).map(P=>({id:P})))){let P={providerID:m.id,modelID:b.id};if(r(P))return P}}}})(),i=o(e.picks??[]),a=i??o([e.serverDefault,e.globalDefault,e.agentModel,s]);return{model:TP(a,t),explicit:i,fallback:s}}return FP(F$);})();
|