@kortix/sdk 0.14.5 → 0.14.6
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 +13 -12
- package/dist/browser/session-sync/server-transcript-mirror.d.ts +6 -0
- package/dist/browser/session-sync/server-transcript-mirror.d.ts.map +1 -1
- package/dist/browser/session-sync/server-transcript-mirror.js +6 -0
- package/dist/browser/session-sync/server-transcript-mirror.js.map +1 -1
- package/dist/browser/session-sync/session-sync-registry.d.ts +9 -6
- package/dist/browser/session-sync/session-sync-registry.d.ts.map +1 -1
- package/dist/browser/session-sync/session-sync-registry.js +17 -8
- package/dist/browser/session-sync/session-sync-registry.js.map +1 -1
- package/dist/core/client/kortix.d.ts +2 -0
- package/dist/core/client/kortix.d.ts.map +1 -1
- package/dist/core/client/project-core.d.ts.map +1 -1
- package/dist/core/client/session-handle.d.ts +1 -0
- package/dist/core/client/session-handle.d.ts.map +1 -1
- package/dist/core/client/session-lifecycle-security.d.ts +10 -2
- package/dist/core/client/session-lifecycle-security.d.ts.map +1 -1
- package/dist/core/client/session-lifecycle-security.js +10 -2
- package/dist/core/client/session-lifecycle-security.js.map +1 -1
- package/dist/core/rest/projects-client/change-requests.d.ts +6 -0
- package/dist/core/rest/projects-client/change-requests.d.ts.map +1 -1
- package/dist/core/rest/projects-client/change-requests.js.map +1 -1
- package/dist/core/rest/projects-client/git-history.d.ts +12 -0
- package/dist/core/rest/projects-client/git-history.d.ts.map +1 -1
- package/dist/core/rest/projects-client/git-history.js.map +1 -1
- package/dist/core/rest/projects-client/projects.d.ts +5 -3
- package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
- package/dist/core/rest/projects-client/projects.js +0 -1
- package/dist/core/rest/projects-client/projects.js.map +1 -1
- package/dist/core/rest/projects-client/session-reminders.d.ts +2 -0
- package/dist/core/rest/projects-client/session-reminders.d.ts.map +1 -1
- package/dist/core/rest/projects-client/session-reminders.js +4 -0
- package/dist/core/rest/projects-client/session-reminders.js.map +1 -1
- package/dist/core/rest/projects-client/sessions.d.ts +17 -2
- package/dist/core/rest/projects-client/sessions.d.ts.map +1 -1
- package/dist/core/rest/projects-client/sessions.js +3 -0
- package/dist/core/rest/projects-client/sessions.js.map +1 -1
- package/dist/core/session/open-bundle.d.ts +2 -0
- package/dist/core/session/open-bundle.d.ts.map +1 -1
- package/dist/core/session/open-bundle.js +2 -0
- package/dist/core/session/open-bundle.js.map +1 -1
- package/dist/core/session-log/shell-exit.d.ts +18 -0
- package/dist/core/session-log/shell-exit.d.ts.map +1 -0
- package/dist/core/session-log/shell-exit.js +52 -0
- package/dist/core/session-log/shell-exit.js.map +1 -0
- package/dist/core/session-log/source.d.ts +0 -4
- package/dist/core/session-log/source.d.ts.map +1 -1
- package/dist/core/session-log/source.js +4 -9
- package/dist/core/session-log/source.js.map +1 -1
- package/dist/core/session-log/store.d.ts.map +1 -1
- package/dist/core/session-log/store.js +8 -2
- package/dist/core/session-log/store.js.map +1 -1
- package/dist/core/session-sync/saved-transcript.d.ts +21 -20
- package/dist/core/session-sync/saved-transcript.d.ts.map +1 -1
- package/dist/core/session-sync/saved-transcript.js +16 -18
- package/dist/core/session-sync/saved-transcript.js.map +1 -1
- package/dist/core/turns/tools/tool-outcome.d.ts.map +1 -1
- package/dist/core/turns/tools/tool-outcome.js +28 -3
- package/dist/core/turns/tools/tool-outcome.js.map +1 -1
- package/dist/core/turns/tools/web-helpers.d.ts +3 -0
- package/dist/core/turns/tools/web-helpers.d.ts.map +1 -1
- package/dist/core/turns/tools/web-helpers.js +5 -0
- package/dist/core/turns/tools/web-helpers.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/kortix.esm.min.js +33 -33
- package/dist/kortix.global.js +33 -33
- package/dist/react/use-reminders.d.ts +32 -2
- package/dist/react/use-reminders.d.ts.map +1 -1
- package/dist/react/use-reminders.js +15 -5
- package/dist/react/use-reminders.js.map +1 -1
- package/dist/react/use-session-log.d.ts +7 -9
- package/dist/react/use-session-log.d.ts.map +1 -1
- package/dist/react/use-session-log.js +9 -13
- package/dist/react/use-session-log.js.map +1 -1
- package/dist/react/use-session-sync.d.ts +10 -7
- package/dist/react/use-session-sync.d.ts.map +1 -1
- package/dist/react/use-session-sync.js +24 -8
- package/dist/react/use-session-sync.js.map +1 -1
- package/dist/react/use-session.d.ts.map +1 -1
- package/dist/react/use-session.js +6 -5
- 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 ai=Object.defineProperty;var Wk=Object.getOwnPropertyDescriptor;var Hk=Object.getOwnPropertyNames;var Vk=Object.prototype.hasOwnProperty;var zk=(e,t)=>{for(var n in t)ai(e,n,{get:t[n],enumerable:!0})},Yk=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Hk(t))!Vk.call(e,s)&&s!==n&&ai(e,s,{get:()=>t[s],enumerable:!(r=Wk(t,s))||r.enumerable});return e};var Jk=e=>Yk(ai({},"__esModule",{value:!0}),e);var nB={};zk(nB,{ABORT_REASONS:()=>mx,ABORT_REASONS_NOT_YET_EMITTED:()=>t0,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>bi,ACTIVE_INSTANCE_COOKIE:()=>Kr,ANALYTICS_UNAVAILABLE_CODE:()=>_i,ATTACHMENT_PART_REF_PREFIX:()=>jx,ApiError:()=>x,AuthError:()=>re,BillingError:()=>et,CAPTURE_DEVICE_DEFAULTS:()=>NO,CAPTURE_EXCLUSION_GROUPS:()=>LO,CAPTURE_FRAME_INTERVALS_MS:()=>UO,CAPTURE_LAYERS:()=>jO,CAPTURE_MAX_HEIGHTS:()=>FO,CAPTURE_RETENTION_LIMITS:()=>$O,CONNECTION_FAULT_GRACE_MS:()=>qx,CONNECTOR_POLL_FIRST_DELAY_MS:()=>Ix,CONNECTOR_POLL_INTERVAL_MS:()=>Ex,CONNECTOR_POLL_WINDOW_MS:()=>Mx,CONTEXT_TOOLS:()=>PP,COST_MARKUP:()=>vy,ConnectorApprovalPendingError:()=>Ps,ConnectorCallError:()=>Ln,ConnectorPageLimitError:()=>xs,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>xP,DEFAULT_NOTIFICATION_PREFERENCES:()=>iI,DEFAULT_TRANSCRIPT_OPTIONS:()=>Kf,DESTRUCTIVE_PHASES:()=>kx,FEATURE_DISABLED_CODE:()=>Dt,FEATURE_FLAG_KEYS:()=>Iv,FEATURE_NOT_SUPPORTED_CODE:()=>mi,FILE_VERBS:()=>mt,FileExistsError:()=>rn,HeadlessAuthError:()=>Yt,HostBoundaryError:()=>Wr,IMPERSONATION_HEADER:()=>mh,INBOX_NOTIFICATION_KINDS:()=>oI,INBOX_OBSERVATION_MAX_MS:()=>Yo,INITIAL_SETTLED_CONNECTION:()=>oF,INSTANCE_SCOPED_ROUTES:()=>fx,KNOWN_TOOL_KINDS:()=>Fh,KORTIX_TRANSCRIPT_SCHEMA:()=>ke,KortixMemberError:()=>yt,MAX_PROMPT_ATTACHMENTS_BYTES:()=>RA,MAX_PROMPT_ATTACHMENT_BYTES:()=>ul,MAX_PROMPT_ATTACHMENT_FILES:()=>Oh,MEMORY_VERBS:()=>h$,MODEL_NOT_SERVABLE_CODE:()=>fi,NO_GROUP_ACTIVITY_TOOLS:()=>Y_,OPTIMISTIC_ABORT_MAX_MS:()=>Jo,OPTIMISTIC_COMPACTION_MAX_MS:()=>_F,OPTIMISTIC_RECEIPT_MAX_MS:()=>Vo,PERSISTED_QUERY_CACHE_VERSION:()=>DJ,PLUMBING_TOOLS:()=>KP,PREVIEW_PROBE_TIMEOUT_MS:()=>JU,PROJECT_ACTIONS:()=>Q,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>uR,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>lR,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>n_,PROVISION_IN_FLIGHT_CODE:()=>yi,PROVISION_STREAM_UNTERMINATED_CODE:()=>Rh,PublicSessionShareError:()=>Ds,REPOSITORY_DISCONNECTED_CODE:()=>An,REVIEW_CONTROL_ACTIONS:()=>SC,RUNTIME_NOT_READY_MARKERS:()=>g0,RUNTIME_PERMISSION_CAPABILITIES:()=>uI,RUNTIME_PERMISSION_REPLIES:()=>lI,RequestTooLargeError:()=>bt,RuntimeNotReadyError:()=>tn,SANDBOX_FS_ROOTS:()=>Po,SANDBOX_PORTS:()=>Ke,SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE:()=>hi,SERVER_COMPACTION_REVALIDATE_MS:()=>Vx,SERVER_OBSERVATION_MAX_MS:()=>zo,SESSION_LIST_STATUS:()=>MF,SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES:()=>ti,SESSION_LOG_MINOR:()=>_e,SESSION_LOG_SCHEMA:()=>ce,SESSION_NOTICE:()=>jF,STANDALONE_TOOLS:()=>J_,STREAM_OBSERVATION_MAX_MS:()=>Sn,SandboxNotReadyError:()=>qr,SessionNotReadyError:()=>Ct,SessionStartError:()=>Ts,TRIGGER_CONTROL_ACTIONS:()=>_C,TURN_END_LEDGER_LAG_MS:()=>pF,TURN_ERROR_CODES:()=>I_,WAKE_ESCALATION_COOLDOWN_MS:()=>kF,WAKE_MAX_RESTARTS:()=>wF,WAKE_NO_PROGRESS_MS:()=>xF,WIRE_ID_BACKDATE_MS:()=>mo,WIRE_ID_CLOCK_TOLERANCE:()=>ct,WIRE_ID_TIME_MASK:()=>Ve,WIRE_ID_TIME_SCALE:()=>Xt,WIRE_MESSAGE_ID:()=>bb,__getConfigResolver:()=>Zk,__setConfigResolver:()=>Xk,abortErrorReason:()=>n0,acceptAccountInvite:()=>ls,acceptAccountInviteAndLand:()=>Wi,acceptEnterpriseOffer:()=>tp,acceptInvite:()=>D0,accountInviteLanding:()=>vh,actReviewItem:()=>wd,activateConnection:()=>hc,addComputerToProject:()=>Sc,addGroupMembers:()=>Jp,addMarketplaceSource:()=>yg,addRoomPerson:()=>qd,addRoomSession:()=>Bd,advanceWakeEscalation:()=>RF,allDescendantIds:()=>MP,appendPreviewToken:()=>qU,approveCaptureDeviceGrant:()=>Df,approveCaptureEnrollment:()=>Sf,approveProjectAccessRequest:()=>ka,approveTask:()=>_E,archiveProject:()=>Dn,assignTicket:()=>AE,attachGroupToProject:()=>Da,authMfa:()=>lo,authUser:()=>io,authenticatedFetch:()=>$,authenticatedRequest:()=>Un,authorizePreviewUrl:()=>YU,backendApi:()=>c,bindSlackIdentity:()=>BR,bindTeamsIdentity:()=>KR,brokerProjectSecretRequest:()=>Ha,browserKeyValueStorage:()=>NU,buildInstancePath:()=>hx,buildPresentationTemplateImageUrl:()=>eF,buildPresentationTemplatePdfUrl:()=>ZU,buildPreviewAuthEndpoint:()=>$y,buildPublicTemplateUrl:()=>vU,buildRuntimePresentationConversionUrl:()=>Kx,buildSandboxTemplate:()=>nl,buildScrapeFailureResults:()=>$P,buildStaticFileHealthPreviewUrl:()=>xO,buildStaticFileLocalUrl:()=>PO,buildStaticFilePreviewUrl:()=>SO,buildStaticFileServicePath:()=>_S,buildTunnelEventStreamUrl:()=>UN,buildWebProxyUrl:()=>RO,bulkActReviewItems:()=>kd,bulkDeletePolicies:()=>IC,bulkImportPolicies:()=>EC,burstSummary:()=>Bo,burstSummaryLabel:()=>qP,burstWorkLabel:()=>my,callConnector:()=>kt,canManageBilling:()=>g_,canOfferTopup:()=>ER,cancelAccountDeletion:()=>yT,cancelAccountInvite:()=>Bi,cancelSandbox:()=>C0,cancelSandboxUpdate:()=>z0,cancelScheduledChange:()=>zu,cancelSubscription:()=>Wu,captureHealthBucket:()=>GO,changeRequestControlsFrom:()=>P_,checkAccessEmail:()=>aU,checkMcpServerSignIn:()=>yA,childMapByParent:()=>xj,claimComputer:()=>Z0,claimNext:()=>HS,claimPerSeatBilling:()=>LR,claimWarmProjectSession:()=>Hl,classifyPart:()=>ny,classifyPreviewProbeStatus:()=>Bx,classifyPtyClose:()=>Cb,classifySessionLogMessage:()=>Ow,classifyTurn:()=>Do,cleanErrorMessage:()=>Lj,cleanResultSnippet:()=>Nj,cleanWorkerOutput:()=>p$,clearImpersonationSession:()=>wi,clearKortixAppViewerCache:()=>lk,clearModelDefault:()=>Iu,clearSessionFresh:()=>BA,closeChangeRequest:()=>kl,closeMilestone:()=>eM,collectTurnParts:()=>Rj,commentTicket:()=>CE,commitSessionChanges:()=>Rl,compactionExpiryAtMs:()=>SF,compactionTurnInfo:()=>wL,compareForDisplayAt:()=>Lo,compareMessagesForDisplay:()=>Pj,compareSemver:()=>zO,completeInFlight:()=>VS,completeSlackInstall:()=>up,completeTeamsInstall:()=>pp,composerSelectableAgents:()=>nh,computeStatusFromPart:()=>xy,configureAutoTopup:()=>Xu,configureKortix:()=>Xr,confirmCheckoutSession:()=>qu,connectEmail:()=>bp,connectSlack:()=>cp,connectTelegram:()=>VR,connectionFromHealth:()=>sF,connectionIsFaulted:()=>rF,connectionSharedWithEveryone:()=>nA,connectorConnect:()=>Ih,connectorFinalize:()=>Eh,connectorHeadline:()=>EU,contactEnterpriseSales:()=>np,contextLabelForTool:()=>Yj,contextToolSummary:()=>vD,contextToolTrigger:()=>AD,convertPresentationToGoogleSlides:()=>RT,convertRuntimePresentation:()=>tF,copyFile:()=>wr,costExportUrl:()=>sp,countLiveInboxPrompts:()=>gF,countReviewItemsBySegment:()=>iC,createAccount:()=>Ii,createAccountAuditWebhook:()=>og,createAccountSecretResource:()=>ec,createAccountToken:()=>Vd,createApp:()=>bg,createAppAccessSession:()=>Rg,createAppDeployment:()=>Tg,createAppToken:()=>xg,createAppVolume:()=>Hg,createAppVolumeSnapshot:()=>Jg,createArtifactKind:()=>hL,createAssignment:()=>yd,createAuditWebhook:()=>aT,createBackup:()=>$0,createCaptureEnrollmentToken:()=>hf,createCheckoutSession:()=>Ku,createConnector:()=>Dc,createConnectorLinkInfoCache:()=>CU,createFile:()=>xr,createGatewayKey:()=>$p,createGroup:()=>Hp,createHttpSessionSyncController:()=>Qw,createInstance:()=>J0,createKortix:()=>KS,createKortixPty:()=>qm,createKortixSession:()=>po,createMarketplaceInstallSession:()=>DT,createMilestone:()=>XE,createModelVisibility:()=>Lk,createOAuthClient:()=>pd,createPerSeatCheckout:()=>jR,createPersistedQueryCache:()=>FU,createPolicy:()=>RC,createPortalSession:()=>Gu,createProject:()=>ta,createProjectAgent:()=>UE,createProjectCliToken:()=>Xd,createProjectRepo:()=>na,createProjectResourceGrant:()=>Ua,createProjectSession:()=>Rt,createProjectSkill:()=>ca,createProjectTrigger:()=>fu,createPromptAttachmentController:()=>pf,createRole:()=>rd,createRoom:()=>jd,createSSEStream:()=>FN,createSandbox:()=>P0,createSandboxShare:()=>Ad,createSandboxTemplate:()=>Zc,createSavedCopyStore:()=>nR,createScimToken:()=>jC,createServiceAccountApi:()=>rT,createSessionPrompt:()=>zn,createSessionPublicShare:()=>ql,createSessionQueue:()=>GS,createSessionReminder:()=>Td,createSsoGroupMapping:()=>zC,createTask:()=>fE,createTicket:()=>wE,createTunnelEventStream:()=>NN,createWarmSessionPool:()=>kN,currentSavedCopyStore:()=>Ol,declineAccountInvite:()=>Hi,declineInvite:()=>j0,deleteAccountImmediately:()=>hT,deleteAccountSecretResource:()=>rc,deleteApp:()=>Pg,deleteAppDeployment:()=>jg,deleteAuditWebhook:()=>lT,deleteBackup:()=>F0,deleteConnector:()=>Uc,deleteConnectorCredential:()=>Gc,deleteCredential:()=>aM,deleteCustomLlmProvider:()=>ir,deleteDriveFile:()=>ZT,deleteEnv:()=>Nm,deleteFile:()=>Et,deleteGatewayBudget:()=>jp,deleteGitHubInstallation:()=>Sa,deleteGroup:()=>zp,deleteInstance:()=>Q0,deleteKortixProject:()=>VE,deleteMilestone:()=>nM,deleteOAuthClient:()=>md,deletePersonalProjectSecret:()=>Qa,deletePolicy:()=>TC,deleteProjectAgent:()=>NE,deleteProjectProviderOAuth:()=>za,deleteProjectResourceGrant:()=>Fa,deleteProjectSecret:()=>jn,deleteProjectSession:()=>ru,deleteProjectTrigger:()=>hu,deletePromptAttachment:()=>Bt,deleteRole:()=>id,deleteSandboxTemplate:()=>tl,deleteServiceAccountApi:()=>oT,deleteSessionPrompt:()=>Ql,deleteSessionReminder:()=>Ls,deleteSessionReminders:()=>Ed,deleteSsoGroupMapping:()=>YC,deleteSsoProvider:()=>HC,deleteTask:()=>bE,deleteTicket:()=>TE,denyCaptureDeviceGrant:()=>jf,denyCaptureEnrollment:()=>Pf,describeAccountInvite:()=>Gi,describeConnectorTool:()=>ys,destroyAppMachine:()=>Kg,destroyAppVolume:()=>zg,detachGroupFromProject:()=>La,detectLocalhostUrls:()=>mS,directSubsessions:()=>$F,disableServiceAccountApi:()=>sT,disconnectEmail:()=>Sp,disconnectGitHubApp:()=>LU,disconnectSlack:()=>gp,disconnectTelegram:()=>YR,discoverConnectionOAuth2:()=>iA,discoverConnectionOAuth2Resource:()=>aA,discoverConnectorAuth:()=>jc,discoverLocalSandbox:()=>v0,dismissDriveConflict:()=>WT,downloadAccountAudit:()=>wU,downloadDriveFile:()=>VT,dropClientForUrl:()=>hM,dropPublicClientForUrl:()=>SM,editQueued:()=>QS,editSessionPrompt:()=>Xl,enqueue:()=>WS,ensurePmSession:()=>LE,ensurePreviewSessionCookie:()=>Nx,ensureProjectConnectorConnection:()=>rA,ensureSandbox:()=>wx,ensureWarmProjectSession:()=>Wl,env:()=>Ab,exchangeCode:()=>ro,execInApp:()=>Gg,exportAccountAudit:()=>rg,extractGatewayErrorDetails:()=>Se,extractInstanceRoute:()=>_n,extractSkillBaseDir:()=>cx,extractSkillContent:()=>k$,extractSkillFiles:()=>ax,extractWorkerPreview:()=>g$,failInFlight:()=>zS,fallbackBusyRowAfterTurnId:()=>KL,familyForTool:()=>fn,featureDisabledKey:()=>pi,featureFlags:()=>Im,fetchAccountStateWithToken:()=>MR,fetchAccountsWithToken:()=>Tv,fetchAttachmentPart:()=>BU,fetchCostExportCsv:()=>NR,fetchKortixAppViewer:()=>Xy,fetchProjectArchive:()=>cl,fetchProjectFileRaw:()=>AA,fetchProjectsForAccountWithToken:()=>Nv,fetchSessionAttachment:()=>Cm,fileDownloadRequest:()=>Yb,filePhase:()=>y$,fileVerb:()=>f$,files:()=>sS,finalizeAppArtifact:()=>Fs,finalizeConnectorSetupLink:()=>mU,findActiveTranscriptShare:()=>dR,findFiles:()=>Sr,findLastTextPart:()=>Cj,findSessionAttachments:()=>HI,findText:()=>Pr,fireProjectTrigger:()=>bu,fixSandboxWithAgent:()=>Xc,flattenModels:()=>Ek,flattenThought:()=>CL,forkAppVolume:()=>Xg,formatBillingErrorForUI:()=>gi,formatCost:()=>r$,formatDuration:()=>ky,formatJsonFailureOutput:()=>$j,formatMessageDay:()=>DL,formatMessageExact:()=>jL,formatOpenCodeRuntimeError:()=>h0,formatRawOutput:()=>Fj,formatRuntimeError:()=>xx,formatTokens:()=>s$,formatTranscript:()=>ZS,freshSendHint:()=>HL,generateSessionId:()=>qS,getAccount:()=>Ei,getAccountAutomations:()=>hR,getAccountBranding:()=>Oi,getAccountDeletionStatus:()=>mT,getAccountState:()=>ju,getAccountStateMinimal:()=>Lu,getActiveInstanceIdFromCookie:()=>bx,getAdminProviderAnalytics:()=>xT,getAdminProviderDistribution:()=>bT,getAdminProviderFallback:()=>kT,getAdminRole:()=>_T,getAgentCardLabel:()=>vP,getAgentConfig:()=>AR,getAgentPersona:()=>BE,getAllVersions:()=>W0,getAnsweredQuestionParts:()=>Ij,getApp:()=>$s,getAppAccess:()=>kg,getAppAuthEnv:()=>wg,getAppDeployment:()=>Eg,getAppDeploymentLogs:()=>Mg,getApprovalLink:()=>OT,getAuthToken:()=>Ft,getAuthTokenWithRetry:()=>Qv,getAutoTopupSettings:()=>Qu,getAutoTopupSetupStatus:()=>DR,getBillingCreditBreakdown:()=>Fu,getBillingTierConfigurations:()=>Bu,getBillingTransactionsSummary:()=>Uu,getBillingUsageHistory:()=>Nu,getCaptureAssetUrl:()=>Mf,getCaptureChunkMedia:()=>Ef,getCaptureDays:()=>Cf,getCaptureDeviceGrant:()=>Of,getCaptureFrame:()=>If,getCapturePolicy:()=>xf,getCaptureStorage:()=>kf,getCaptureTimeline:()=>Af,getCaptureTimelineItems:()=>Rf,getCaptureWorkspace:()=>Lf,getChangeRequest:()=>bl,getChangeRequestDiff:()=>Sl,getChangeRequestMergePreview:()=>Pl,getChildSessionError:()=>ND,getChildSessionId:()=>Or,getChildSessionToolParts:()=>BD,getClient:()=>ut,getClientForUrl:()=>Me,getConnectStatus:()=>Kc,getConnectionOAuth2Application:()=>oA,getConnectionOAuth2Status:()=>dA,getConnectionPolicies:()=>gA,getConnectorCatalog:()=>Nt,getConnectorConfig:()=>Ec,getConnectorPolicies:()=>Tc,getConnectorSetupLink:()=>dU,getCostSummary:()=>FR,getCurrentInstanceIdFromPathname:()=>_x,getCurrentInstanceIdFromWindow:()=>o0,getCurrentProject:()=>ef,getDefaultAccountState:()=>Du,getDiagnostics:()=>HD,getDirectory:()=>kP,getDiscoverConnector:()=>Ss,getDiscoverIntegration:()=>SA,getDriveFileUrl:()=>Zg,getEmailInstallation:()=>hp,getEmailMode:()=>_p,getEnterpriseDemo:()=>pT,getFileStatus:()=>br,getFileWithDir:()=>Yf,getFilename:()=>wP,getFolderAccess:()=>NT,getFullChangelog:()=>vx,getGatewayBreakdown:()=>Ip,getGatewayBudgets:()=>Op,getGatewayErrors:()=>Mp,getGatewayKeys:()=>Lp,getGatewayLog:()=>Rp,getGatewayOverview:()=>Cp,getGatewayRoutingPolicy:()=>xp,getGatewaySeries:()=>Tp,getGatewaySessions:()=>Ep,getGitHubAppStatus:()=>MU,getGitHubInstallation:()=>da,getGoogleAuthUrl:()=>AT,getGroup:()=>Wp,getHiddenToolParts:()=>jD,getImpersonationSession:()=>hh,getInvite:()=>O0,getJustavpsServerTypes:()=>Y0,getKortixProject:()=>GE,getKortixProjectBySession:()=>WE,getKortixPtyWebSocketUrl:()=>Hm,getLatestSandboxVersion:()=>G0,getMaintenanceConfig:()=>bU,getManagedGitBackend:()=>Pa,getManagedGitStatus:()=>Lv,getMarketplaceCatalogItem:()=>gg,getMarketplaceCatalogItemFile:()=>mg,getMfaRequired:()=>$C,getMilestone:()=>JE,getMobileClientPolicy:()=>Bf,getModelDefaults:()=>Cu,getMyCaptureFrame:()=>Nf,getMyCaptureTimeline:()=>Ff,getNotificationPreferences:()=>am,getOAuthClient:()=>ud,getOAuthConsentRequest:()=>uU,getOpenCodeConfigInvalidError:()=>u0,getPartText:()=>MD,getPatPolicy:()=>eT,getPermissionForTool:()=>VD,getProject:()=>wt,getProjectActivity:()=>KE,getProjectCommit:()=>ml,getProjectCommitDiff:()=>fl,getProjectDetail:()=>In,getProjectDrive:()=>FT,getProjectFileHistory:()=>yl,getProjectGitConnectionState:()=>Kv,getProjectGitToken:()=>ea,getProjectLlmCatalog:()=>En,getProjectLlmCatalogProviders:()=>Mv,getProjectModelAccess:()=>nr,getProjectModelPicker:()=>Mn,getProjectQuota:()=>jv,getProjectSandboxHealth:()=>$n,getProjectSandboxProviderTransition:()=>$v,getProjectSession:()=>Wn,getProjectSessionConfigState:()=>iu,getProjectSessionScope:()=>lu,getProrationPreview:()=>Yu,getProviders:()=>b0,getProxyBaseUrl:()=>wO,getPublicClientForUrl:()=>bM,getPublicMarketplaceItem:()=>oU,getPublicMarketplaceItemFile:()=>iU,getPublicSessionShare:()=>CT,getPublicSessionShareMessages:()=>TT,getPublicShareByToken:()=>hU,getPublicTemplate:()=>AU,getQuestionForTool:()=>zD,getReferralCode:()=>eC,getReferralStats:()=>rC,getRetryInfo:()=>o$,getRetryMessage:()=>i$,getReviewItem:()=>Pd,getReviewSummary:()=>Sd,getRolePermissions:()=>td,getRoleUsage:()=>nd,getRoom:()=>Ld,getRuntimeConfigInvalidError:()=>Ho,getSSHConnection:()=>B0,getSandbox:()=>S0,getSandboxById:()=>x0,getSandboxPortUrl:()=>_0,getSandboxProvisionStatus:()=>eU,getSandboxProvisionStreamUrl:()=>tU,getSandboxUpdateStatus:()=>q0,getSandboxUrl:()=>Oy,getSandboxUrlForExternalId:()=>Ie,getSecretSetupLink:()=>fU,getServerHealth:()=>xo,getServiceLogs:()=>dM,getSessionAudit:()=>Vl,getSessionCost:()=>n$,getSessionCostRecord:()=>Zn,getSessionDrives:()=>R_,getSessionHealth:()=>sf,getSessionLogPage:()=>Yl,getSessionMessageAuthors:()=>du,getSessionModelUsage:()=>gu,getSessionOpenBundle:()=>gR,getSessionOversight:()=>NC,getSessionParticipants:()=>Ll,getSessionPolicy:()=>JC,getSessionPreviewCandidates:()=>Bl,getSessionProviderSecretPool:()=>ac,getSessionTranscript:()=>zl,getSessionTranscriptSync:()=>Hn,getSessionTurn:()=>Vn,getSessionWatch:()=>$l,getShellModePart:()=>u$,getSlackChannelFile:()=>mp,getSlackInstallation:()=>ap,getSlackManifest:()=>dp,getSlackMode:()=>lp,getSsoProvider:()=>KC,getStaticFileHealthPath:()=>bS,getSupabaseAccessToken:()=>ds,getSupabaseAccessTokenWithRetry:()=>Th,getTask:()=>dE,getTaskStatus:()=>mE,getTelegramInstallation:()=>HR,getTemplate:()=>jT,getTicket:()=>PE,getToolInfo:()=>qD,getToolPrimaryArg:()=>To,getTranscriptFilename:()=>eP,getTurnCost:()=>Wo,getTurnError:()=>JL,getTurnErrorDetails:()=>XL,getTurnErrorRawText:()=>QL,getTurnStatus:()=>wy,getUsageRollup:()=>rp,getUserRolesWithToken:()=>PU,getVersionDiff:()=>hl,getWebPushPublicKey:()=>lm,getWorkingState:()=>zL,grantAccountSecretResource:()=>sc,grantSandboxProjectAccess:()=>E0,grantSecretToAgent:()=>CR,groupMessagesIntoTurns:()=>kj,groupShowSegments:()=>_y,groupSteps:()=>fy,hasDiffs:()=>a$,hasLocalhostUrls:()=>hO,hasPreviewTarget:()=>hS,hasRetryingAssistantTurn:()=>iy,heartbeatGapEvent:()=>qb,holdSessionPrompts:()=>tu,humanizeReviewActionPath:()=>qp,humanizeSearchQuery:()=>Tr,humanizeToolName:()=>Zf,impersonationHeaders:()=>ki,importSsoProviderFromMetadata:()=>GC,inboxObservationSupersedes:()=>dF,initialWakeEscalationState:()=>Fy,inputPath:()=>ve,installTemplate:()=>LT,interruptSessionPrompt:()=>Zl,invalidateTokenCache:()=>gs,inviteAccountMember:()=>Fi,inviteProjectMember:()=>Ta,inviteRepoCollaborator:()=>Xi,isAbortError:()=>Br,isAdminBypassEnabled:()=>Ph,isAgentPart:()=>RD,isAppRouteUrl:()=>gS,isAttachment:()=>OD,isAttachmentPartRef:()=>Lx,isAuthFailure:()=>jt,isBillingError:()=>di,isCompactionPart:()=>CD,isConfigured:()=>Zr,isContextTool:()=>kD,isDestructivePhase:()=>K0,isEmptyConversation:()=>Qy,isEmptyShowPart:()=>Ys,isErrorOutput:()=>Ej,isExternalUrl:()=>IO,isFeatureDisabledError:()=>ui,isFilePart:()=>Jf,isImpersonationSessionLive:()=>fh,isInstanceDetailPath:()=>r0,isInstanceScopedAppPath:()=>yx,isInternalLocalhostUrl:()=>AO,isInvisibleActivityPart:()=>xm,isInviteSent:()=>Gv,isLastUserMessage:()=>VL,isLegacyMigratedSession:()=>zx,isManagedGithubProject:()=>Ev,isNoGroupActivityTool:()=>Pm,isOfferedModel:()=>oi,isOpenCodeConfigInvalidError:()=>p0,isPaintableSavedCopy:()=>Jh,isPatchPart:()=>ID,isPersistableQueryKey:()=>UU,isPreviewUrl:()=>vO,isProxiableLocalhostUrl:()=>SS,isQuestionTool:()=>Sm,isReasoningPart:()=>we,isRepositoryDisconnectedError:()=>lh,isRetryableTurnError:()=>OP,isRuntimeConfigInvalidError:()=>Sx,isRuntimeNotReadyResponse:()=>Px,isRuntimeReady:()=>rf,isRuntimeStartingError:()=>y0,isSandboxNotReadyError:()=>bn,isSelectableAgent:()=>Qs,isServerReachable:()=>tf,isSessionAttachmentRef:()=>FI,isSessionFresh:()=>Tl,isSessionLogRestoreNote:()=>$w,isSessionStartError:()=>PR,isShellActivityTool:()=>DI,isShellMode:()=>sx,isShortOutput:()=>d$,isShowContentUnavailable:()=>aI,isShowPayloadEmpty:()=>ar,isSnapshotPart:()=>TD,isStandaloneActivityTool:()=>wm,isStepPart:()=>ED,isSubdomainPreviewUrl:()=>Hr,isTextPart:()=>Oe,isToolPart:()=>ee,isToolPartHidden:()=>LD,isTurnErrorCode:()=>gm,isUnderSandboxRoot:()=>Xm,isWebProxyUrl:()=>TO,isWireIdAheadOf:()=>Pb,kortixAppViewerToken:()=>uk,kortixBinding:()=>pk,kortixPty:()=>Eb,kortixToken:()=>Zy,latestPromptModel:()=>Fk,leaveAccount:()=>Yi,linkCaptureDevice:()=>ff,linkGitHubInstallation:()=>_a,linkRepository:()=>ua,listAccountAudit:()=>tg,listAccountAuditWebhooks:()=>sg,listAccountInvites:()=>Ni,listAccountMembers:()=>Ui,listAccountResourceGrants:()=>vC,listAccountSecretResources:()=>Za,listAccountSessions:()=>XC,listAccountTokens:()=>Hd,listAccounts:()=>Ti,listActions:()=>MC,listAdminSandboxes:()=>ST,listAgentIdentities:()=>Zp,listAllConnections:()=>dc,listAppAgents:()=>vg,listAppDeployments:()=>Ig,listAppMachines:()=>$g,listAppVolumeSnapshots:()=>Yg,listAppVolumes:()=>Wg,listApps:()=>_g,listAssignments:()=>fd,listAuditEvents:()=>uT,listAuditWebhooks:()=>iT,listBackups:()=>L0,listBillingTransactions:()=>$u,listCaptureDevices:()=>gf,listCaptureEnrollmentTokens:()=>yf,listCaptureEnrollments:()=>bf,listChangeRequests:()=>_l,listChannelBindings:()=>QR,listColumns:()=>IE,listConnectSections:()=>_A,listConnectToolkits:()=>hA,listConnections:()=>pc,listConnectorAccounts:()=>hs,listConnectorMoves:()=>Lc,listConnectorTools:()=>fs,listConnectors:()=>kc,listCostByProject:()=>UR,listCredentialEvents:()=>sM,listCredentials:()=>rM,listCustomLlmProviders:()=>sr,listDiscoverConnectors:()=>bs,listDiscoverIntegrations:()=>bA,listDiscoverSections:()=>Bc,listDriveConflicts:()=>GT,listDriveFiles:()=>HT,listDriveFolder:()=>A_,listDriveVersions:()=>eI,listEnv:()=>Um,listFeaturedMarketplaces:()=>dg,listFields:()=>ME,listFiles:()=>on,listFolderPrincipals:()=>qT,listGatewayLogs:()=>Ap,listGitHubInstallations:()=>ga,listGitHubRepositories:()=>fa,listGitHubRepositoryBranches:()=>ya,listGroupMembers:()=>Yp,listGroupProjectGrants:()=>xC,listGroups:()=>Gp,listKortixProjectSessions:()=>HE,listKortixProjects:()=>qE,listKortixPty:()=>Km,listLinkableGitHubInstallations:()=>ma,listManagedGitRepositories:()=>xa,listMarketplaceCatalogItems:()=>ug,listMarketplaceSources:()=>fg,listMarketplaces:()=>pg,listMemberGroups:()=>wC,listMemberProjectAccess:()=>kC,listMilestoneEvents:()=>QE,listMilestones:()=>YE,listMyAccountInvites:()=>qi,listNotifications:()=>om,listOAuthClients:()=>ld,listOAuthGrants:()=>Yd,listPendingApprovals:()=>Na,listPendingProjectInvites:()=>Ia,listPermissions:()=>_d,listPipedreamApps:()=>Fc,listPipedreamSections:()=>Nc,listPolicies:()=>AC,listProjectAccess:()=>Aa,listProjectAccessRequests:()=>wa,listProjectAgentIdentities:()=>ed,listProjectAgents:()=>$E,listProjectAudit:()=>ng,listProjectBranches:()=>dl,listProjectCliTokens:()=>Qd,listProjectCommits:()=>gl,listProjectDirectory:()=>ol,listProjectFiles:()=>sl,listProjectGroupGrants:()=>Oa,listProjectPolicies:()=>Vc,listProjectProviderOAuth:()=>Va,listProjectReminders:()=>Md,listProjectResourceGrants:()=>$a,listProjectSandboxTemplates:()=>Yc,listProjectSandboxes:()=>rl,listProjectSecrets:()=>qa,listProjectSessions:()=>At,listProjectSessionsPage:()=>Dl,listProjectSnapshots:()=>Jc,listProjectTriggerEventApps:()=>ku,listProjectTriggerEventTypes:()=>wu,listProjectTriggerRuns:()=>Pu,listProjectTriggers:()=>mu,listProjects:()=>xt,listProjectsForAccount:()=>Qi,listPublicMarketplaceItems:()=>rU,listPublicMarketplaces:()=>sU,listReferrals:()=>sC,listReviewItems:()=>bd,listRoles:()=>Xp,listRoomMessages:()=>Ud,listRoomPeople:()=>Wd,listRooms:()=>Dd,listSandboxProjectMembers:()=>I0,listSandboxShares:()=>vd,listSandboxes:()=>k0,listScimTokens:()=>DC,listServiceAccountsApi:()=>nT,listServiceTemplates:()=>pM,listServices:()=>uM,listSessionConnectRequests:()=>fA,listSessionCosts:()=>ip,listSessionDrives:()=>rI,listSessionPrompts:()=>Jl,listSessionProviderSecretPools:()=>cc,listSessionPublicShares:()=>Kl,listSessionReminders:()=>Cd,listSessionsNeedingInput:()=>Ba,listSignedInDevices:()=>ET,listSsoGroupMappings:()=>VC,listTaskEvents:()=>gE,listTasks:()=>pE,listTemplates:()=>DE,listTicketEvents:()=>xE,listTickets:()=>SE,listTriggerRuns:()=>Su,loadHttpSessionHistory:()=>Jw,loadPreviewUrlTemplate:()=>it,looksLikeError:()=>cy,looksLikeHtml:()=>Gj,looksLikeJsonPayload:()=>Uj,makeDriveFolder:()=>QT,mapApiReviewItem:()=>hC,markInstanceError:()=>X0,markNotificationsRead:()=>im,markRoomRead:()=>Nd,markSessionFresh:()=>Kn,maxWireIdClock:()=>Dm,memoryRelPath:()=>_$,mergeBurstSteps:()=>yy,mergeChangeRequest:()=>wl,messageCreatedAt:()=>TL,messageTime:()=>YP,migrateAdminSandboxProvider:()=>wT,mintWireMessageId:()=>fo,mintWireMessageIdAbove:()=>jm,mkdir:()=>un,modelInDefaultView:()=>$k,modelRefToKey:()=>kn,moveConnector:()=>$c,moveDriveFile:()=>XT,narrateFailedStep:()=>dy,narrateStep:()=>Ur,narrationToolName:()=>$r,narrowChatEvent:()=>Gb,newestWireIdClock:()=>xb,nextConnectorPollDelay:()=>IU,normalizeActivityToolName:()=>fe,normalizeAppPathname:()=>c0,normalizeCaptureAppId:()=>qO,normalizeCaptureDomain:()=>KO,normalizeExternalInput:()=>EO,normalizeName:()=>Z,normalizeToolName:()=>Xf,notifyHostSignal:()=>Jx,openChangeRequest:()=>xl,openEventStream:()=>bo,openStressTestStream:()=>kU,paginateConnector:()=>Hc,parseBillingError:()=>Rn,parseEmbeddedFailure:()=>Bj,parseFlagOverride:()=>zI,parseJsonFailure:()=>ly,parseLocalhostUrl:()=>Rr,parseMemoryView:()=>b$,parseOpenCodeErrorPayload:()=>l0,parsePresentationOutput:()=>x$,parseProxyHop:()=>nf,parseQuestionAnswersFromOutput:()=>Cy,parseReadOutput:()=>w$,parseRuntimeErrorPayload:()=>My,parseScrapeInputUrls:()=>LP,parseScrapeOutput:()=>UP,parseSubdomainUrl:()=>af,parseTaskRows:()=>m$,parseWebProxyUrl:()=>CO,parseWebSearchOutput:()=>uy,partOutcome:()=>$o,patchKortixProject:()=>zE,patchVerb:()=>P$,pickerProviderList:()=>Ik,pipedreamConnect:()=>Oc,pipedreamConnectConnection:()=>xc,pipedreamFinalize:()=>Wc,pipedreamFinalizeConnection:()=>wc,platformConfig:()=>I,pollConnectionOAuth2DeviceAuthorization:()=>pA,pollProjectProviderOAuth:()=>ps,postRoomMessage:()=>Fd,previewBillingPlan:()=>Zu,previewGatewayRoute:()=>vp,previewMfaRequired:()=>UC,previewSlackIdentity:()=>qR,previewTeamsIdentity:()=>GR,probeEffectivePermission:()=>ad,probeEffectivePermissions:()=>cd,probePreviewPort:()=>QU,projectArchiveRequest:()=>ll,projectCompacting:()=>bF,projectConfigAgentsToOpenCodeAgents:()=>_k,projectConfigAgentsToRuntimeAgents:()=>th,projectSessionConnection:()=>nF,projectSessionForRuntimeId:()=>UF,projectSessionStartSeed:()=>Au,projectWorking:()=>mF,provisionProject:()=>ra,provisionProjectStream:()=>Dv,provisionProjectWithToken:()=>Bv,proxyLocalhostUrl:()=>of,proxyUrlToInternal:()=>kO,purchaseCredits:()=>Ju,putConnectionOAuth2Application:()=>sA,putCustomLlmProvider:()=>or,rawErrorText:()=>Cr,reactivateSandbox:()=>T0,reactivateSubscription:()=>Hu,readBlob:()=>cn,readDriveFile:()=>zT,readFile:()=>an,readKortixMember:()=>si,readProjectFile:()=>al,readSavedSessionCopy:()=>ak,reasoningIsRunning:()=>Ko,rebuildProjectSnapshot:()=>Qc,reconcileConnection:()=>gc,reconcileMemberConnection:()=>mc,reconcileServices:()=>mM,recordPlatformLogout:()=>lU,recoverLinkResults:()=>Uo,recoverProjectSession:()=>su,refreshReferralCode:()=>tC,refreshSession:()=>Jt,registerAppArtifact:()=>Us,registerConnectionOAuth2Client:()=>cA,registerDeviceToken:()=>nm,registerService:()=>fM,registerWebPushSubscription:()=>um,rejectProjectAccessRequest:()=>va,relativizePath:()=>WD,releaseDeviceToken:()=>sm,reloadProjectSessionConfig:()=>au,reloadProjectSessionConfigStream:()=>cu,removeAccountAuditWebhook:()=>ag,removeAccountBrandingAsset:()=>Li,removeAccountMember:()=>Vi,removeGroupMember:()=>Qp,removeKortixPty:()=>Wm,removeMarketplaceSource:()=>hg,removeProjectSkill:()=>la,removeQueued:()=>JS,removeRoomPerson:()=>Gd,removeRoomSession:()=>Kd,renameConnection:()=>bc,renameFile:()=>vr,renameSandbox:()=>w0,reopenChangeRequest:()=>vl,reopenMilestone:()=>tM,reorderQueued:()=>XS,replaceColumns:()=>EE,replaceFields:()=>OE,replaceProjectRepository:()=>pa,replaceTemplates:()=>jE,replayTriggerRun:()=>xu,repositoryDisconnectedReason:()=>uh,requestAccountDeletion:()=>fT,requestChangesOnChangeRequest:()=>Al,requestProjectAccess:()=>qv,requestProjectConnector:()=>lg,requestProjectSecret:()=>cg,requestTopUp:()=>OR,requireKortixMember:()=>mk,resendAccountInvite:()=>Ki,resendPendingProjectInvite:()=>Ma,resetAccountBranding:()=>$i,resetClient:()=>_M,resetGatewayRoutingPolicy:()=>kp,resetPassword:()=>so,resetPublicClient:()=>PM,resetSandboxUpdateStatus:()=>V0,resolveApproval:()=>Ka,resolveComposerAgent:()=>hk,resolveComposerModel:()=>qk,resolveConnectorStart:()=>TU,resolveModelDefault:()=>Uk,resolvePublicShareUrl:()=>pR,resolveScrapeResults:()=>Wj,resolveWorkingTurn:()=>Py,resolvedPlan:()=>IR,restartAppMachine:()=>Bg,restartProjectSession:()=>Yn,restartSandbox:()=>A0,restoreAppVolume:()=>Qg,restoreBackup:()=>U0,restoreDriveVersion:()=>tI,restoreProjectSession:()=>ou,retryAccountSecretResource:()=>nc,retryFailed:()=>YS,retrySessionPrompt:()=>eu,revealCredential:()=>iM,reviewItemTarget:()=>Kp,reviewSegmentForStatus:()=>S_,reviewVerdictAllowed:()=>PC,reviewVerdictForStatus:()=>aC,revokeAccountSecretResourceGrant:()=>oc,revokeAccountSession:()=>ZC,revokeAccountToken:()=>zd,revokeAssignment:()=>hd,revokeCaptureDevice:()=>mf,revokeCaptureEnrollmentToken:()=>_f,revokeConnection:()=>yc,revokeGatewayKey:()=>Up,revokeOAuthGrant:()=>Jd,revokePendingProjectInvite:()=>Ea,revokeProjectAccess:()=>Ca,revokeProjectCliToken:()=>Zd,revokeSandboxProjectAccess:()=>M0,revokeSandboxShare:()=>Rd,revokeScimToken:()=>LC,revokeSessionPublicShare:()=>Gl,rewriteLocalhostUrl:()=>dt,rollbackApp:()=>Lg,rootRuntimeSession:()=>Yx,rotateAccountSecretResource:()=>tc,rotateOAuthClientSecret:()=>gd,runConnector:()=>ws,runGatewayPlayground:()=>Fp,runProjectProviderOAuthFlow:()=>zv,runtimeSessionsOf:()=>Qo,runtimeSupports:()=>cS,sanitizePtyChunk:()=>Ib,saveGitHubInstallation:()=>ha,savedCopyEmptyRoot:()=>Jy,scaleApp:()=>qg,scheduleDowngrade:()=>Vu,searchCapture:()=>Tf,searchConnectorTools:()=>uc,searchMyCapture:()=>Uf,searchProjectFiles:()=>il,segmentTurn:()=>hy,selectableProjectAgents:()=>JI,sendMagicLink:()=>eo,sendReferralEmails:()=>oC,serverCompactionRevalidateAtMs:()=>PF,serviceAction:()=>gM,sessionConnectionLabel:()=>DF,sessionListStatus:()=>OF,sessionLogActivityText:()=>Aw,sessionLogAnsweredQuestionCall:()=>Mw,sessionLogBurstRunning:()=>Tw,sessionLogBurstSteps:()=>vw,sessionLogBurstSummary:()=>Rw,sessionLogBurstWorkLabel:()=>Cw,sessionLogCallStatus:()=>hw,sessionLogFullTextAction:()=>qw,sessionLogFullTextPlan:()=>Gw,sessionLogHarnessSwitches:()=>Uw,sessionLogOfV1Rows:()=>cw,sessionLogOpenCall:()=>Iw,sessionLogPromptMessage:()=>_w,sessionLogReferencedTexts:()=>Bw,sessionLogRestoreNotice:()=>Fw,sessionLogRetrying:()=>Hy,sessionLogShowGroupCall:()=>Ew,sessionLogThreadMetrics:()=>jw,sessionLogTurnSegments:()=>ww,sessionLogTurns:()=>ei,sessionLogWithFullTexts:()=>Ww,sessionModelCandidates:()=>Kk,sessionModelFallback:()=>Nk,sessionModelPin:()=>Qn,sessionParentId:()=>cR,sessionPickStands:()=>Bk,sessionPromptActions:()=>yR,sessionStartKey:()=>wR,setAccountAutomationsPaused:()=>_R,setAccountSecretResourceAccess:()=>ic,setActiveInstanceCookie:()=>i0,setAdminBypass:()=>Sh,setAdminProviderDistribution:()=>PT,setAdminProviderFallback:()=>vT,setAgentScope:()=>Eu,setBillingPlan:()=>ep,setBootstrapAuthToken:()=>Jv,setCachedAuthToken:()=>Yv,setCaptureEnabled:()=>$f,setCapturePolicy:()=>wf,setCaptureStorage:()=>vf,setConnectionPolicies:()=>mA,setConnectorAuthorizationStrategy:()=>Rc,setConnectorCredential:()=>qc,setConnectorCredentialMode:()=>Ac,setConnectorName:()=>Mc,setConnectorPolicies:()=>Ic,setConnectorSecretBinding:()=>PA,setConnectorSensitive:()=>Cc,setDefaultConnection:()=>_c,setEnterpriseDemo:()=>dT,setEnv:()=>Fm,setGatewayBudget:()=>Dp,setGatewayRoutingPolicy:()=>wp,setGitHubAppFromExisting:()=>DU,setGitHubAppPat:()=>jU,setImpersonationSession:()=>gv,setMaintenanceConfig:()=>SU,setMemberSuperAdmin:()=>OC,setMfaRequired:()=>FC,setModelDefault:()=>Tu,setPersonalProjectSecret:()=>Ja,setProjectModelAccess:()=>rr,setProjectModelEnablement:()=>kR,setProjectOnboardingComplete:()=>aa,setProjectOnboardingProfile:()=>Fv,setProjectPolicies:()=>zc,setProjectSecretStrategy:()=>Wa,setProjectSessionModel:()=>pu,setProjectSessionScope:()=>uu,setProjectSessionSharing:()=>jl,setProjectTriggersActivation:()=>_u,setSavedCopyStore:()=>rR,setSessionArchived:()=>Nl,setSessionOversight:()=>BC,setSessionPinned:()=>Fl,setSessionProviderSecretPool:()=>lc,setSessionWatch:()=>Ul,setTelegramAllowedUsers:()=>zR,settleSessionConnection:()=>iF,setupSSH:()=>N0,shareConnection:()=>Pc,shareFolder:()=>BT,shellActivityGroupLabel:()=>jI,shellExitCode:()=>Iy,shouldAttachImpersonation:()=>_h,shouldHideResponsePart:()=>YL,shouldShowToolPart:()=>gn,shouldSuppressWorkingTurnBusy:()=>NL,showGroupItems:()=>by,showTurnBusyIndicator:()=>Sy,signInWithPassword:()=>Zs,signInWithProvider:()=>no,signInWithSso:()=>co,signOut:()=>uo,signOutDevice:()=>MT,signUp:()=>Xs,skillDocumentPath:()=>I$,skillInputDir:()=>R$,sortSessions:()=>wj,splitSessionLogTurnWork:()=>kw,splitTurnWork:()=>Ry,splitUserParts:()=>DD,startApp:()=>Og,startAppMachine:()=>Fg,startConnectionOAuth2Authorization:()=>lA,startConnectionOAuth2DeviceAuthorization:()=>uA,startConnectorSetupLink:()=>gU,startGitHubAppManifest:()=>OU,startProjectProviderOAuth:()=>us,startProjectSession:()=>nt,startProjectSessionOrThrow:()=>Ru,startSessionWithToken:()=>_U,startTask:()=>hE,stepLabel:()=>yn,stopApp:()=>Dg,stopAppMachine:()=>Ng,stopProjectSession:()=>Jn,stopSandbox:()=>R0,storeGitHubUserToken:()=>ba,stripAnsi:()=>Qf,stripInstancePrefix:()=>s0,stripTrailingSlashes:()=>le,subAgentCalls:()=>Dw,submitAccessRequest:()=>cU,submitDemoRequest:()=>xU,submitOAuthConsent:()=>pU,submitReviewItem:()=>xd,submitSecretSetupLink:()=>yU,subscribeToImpersonation:()=>mv,supabaseClient:()=>Rv,syncConnectors:()=>vc,syncSubscription:()=>$R,systemReload:()=>wM,toDaemonPath:()=>pt,toInstanceAwarePath:()=>a0,toInternalUrl:()=>PS,toSandboxAbsolutePath:()=>sn,toToolView:()=>ty,toWorkspaceRelative:()=>Zm,toolCallBlock:()=>lr,toolCallError:()=>z_,toolCallMetadata:()=>G_,toolCallRawOutput:()=>V_,toolCallStatus:()=>H_,toolInfo:()=>Eo,toolKind:()=>ae,toolViewModel:()=>dx,triggerControlsFrom:()=>bC,triggerSandboxUpdate:()=>H0,triggersRequest:()=>Rb,turnEndCause:()=>Hx,turnEndNotice:()=>hF,turnHasSteps:()=>Tj,turnIsConfirmedActive:()=>qL,turnRendersQueued:()=>GL,turnRetryLabel:()=>LF,unassignTicket:()=>RE,unregisterDeviceToken:()=>rm,unregisterWebPushSubscription:()=>pm,unshareFolder:()=>KT,untimedAnchorOf:()=>oy,unwrapError:()=>ye,updateAccountAuditWebhook:()=>ig,updateAccountBranding:()=>Di,updateAccountMemberRole:()=>zi,updateAccountName:()=>Mi,updateAgentConfig:()=>RR,updateApp:()=>Sg,updateAppAccess:()=>Ag,updateAppVolume:()=>Vg,updateAuditWebhook:()=>cT,updateChangeRequest:()=>Cl,updateChannelBinding:()=>XR,updateConnectionCredential:()=>fc,updateEmailPolicy:()=>Pp,updateExperimentalFeature:()=>oa,updateFeatureFlag:()=>sa,updateGroup:()=>Vp,updateKortixPty:()=>Gm,updateMilestone:()=>ZE,updateNotificationPreferences:()=>cm,updateOAuthClient:()=>dd,updatePassword:()=>oo,updatePatPolicy:()=>tT,updatePolicy:()=>CC,updateProject:()=>On,updateProjectAccess:()=>Ra,updateProjectAgent:()=>FE,updateProjectDefaultAgent:()=>Ou,updateProjectGroupGrant:()=>ja,updateProjectSandboxProvider:()=>ia,updateProjectSession:()=>nu,updateProjectTrigger:()=>yu,updateRole:()=>sd,updateRolePermissions:()=>od,updateRoom:()=>$d,updateSandboxTemplate:()=>el,updateSessionPolicy:()=>QC,updateSessionReminder:()=>js,updateSessionReminders:()=>Id,updateTask:()=>yE,updateTemplateWarmPool:()=>Uv,updateTicket:()=>kE,updateTicketStatus:()=>vE,updateUserMetadata:()=>ao,uploadAccountBrandingAsset:()=>ji,uploadAppArtifactArchive:()=>Cg,uploadConnectorAttachment:()=>_s,uploadDriveFile:()=>YT,uploadFile:()=>ln,uploadNativeFile:()=>Zb,uploadPromptAttachment:()=>Bn,uploadSessionAttachment:()=>Rm,uploadSlackChannelFile:()=>fp,uploadTimeoutMsForBytes:()=>nn,upsertCredential:()=>oM,upsertProjectGitCredential:()=>Ya,upsertProjectSecret:()=>Ga,upsertSsoProvider:()=>qC,validateProjectManifest:()=>Zi,validateReferralCode:()=>nC,validateToken:()=>Ji,verifyGatewayProvider:()=>ZR,verifyKortixToken:()=>yk,verifyOtp:()=>to,verifySsoDomain:()=>WC,wakeEscalationAttemptSummary:()=>EF,wakeEscalationNote:()=>TF,wakeProgressFingerprint:()=>vF,wireIdClock:()=>Tt,wireIdClockAt:()=>Zt,wireIdClockDelta:()=>It,workedForLabel:()=>l$,workingExpiryAtMs:()=>fF,workingTurnDrawsBusyRow:()=>WL,writeActivityGroupLabel:()=>LI,writeFile:()=>kr,wsDomain:()=>No,wsFavicon:()=>qj,wsRootDomain:()=>Kj});var Qk={backendUrl:"",getToken:async()=>null},ci=null,Qr=null;function Xk(e){Qr=e}function Zk(){return Qr}function Xr(e,t){t?.global!==!1&&(ci=e)}function I(){return Qr?.()??ci??Qk}function Zr(){return ci!==null||Qr?.()!==void 0}function ev(e){return new Promise(t=>setTimeout(t,e))}async function es(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(o&&n?.(),s>0&&await ev(s)),i=await e(),i)return i;return i}var li=12e4;function tv(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function ah(e,t,n=li){let r=e instanceof Request?e.signal:t?.signal;if(tv(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function ts(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var x=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},re=class extends x{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},et=class extends x{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},bt=class extends x{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},nv="ENDPOINT_RETIRED";function N(e,t){let n=t?` ${t}`:"";return new x(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:nv})}var Dt="feature_disabled";function ch(e){if(!(e instanceof x)||e.status!==403||e.code!==Dt)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function ui(e){let t=ch(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function pi(e){let t=ch(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}var An="repository_disconnected",rv=new Set(["app_uninstalled","app_suspended","repo_not_accessible"]);function lh(e){return!!e&&typeof e=="object"&&e.code===An}function uh(e){if(e?.status!=="error")return null;let t=e.last_error_code;return t&&rv.has(t)?t:null}function Rn(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 et(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 di(e){return e instanceof et}function jt(e){if(e instanceof re)return!0;let t=e?.status;return t===401||t===403}function gi(e){if(!(e instanceof et))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 Ae(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function Re(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(Ae())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function ns(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(Ae())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var ph="request_deadline",sv=/^Request exceeded the \d+s server processing deadline$/,dh=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===ph||sv.test(n),ov="git_mirror_unavailable",iv=/^git mirror is temporarily unavailable$/,av=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===ov||iv.test(n),cv="connectors_provider_unavailable",lv=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===cv;async function uv(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await Re(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 Ae();return{message:n,data:r}}function pv(e,t,n){return dh(e,t,n)||av(e,t,n)||lv(e,t)||e===403&&t?.code===Dt||e===501&&t?.code===mi||e===409&&(t?.code===fi||t?.code===yi||t?.code===hi||t?.code===An)||e===503&&(t?.code===_i||t?.code===bi)}async function gh(e,t,n,r){let{message:s,data:o}=await uv(e,t),i=new x(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:dh(e.status,o,s)?ph:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=Rn(i));let a=e.status===403&&(o?.code==="account_mfa_required"||o?.code==="sso_required")?o.code:null;if(a){try{I().onAccessRemedy?.(a)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a==="account_mfa_required"?"kortix:mfa-required":"kortix:sso-required"))}catch{}}return e.status===431&&(i=new bt(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&&!pv(e.status,o,s)&&I().onError?.(i,r),{error:i,success:!1}}var mh="X-Kortix-Impersonate",Pi="kortix.impersonation",St=null,rs=!1,Si=new Set;function xi(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function fh(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 dv(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 yh(){for(let e of Si)try{e()}catch{}}function hh(){return rs||(rs=!0,St=dv(xi()?.getItem(Pi)??null)),St&&!fh(St)?(wi(),null):St}function gv(e){if(rs=!0,!e){wi();return}St=e;try{xi()?.setItem(Pi,JSON.stringify(e))}catch{}yh()}function wi(){rs=!0;let e=St!==null;St=null;try{xi()?.removeItem(Pi)}catch{}e&&yh()}function mv(e){return Si.add(e),()=>{Si.delete(e)}}var fv=/(^|\/)admin\/(api|analytics)(\/|$)/;function _h(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!fv.test(t)}function ki(e){if(e!==void 0&&!_h(e))return{};let t=hh();return t?{[mh]:t.grantId}:{}}function Sh(e){}function Ph(){return!1}function yv(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 Cn(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function os(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(yv))Cn(n,s,o);return n}function Ai(e,t,n){let r={...t},s=I().clientVersion?.trim();s&&!ss(r,"x-kortix-client-version")&&Cn(r,"X-Kortix-Client-Version",s);for(let[i,a]of Object.entries(ki(e)))Cn(r,i,a);let o=I().credentialHeader?.trim();return o?ss(r,o)||Cn(r,o,n):ss(r,"authorization")||Cn(r,"Authorization",`Bearer ${n}`),r}async function Lt(e,t){let n=await is();if(!n)throw new re;return{headers:new Headers(Ai(e,os(e,{headers:t}),n)),rejected:()=>Tn(n)}}function hv(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function bh(e,t,n,r,s){if(t instanceof Request){let l=new Headers(Ai(t.url,os(t,n),r));return e(new Request(t,{headers:l,...s?{signal:s}:{}}))}let o=String(t),i=Ai(o,os(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var xh=null;async function Ri(e){let t=await es(()=>I().getToken(),e);return t&&(xh=t),t}var is=Ri;function Tn(e=xh){e&&I().getToken.invalidate?.(e)}var vi=new Map;function _v(e){let t=vi.get(e);if(t)return t;let n=(async()=>(Tn(e),is({attempts:2,baseDelayMs:200})))().finally(()=>vi.delete(e));return vi.set(e,n),n}async function Pt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=li}=n,o=n.fetch??I().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:ah(e,t,s);if(i?.aborted)throw Ae();let a=await(i?Re(is(),i):is());if(!a)throw new re;let l=r&&!hv(t)&&!ss(os(e,t),"authorization"),p=l&&e instanceof Request?e.clone():e,d=await bh(o,e,t,a,i);if(d.status!==401||!l)return d;let g=await _v(a);return!g||g===a?d:bh(o,p,t,g,i)}async function Le(e,t,n,r){let s=await Pt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new x(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var wh=()=>I().backendUrl||"",bv=new Set([502,503,504]),Sv=e=>bv.has(e),kh=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Pv=e=>kh(e)||(e??"GET").toUpperCase()==="DELETE",xv=2,as=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function $e(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...i}=t,a=new AbortController,l={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>l.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await wv(e,i,n,r,s,o,a,l)}finally{i.signal?.removeEventListener("abort",p)}}async function wv(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw Ae();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},s);let l={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await vv(e,t,l,s,o,i,a);if(p instanceof re)return{error:p,success:!1};if(!p.ok)return await gh(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await Re(p.json(),a.activeController.signal):g?.includes("text/")?d=await Re(p.text(),a.activeController.signal):d=await Re(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(l){return Av(l,e,t.method,n,r,s,a)}finally{cs(a)}}function cs(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function kv(e,t,n){try{await Re(e.arrayBuffer(),t)}catch(r){if(as(r))throw r}finally{cs(n)}}async function vv(e,t,n,r,s,o,i){let a=kh(t.method),l=Pv(t.method),p=l?xv+1:1,d;for(let g=0;g<p;g++){g>0&&await ns(250*2**(g-1),t.signal??void 0);let m=g===0?o:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await Re(Pt(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 re)return new re;if(i.didTimeout&&as(f)&&!t.signal?.aborted&&l&&g<p-1){i.didTimeout=!1;continue}if(as(f)||g===p-1)throw f;continue}if(!a||!Sv(d.status)||g===p-1)return s||cs(i),d;await kv(d,m.signal,i)}return d}function Av(e,t,n,r,s,o,i){cs(i);let a=as(e);a&&(i.isAborted=!0);let l;if(a){if(!i.didTimeout)return{error:new x("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(wh(),"")||t;l=new x(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(l=new x(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(wh(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&I().onError?.(l,s)):(l=new x(String(e)),r&&I().onError?.(l,s));return{error:l,success:!1}}var Ue=()=>I().backendUrl||"",mi="feature_not_supported",fi="model_not_servable",yi="provision_in_flight",hi="sandbox_state_change_in_progress",_i="analytics_unavailable",bi="accounts_list_unavailable",Rv={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new x(r.message||"Database error",{code:r.code,details:r});return I().onError?.(s,t),{error:s,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new x(n.message,{name:n.name||"ApiError",stack:n.stack}):new x(String(n));return I().onError?.(r,t),{error:r,success:!1}}}};async function Cv(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await Pt(`${Ue()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof re)return ts();throw a}finally{clearTimeout(i)}}var c={putRaw:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>$e(`${Ue()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>$e(`${Ue()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],$e(`${Ue()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],$e(`${Ue()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:Cv};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function Ci(e){return e.replace(/\/v1\/?$/,"")}async function $t(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=Ci(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 Ti(){return u(await c.get("/accounts"))}async function Ii(e){return u(await c.post("/accounts",e))}async function Ei(e){return u(await c.get(`/accounts/${e}`))}async function Mi(e,t){return u(await c.patch(`/accounts/${e}`,{name:t}))}async function Oi(e){return u(await c.get(`/accounts/${e}/branding`))}async function Di(e,t){return u(await c.put(`/accounts/${e}/branding`,t))}async function ji(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),u(await c.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function Li(e,t){return u(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function $i(e){return u(await c.delete(`/accounts/${e}/branding`))}async function Ui(e){return u(await c.get(`/accounts/${e}/members`))}async function Fi(e,t){return u(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Ni(e){return u(await c.get(`/accounts/${e}/invites`))}async function Bi(e,t){return u(await c.delete(`/accounts/${e}/invites/${t}`))}async function Ki(e,t){return u(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function qi(){return u(await c.get("/account-invites",{showErrors:!1})).invites}async function Gi(e){return u(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function ls(e){return u(await c.post(`/account-invites/${e}/accept`,{}))}function vh(e,t){let n=e.bootstrap_grants_applied?.[0]??t?.projects?.[0];return n?{kind:"project",projectId:n.project_id,accountId:e.account_id}:{kind:"account",accountId:e.account_id}}async function Wi(e,t){let n=await ls(e);return{accepted:n,landing:vh(n,t)}}async function Hi(e){return u(await c.post(`/account-invites/${e}/decline`,{}))}async function Vi(e,t){return u(await c.delete(`/accounts/${e}/members/${t}`))}async function zi(e,t,n){return u(await c.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Yi(e){return u(await c.post(`/accounts/${e}/leave`,{}))}async function Tv(e){return $t(e,"/v1/accounts")}async function Ji(){let e=await c.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var Iv=["marketplace","connectors_api_discover","agentmail_email","meta_agent","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","genui","us_region","event_triggers","notification_center","volumes","drives","session_log","session_log_restore","connectors_v2","agent_rooms","goals"];async function xt(){return u(await c.get("/projects"))}async function Qi(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/projects${t}`))}async function wt(e,t){return u(await c.get(`/projects/${e}`,t))}async function Xi(e,t,n="write"){return u(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Zi(e,t){return u(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function ea(e){return u(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function Ev(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function In(e,t){let n=u(await c.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function En(e,t){return u(await c.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Mn(e,t){return u(await c.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function Mv(e,t){return u(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function ta(e){return u(await c.post("/projects",e))}async function na(e){return u(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function ra(e,t={}){return u(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Rh="provision_stream_unterminated",Ah=200;function Ov(e){let t=e.split(`
|
|
1
|
+
"use strict";var Kortix=(()=>{var ci=Object.defineProperty;var Vk=Object.getOwnPropertyDescriptor;var zk=Object.getOwnPropertyNames;var Yk=Object.prototype.hasOwnProperty;var Jk=(e,t)=>{for(var n in t)ci(e,n,{get:t[n],enumerable:!0})},Qk=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of zk(t))!Yk.call(e,s)&&s!==n&&ci(e,s,{get:()=>t[s],enumerable:!(r=Vk(t,s))||r.enumerable});return e};var Xk=e=>Qk(ci({},"__esModule",{value:!0}),e);var cB={};Jk(cB,{ABORT_REASONS:()=>fP,ABORT_REASONS_NOT_YET_EMITTED:()=>o0,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>Si,ACTIVE_INSTANCE_COOKIE:()=>qr,ANALYTICS_UNAVAILABLE_CODE:()=>bi,ATTACHMENT_PART_REF_PREFIX:()=>LP,ApiError:()=>P,AuthError:()=>re,BillingError:()=>et,CAPTURE_DEVICE_DEFAULTS:()=>KO,CAPTURE_EXCLUSION_GROUPS:()=>UO,CAPTURE_FRAME_INTERVALS_MS:()=>NO,CAPTURE_LAYERS:()=>$O,CAPTURE_MAX_HEIGHTS:()=>BO,CAPTURE_RETENTION_LIMITS:()=>FO,CONNECTION_FAULT_GRACE_MS:()=>GP,CONNECTOR_POLL_FIRST_DELAY_MS:()=>EP,CONNECTOR_POLL_INTERVAL_MS:()=>MP,CONNECTOR_POLL_WINDOW_MS:()=>OP,CONTEXT_TOOLS:()=>Px,COST_MARKUP:()=>Ry,ConnectorApprovalPendingError:()=>Ps,ConnectorCallError:()=>Ln,ConnectorPageLimitError:()=>ws,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>wx,DEFAULT_NOTIFICATION_PREFERENCES:()=>cI,DEFAULT_TRANSCRIPT_OPTIONS:()=>Gf,DESTRUCTIVE_PHASES:()=>vP,FEATURE_DISABLED_CODE:()=>Dt,FEATURE_FLAG_KEYS:()=>Mv,FEATURE_NOT_SUPPORTED_CODE:()=>fi,FILE_VERBS:()=>mt,FileExistsError:()=>rn,HeadlessAuthError:()=>Yt,HostBoundaryError:()=>Hr,IMPERSONATION_HEADER:()=>yh,INBOX_NOTIFICATION_KINDS:()=>aI,INBOX_OBSERVATION_MAX_MS:()=>Jo,INITIAL_SETTLED_CONNECTION:()=>lF,INSTANCE_SCOPED_ROUTES:()=>yP,KNOWN_TOOL_KINDS:()=>Bh,KORTIX_TRANSCRIPT_SCHEMA:()=>ke,KortixMemberError:()=>yt,MAX_PROMPT_ATTACHMENTS_BYTES:()=>TA,MAX_PROMPT_ATTACHMENT_BYTES:()=>pl,MAX_PROMPT_ATTACHMENT_FILES:()=>jh,MEMORY_VERBS:()=>x$,MODEL_NOT_SERVABLE_CODE:()=>yi,NO_GROUP_ACTIVITY_TOOLS:()=>Q_,OPTIMISTIC_ABORT_MAX_MS:()=>Qo,OPTIMISTIC_COMPACTION_MAX_MS:()=>PF,OPTIMISTIC_RECEIPT_MAX_MS:()=>zo,PERSISTED_QUERY_CACHE_VERSION:()=>NJ,PLUMBING_TOOLS:()=>qx,PREVIEW_PROBE_TIMEOUT_MS:()=>eF,PROJECT_ACTIONS:()=>Q,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>dR,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>pR,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>s_,PROVISION_IN_FLIGHT_CODE:()=>hi,PROVISION_STREAM_UNTERMINATED_CODE:()=>Th,PublicSessionShareError:()=>js,REPOSITORY_DISCONNECTED_CODE:()=>An,REVIEW_CONTROL_ACTIONS:()=>PC,RUNTIME_NOT_READY_MARKERS:()=>h0,RUNTIME_PERMISSION_CAPABILITIES:()=>dI,RUNTIME_PERMISSION_REPLIES:()=>pI,RequestTooLargeError:()=>bt,RuntimeNotReadyError:()=>tn,SANDBOX_FS_ROOTS:()=>Po,SANDBOX_PORTS:()=>Ke,SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE:()=>_i,SERVER_COMPACTION_REVALIDATE_MS:()=>zP,SERVER_OBSERVATION_MAX_MS:()=>Yo,SESSION_LIST_STATUS:()=>LF,SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES:()=>ni,SESSION_LOG_MINOR:()=>_e,SESSION_LOG_SCHEMA:()=>ce,SESSION_NOTICE:()=>FF,STANDALONE_TOOLS:()=>X_,STREAM_OBSERVATION_MAX_MS:()=>Sn,SandboxNotReadyError:()=>Gr,SessionNotReadyError:()=>Ct,SessionStartError:()=>Is,TRIGGER_CONTROL_ACTIONS:()=>SC,TURN_END_LEDGER_LAG_MS:()=>fF,TURN_ERROR_CODES:()=>M_,WAKE_ESCALATION_COOLDOWN_MS:()=>CF,WAKE_MAX_RESTARTS:()=>RF,WAKE_NO_PROGRESS_MS:()=>AF,WIRE_ID_BACKDATE_MS:()=>fo,WIRE_ID_CLOCK_TOLERANCE:()=>ct,WIRE_ID_TIME_MASK:()=>Ve,WIRE_ID_TIME_SCALE:()=>Xt,WIRE_MESSAGE_ID:()=>xb,__getConfigResolver:()=>tv,__setConfigResolver:()=>ev,abortErrorReason:()=>i0,acceptAccountInvite:()=>us,acceptAccountInviteAndLand:()=>Hi,acceptEnterpriseOffer:()=>np,acceptInvite:()=>U0,accountInviteLanding:()=>Rh,actReviewItem:()=>kd,activateConnection:()=>_c,addComputerToProject:()=>xc,addGroupMembers:()=>Qp,addMarketplaceSource:()=>_g,addRoomPerson:()=>Wd,addRoomSession:()=>qd,advanceWakeEscalation:()=>EF,allDescendantIds:()=>Ox,appendPreviewToken:()=>VU,approveCaptureDeviceGrant:()=>Lf,approveCaptureEnrollment:()=>Pf,approveProjectAccessRequest:()=>va,approveTask:()=>SE,archiveProject:()=>Dn,assignTicket:()=>CE,attachGroupToProject:()=>ja,authMfa:()=>uo,authUser:()=>ao,authenticatedFetch:()=>$,authenticatedRequest:()=>Un,authorizePreviewUrl:()=>ZU,backendApi:()=>c,bindSlackIdentity:()=>qR,bindTeamsIdentity:()=>GR,brokerProjectSecretRequest:()=>Va,browserKeyValueStorage:()=>GU,buildInstancePath:()=>_P,buildPresentationTemplateImageUrl:()=>sF,buildPresentationTemplatePdfUrl:()=>rF,buildPreviewAuthEndpoint:()=>Fy,buildPublicTemplateUrl:()=>TU,buildRuntimePresentationConversionUrl:()=>qP,buildSandboxTemplate:()=>rl,buildScrapeFailureResults:()=>Ux,buildStaticFileHealthPreviewUrl:()=>kO,buildStaticFileLocalUrl:()=>wO,buildStaticFilePreviewUrl:()=>PO,buildStaticFileServicePath:()=>SS,buildTunnelEventStreamUrl:()=>GN,buildWebProxyUrl:()=>TO,bulkActReviewItems:()=>vd,bulkDeletePolicies:()=>MC,bulkImportPolicies:()=>OC,burstSummary:()=>Ko,burstSummaryLabel:()=>Gx,burstWorkLabel:()=>yy,callConnector:()=>kt,canManageBilling:()=>f_,canOfferTopup:()=>OR,cancelAccountDeletion:()=>_T,cancelAccountInvite:()=>Ki,cancelSandbox:()=>M0,cancelSandboxUpdate:()=>X0,cancelScheduledChange:()=>Yu,cancelSubscription:()=>Hu,captureHealthBucket:()=>HO,changeRequestControlsFrom:()=>w_,checkAccessEmail:()=>pU,checkMcpServerSignIn:()=>_A,childMapByParent:()=>kj,claimComputer:()=>rU,claimNext:()=>zS,claimPerSeatBilling:()=>UR,claimWarmProjectSession:()=>Vl,classifyPart:()=>oy,classifyPreviewProbeStatus:()=>KP,classifyPtyClose:()=>Ib,classifySessionLogMessage:()=>Dw,classifyTurn:()=>jo,cleanErrorMessage:()=>Nj,cleanResultSnippet:()=>Gj,cleanWorkerOutput:()=>f$,clearImpersonationSession:()=>ki,clearKortixAppViewerCache:()=>pk,clearModelDefault:()=>Eu,clearSessionFresh:()=>qA,closeChangeRequest:()=>vl,closeMilestone:()=>nM,collectTurnParts:()=>Tj,commentTicket:()=>IE,commitSessionChanges:()=>Cl,compactionExpiryAtMs:()=>kF,compactionTurnInfo:()=>RL,compareForDisplayAt:()=>$o,compareMessagesForDisplay:()=>wj,compareSemver:()=>JO,completeInFlight:()=>YS,completeSlackInstall:()=>pp,completeTeamsInstall:()=>dp,composerSelectableAgents:()=>sh,computeStatusFromPart:()=>ky,configureAutoTopup:()=>Zu,configureKortix:()=>Zr,confirmCheckoutSession:()=>Gu,connectEmail:()=>Sp,connectSlack:()=>lp,connectTelegram:()=>YR,connectionFromHealth:()=>cF,connectionIsFaulted:()=>aF,connectionSharedWithEveryone:()=>sA,connectorConnect:()=>Mh,connectorFinalize:()=>Oh,connectorHeadline:()=>jU,contactEnterpriseSales:()=>rp,contextLabelForTool:()=>Zj,contextToolSummary:()=>RD,contextToolTrigger:()=>CD,convertPresentationToGoogleSlides:()=>TT,convertRuntimePresentation:()=>oF,copyFile:()=>wr,costExportUrl:()=>op,countLiveInboxPrompts:()=>hF,countReviewItemsBySegment:()=>cC,createAccount:()=>Ei,createAccountAuditWebhook:()=>ag,createAccountSecretResource:()=>tc,createAccountToken:()=>Yd,createApp:()=>xg,createAppAccessSession:()=>Tg,createAppDeployment:()=>Eg,createAppToken:()=>kg,createAppVolume:()=>zg,createAppVolumeSnapshot:()=>Xg,createArtifactKind:()=>xL,createAssignment:()=>hd,createAuditWebhook:()=>lT,createBackup:()=>B0,createCaptureEnrollmentToken:()=>bf,createCheckoutSession:()=>qu,createConnector:()=>jc,createConnectorLinkInfoCache:()=>MU,createFile:()=>Pr,createGatewayKey:()=>Up,createGroup:()=>Vp,createHttpSessionSyncController:()=>Xw,createInstance:()=>eU,createKortix:()=>GS,createKortixPty:()=>Wm,createKortixSession:()=>go,createMarketplaceInstallSession:()=>LT,createMilestone:()=>eM,createModelVisibility:()=>Uk,createOAuthClient:()=>dd,createPerSeatCheckout:()=>$R,createPersistedQueryCache:()=>qU,createPolicy:()=>TC,createPortalSession:()=>Wu,createProject:()=>na,createProjectAgent:()=>NE,createProjectCliToken:()=>eg,createProjectRepo:()=>ra,createProjectResourceGrant:()=>Fa,createProjectSession:()=>Rt,createProjectSkill:()=>la,createProjectTrigger:()=>yu,createPromptAttachmentController:()=>gf,createRole:()=>sd,createRoom:()=>$d,createSSEStream:()=>WN,createSandbox:()=>v0,createSandboxShare:()=>Rd,createSandboxTemplate:()=>el,createSavedCopyStore:()=>sR,createScimToken:()=>$C,createServiceAccountApi:()=>oT,createSessionPrompt:()=>zn,createSessionPublicShare:()=>Gl,createSessionQueue:()=>HS,createSessionReminder:()=>Id,createSsoGroupMapping:()=>JC,createTask:()=>hE,createTicket:()=>vE,createTunnelEventStream:()=>HN,createWarmSessionPool:()=>CN,currentSavedCopyStore:()=>Dl,declineAccountInvite:()=>Vi,declineInvite:()=>F0,deleteAccountImmediately:()=>bT,deleteAccountSecretResource:()=>sc,deleteApp:()=>wg,deleteAppDeployment:()=>$g,deleteAuditWebhook:()=>pT,deleteBackup:()=>q0,deleteConnector:()=>Fc,deleteConnectorCredential:()=>Wc,deleteCredential:()=>lM,deleteCustomLlmProvider:()=>ir,deleteDriveFile:()=>tI,deleteEnv:()=>Km,deleteFile:()=>Et,deleteGatewayBudget:()=>Lp,deleteGitHubInstallation:()=>xa,deleteGroup:()=>Yp,deleteInstance:()=>tU,deleteKortixProject:()=>YE,deleteMilestone:()=>sM,deleteOAuthClient:()=>fd,deletePersonalProjectSecret:()=>Xa,deletePolicy:()=>EC,deleteProjectAgent:()=>KE,deleteProjectProviderOAuth:()=>Ya,deleteProjectResourceGrant:()=>Na,deleteProjectSecret:()=>jn,deleteProjectSession:()=>su,deleteProjectTrigger:()=>_u,deletePromptAttachment:()=>Bt,deleteRole:()=>ad,deleteSandboxTemplate:()=>nl,deleteServiceAccountApi:()=>aT,deleteSessionPrompt:()=>Xl,deleteSessionReminder:()=>$s,deleteSessionReminders:()=>Od,deleteSsoGroupMapping:()=>QC,deleteSsoProvider:()=>zC,deleteTask:()=>xE,deleteTicket:()=>EE,denyCaptureDeviceGrant:()=>$f,denyCaptureEnrollment:()=>wf,describeAccountInvite:()=>Wi,describeConnectorTool:()=>hs,destroyAppMachine:()=>Gg,destroyAppVolume:()=>Jg,detachGroupFromProject:()=>$a,detectLocalhostUrls:()=>yS,directSubsessions:()=>BF,disableServiceAccountApi:()=>iT,disconnectEmail:()=>xp,disconnectGitHubApp:()=>NU,disconnectSlack:()=>mp,disconnectTelegram:()=>QR,discoverConnectionOAuth2:()=>cA,discoverConnectionOAuth2Resource:()=>lA,discoverConnectorAuth:()=>Lc,discoverLocalSandbox:()=>T0,dismissDriveConflict:()=>VT,downloadAccountAudit:()=>RU,downloadDriveFile:()=>YT,dropClientForUrl:()=>bM,dropPublicClientForUrl:()=>PM,editQueued:()=>ZS,editSessionPrompt:()=>Zl,enqueue:()=>VS,ensurePmSession:()=>UE,ensurePreviewSessionCookie:()=>BP,ensureProjectConnectorConnection:()=>oA,ensureSandbox:()=>kP,ensureWarmProjectSession:()=>Hl,env:()=>Cb,exchangeCode:()=>so,execInApp:()=>Hg,exportAccountAudit:()=>og,extractGatewayErrorDetails:()=>Se,extractInstanceRoute:()=>_n,extractSkillBaseDir:()=>lP,extractSkillContent:()=>C$,extractSkillFiles:()=>cP,extractWorkerPreview:()=>h$,failInFlight:()=>JS,fallbackBusyRowAfterTurnId:()=>HL,familyForTool:()=>fn,featureDisabledKey:()=>di,featureFlags:()=>Mm,fetchAccountStateWithToken:()=>DR,fetchAccountsWithToken:()=>Ev,fetchAttachmentPart:()=>WU,fetchCostExportCsv:()=>KR,fetchKortixAppViewer:()=>eh,fetchProjectArchive:()=>ll,fetchProjectFileRaw:()=>CA,fetchProjectsForAccountWithToken:()=>Kv,fetchSessionAttachment:()=>Im,fileDownloadRequest:()=>Qb,filePhase:()=>S$,fileVerb:()=>b$,files:()=>iS,finalizeAppArtifact:()=>Ns,finalizeConnectorSetupLink:()=>_U,findActiveTranscriptShare:()=>mR,findFiles:()=>Sr,findLastTextPart:()=>Ij,findSessionAttachments:()=>zI,findText:()=>xr,fireProjectTrigger:()=>Su,fixSandboxWithAgent:()=>Zc,flattenModels:()=>Ok,flattenThought:()=>ML,forkAppVolume:()=>em,formatBillingErrorForUI:()=>mi,formatCost:()=>a$,formatDuration:()=>Ay,formatJsonFailureOutput:()=>Bj,formatMessageDay:()=>UL,formatMessageExact:()=>FL,formatOpenCodeRuntimeError:()=>x0,formatRawOutput:()=>qj,formatRuntimeError:()=>wP,formatTokens:()=>c$,formatTranscript:()=>tx,freshSendHint:()=>JL,generateSessionId:()=>WS,getAccount:()=>Mi,getAccountAutomations:()=>bR,getAccountBranding:()=>Di,getAccountDeletionStatus:()=>yT,getAccountState:()=>Lu,getAccountStateMinimal:()=>$u,getActiveInstanceIdFromCookie:()=>SP,getAdminProviderAnalytics:()=>kT,getAdminProviderDistribution:()=>xT,getAdminProviderFallback:()=>AT,getAdminRole:()=>ST,getAgentCardLabel:()=>Ax,getAgentConfig:()=>CR,getAgentPersona:()=>qE,getAllVersions:()=>Y0,getAnsweredQuestionParts:()=>Mj,getApp:()=>Us,getAppAccess:()=>Ag,getAppAuthEnv:()=>vg,getAppDeployment:()=>Og,getAppDeploymentLogs:()=>Dg,getApprovalLink:()=>jT,getAuthToken:()=>Ft,getAuthTokenWithRetry:()=>Zv,getAutoTopupSettings:()=>Xu,getAutoTopupSetupStatus:()=>LR,getBillingCreditBreakdown:()=>Nu,getBillingTierConfigurations:()=>Ku,getBillingTransactionsSummary:()=>Fu,getBillingUsageHistory:()=>Bu,getCaptureAssetUrl:()=>Df,getCaptureChunkMedia:()=>Of,getCaptureDays:()=>If,getCaptureDeviceGrant:()=>jf,getCaptureFrame:()=>Mf,getCapturePolicy:()=>kf,getCaptureStorage:()=>Af,getCaptureTimeline:()=>Cf,getCaptureTimelineItems:()=>Tf,getCaptureWorkspace:()=>Uf,getChangeRequest:()=>Sl,getChangeRequestDiff:()=>xl,getChangeRequestMergePreview:()=>Pl,getChildSessionError:()=>KD,getChildSessionId:()=>Or,getChildSessionToolParts:()=>qD,getClient:()=>ut,getClientForUrl:()=>Me,getConnectStatus:()=>qc,getConnectionOAuth2Application:()=>aA,getConnectionOAuth2Status:()=>mA,getConnectionPolicies:()=>fA,getConnectorCatalog:()=>Nt,getConnectorConfig:()=>Mc,getConnectorPolicies:()=>Ic,getConnectorSetupLink:()=>yU,getCostSummary:()=>BR,getCurrentInstanceIdFromPathname:()=>bP,getCurrentInstanceIdFromWindow:()=>l0,getCurrentProject:()=>nf,getDefaultAccountState:()=>ju,getDiagnostics:()=>zD,getDirectory:()=>vx,getDiscoverConnector:()=>xs,getDiscoverIntegration:()=>PA,getDriveFileUrl:()=>tm,getEmailInstallation:()=>_p,getEmailMode:()=>bp,getEnterpriseDemo:()=>gT,getFileStatus:()=>br,getFileWithDir:()=>Xf,getFilename:()=>kx,getFolderAccess:()=>KT,getFullChangelog:()=>AP,getGatewayBreakdown:()=>Ep,getGatewayBudgets:()=>Dp,getGatewayErrors:()=>Op,getGatewayKeys:()=>$p,getGatewayLog:()=>Cp,getGatewayOverview:()=>Tp,getGatewayRoutingPolicy:()=>wp,getGatewaySeries:()=>Ip,getGatewaySessions:()=>Mp,getGitHubAppStatus:()=>LU,getGitHubInstallation:()=>ga,getGoogleAuthUrl:()=>CT,getGroup:()=>Hp,getHiddenToolParts:()=>$D,getImpersonationSession:()=>bh,getInvite:()=>$0,getJustavpsServerTypes:()=>Z0,getKortixProject:()=>HE,getKortixProjectBySession:()=>VE,getKortixPtyWebSocketUrl:()=>zm,getLatestSandboxVersion:()=>z0,getMaintenanceConfig:()=>wU,getManagedGitBackend:()=>Pa,getManagedGitStatus:()=>Uv,getMarketplaceCatalogItem:()=>fg,getMarketplaceCatalogItemFile:()=>yg,getMfaRequired:()=>FC,getMilestone:()=>XE,getMobileClientPolicy:()=>qf,getModelDefaults:()=>Tu,getMyCaptureFrame:()=>Kf,getMyCaptureTimeline:()=>Bf,getNotificationPreferences:()=>lm,getOAuthClient:()=>pd,getOAuthConsentRequest:()=>mU,getOpenCodeConfigInvalidError:()=>m0,getPartText:()=>DD,getPatPolicy:()=>nT,getPermissionForTool:()=>YD,getProject:()=>wt,getProjectActivity:()=>GE,getProjectCommit:()=>fl,getProjectCommitDiff:()=>yl,getProjectDetail:()=>In,getProjectDrive:()=>BT,getProjectFileHistory:()=>hl,getProjectGitConnectionState:()=>Gv,getProjectGitToken:()=>ta,getProjectLlmCatalog:()=>En,getProjectLlmCatalogProviders:()=>Dv,getProjectModelAccess:()=>nr,getProjectModelPicker:()=>Mn,getProjectQuota:()=>$v,getProjectSandboxHealth:()=>$n,getProjectSandboxProviderTransition:()=>Fv,getProjectSession:()=>Wn,getProjectSessionConfigState:()=>au,getProjectSessionScope:()=>uu,getProrationPreview:()=>Ju,getProviders:()=>w0,getProxyBaseUrl:()=>vO,getPublicClientForUrl:()=>xM,getPublicMarketplaceItem:()=>lU,getPublicMarketplaceItemFile:()=>uU,getPublicSessionShare:()=>IT,getPublicSessionShareMessages:()=>ET,getPublicShareByToken:()=>xU,getPublicTemplate:()=>IU,getQuestionForTool:()=>JD,getReferralCode:()=>nC,getReferralStats:()=>oC,getRetryInfo:()=>l$,getRetryMessage:()=>u$,getReviewItem:()=>Pd,getReviewSummary:()=>xd,getRolePermissions:()=>nd,getRoleUsage:()=>rd,getRoom:()=>Ud,getRuntimeConfigInvalidError:()=>Vo,getSSHConnection:()=>W0,getSandbox:()=>k0,getSandboxById:()=>A0,getSandboxPortUrl:()=>P0,getSandboxProvisionStatus:()=>sU,getSandboxProvisionStreamUrl:()=>oU,getSandboxUpdateStatus:()=>V0,getSandboxUrl:()=>jy,getSandboxUrlForExternalId:()=>Ie,getSecretSetupLink:()=>bU,getServerHealth:()=>wo,getServiceLogs:()=>mM,getSessionAudit:()=>zl,getSessionCost:()=>i$,getSessionCostRecord:()=>Zn,getSessionDrives:()=>T_,getSessionHealth:()=>af,getSessionLogPage:()=>Jl,getSessionMessageAuthors:()=>gu,getSessionModelUsage:()=>mu,getSessionOpenBundle:()=>fR,getSessionOversight:()=>KC,getSessionParticipants:()=>$l,getSessionPolicy:()=>XC,getSessionPreviewCandidates:()=>Kl,getSessionProviderSecretPool:()=>cc,getSessionTranscript:()=>Yl,getSessionTranscriptSync:()=>Hn,getSessionTurn:()=>Vn,getSessionWatch:()=>Ul,getShellModePart:()=>m$,getSlackChannelFile:()=>fp,getSlackInstallation:()=>cp,getSlackManifest:()=>gp,getSlackMode:()=>up,getSsoProvider:()=>GC,getStaticFileHealthPath:()=>xS,getSupabaseAccessToken:()=>gs,getSupabaseAccessTokenWithRetry:()=>Eh,getTask:()=>mE,getTaskStatus:()=>yE,getTelegramInstallation:()=>zR,getTemplate:()=>$T,getTicket:()=>wE,getToolInfo:()=>WD,getToolPrimaryArg:()=>Io,getTranscriptFilename:()=>nx,getTurnCost:()=>Ho,getTurnError:()=>e$,getTurnErrorDetails:()=>n$,getTurnErrorRawText:()=>t$,getTurnStatus:()=>vy,getUsageRollup:()=>sp,getUserRolesWithToken:()=>vU,getVersionDiff:()=>_l,getWebPushPublicKey:()=>pm,getWorkingState:()=>XL,grantAccountSecretResource:()=>oc,grantSandboxProjectAccess:()=>j0,grantSecretToAgent:()=>IR,groupMessagesIntoTurns:()=>Aj,groupShowSegments:()=>Sy,groupSteps:()=>hy,hasDiffs:()=>p$,hasLocalhostUrls:()=>bO,hasPreviewTarget:()=>bS,hasRetryingAssistantTurn:()=>ly,heartbeatGapEvent:()=>Wb,holdSessionPrompts:()=>nu,humanizeReviewActionPath:()=>Gp,humanizeSearchQuery:()=>Tr,humanizeToolName:()=>ny,impersonationHeaders:()=>vi,importSsoProviderFromMetadata:()=>HC,inboxObservationSupersedes:()=>yF,initialWakeEscalationState:()=>By,inputPath:()=>ve,installTemplate:()=>UT,interruptSessionPrompt:()=>eu,invalidateTokenCache:()=>ms,inviteAccountMember:()=>Ni,inviteProjectMember:()=>Ia,inviteRepoCollaborator:()=>Zi,isAbortError:()=>Kr,isAdminBypassEnabled:()=>wh,isAgentPart:()=>TD,isAppRouteUrl:()=>fS,isAttachment:()=>jD,isAttachmentPartRef:()=>$P,isAuthFailure:()=>jt,isBillingError:()=>gi,isCompactionPart:()=>ID,isConfigured:()=>es,isContextTool:()=>AD,isDestructivePhase:()=>H0,isEmptyConversation:()=>Zy,isEmptyShowPart:()=>Js,isErrorOutput:()=>Oj,isExternalUrl:()=>MO,isFeatureDisabledError:()=>pi,isFilePart:()=>Zf,isImpersonationSessionLive:()=>hh,isInstanceDetailPath:()=>a0,isInstanceScopedAppPath:()=>hP,isInternalLocalhostUrl:()=>CO,isInvisibleActivityPart:()=>km,isInviteSent:()=>Hv,isLastUserMessage:()=>QL,isLegacyMigratedSession:()=>YP,isManagedGithubProject:()=>Ov,isNoGroupActivityTool:()=>wm,isOfferedModel:()=>ii,isOpenCodeConfigInvalidError:()=>f0,isPaintableSavedCopy:()=>Xh,isPatchPart:()=>MD,isPersistableQueryKey:()=>KU,isPreviewUrl:()=>RO,isProxiableLocalhostUrl:()=>PS,isQuestionTool:()=>Pm,isReasoningPart:()=>we,isRepositoryDisconnectedError:()=>ph,isRetryableTurnError:()=>Dx,isRuntimeConfigInvalidError:()=>xP,isRuntimeNotReadyResponse:()=>PP,isRuntimeReady:()=>of,isRuntimeStartingError:()=>S0,isSandboxNotReadyError:()=>bn,isSelectableAgent:()=>Xs,isServerReachable:()=>rf,isSessionAttachmentRef:()=>BI,isSessionFresh:()=>Il,isSessionLogRestoreNote:()=>Uw,isSessionStartError:()=>wR,isShellActivityTool:()=>LI,isShellMode:()=>oP,isShortOutput:()=>y$,isShowContentUnavailable:()=>lI,isShowPayloadEmpty:()=>ar,isSnapshotPart:()=>ED,isStandaloneActivityTool:()=>vm,isStepPart:()=>OD,isSubdomainPreviewUrl:()=>Vr,isTextPart:()=>Oe,isToolPart:()=>ee,isToolPartHidden:()=>UD,isTurnErrorCode:()=>fm,isUnderSandboxRoot:()=>ef,isWebProxyUrl:()=>EO,isWireIdAheadOf:()=>wb,kortixAppViewerToken:()=>dk,kortixBinding:()=>gk,kortixPty:()=>Ob,kortixToken:()=>th,latestPromptModel:()=>Bk,leaveAccount:()=>Ji,linkCaptureDevice:()=>hf,linkGitHubInstallation:()=>ba,linkRepository:()=>pa,listAccountAudit:()=>rg,listAccountAuditWebhooks:()=>ig,listAccountInvites:()=>Bi,listAccountMembers:()=>Fi,listAccountResourceGrants:()=>RC,listAccountSecretResources:()=>ec,listAccountSessions:()=>eT,listAccountTokens:()=>zd,listAccounts:()=>Ii,listActions:()=>DC,listAdminSandboxes:()=>PT,listAgentIdentities:()=>ed,listAllConnections:()=>gc,listAppAgents:()=>Rg,listAppDeployments:()=>Mg,listAppMachines:()=>Fg,listAppVolumeSnapshots:()=>Qg,listAppVolumes:()=>Vg,listApps:()=>Sg,listAssignments:()=>yd,listAuditEvents:()=>dT,listAuditWebhooks:()=>cT,listBackups:()=>N0,listBillingTransactions:()=>Uu,listCaptureDevices:()=>ff,listCaptureEnrollmentTokens:()=>_f,listCaptureEnrollments:()=>xf,listChangeRequests:()=>bl,listChannelBindings:()=>ZR,listColumns:()=>ME,listConnectSections:()=>SA,listConnectToolkits:()=>bA,listConnections:()=>dc,listConnectorAccounts:()=>_s,listConnectorMoves:()=>$c,listConnectorTools:()=>ys,listConnectors:()=>vc,listCostByProject:()=>NR,listCredentialEvents:()=>iM,listCredentials:()=>oM,listCustomLlmProviders:()=>sr,listDiscoverConnectors:()=>Ss,listDiscoverIntegrations:()=>xA,listDiscoverSections:()=>Kc,listDriveConflicts:()=>HT,listDriveFiles:()=>zT,listDriveFolder:()=>C_,listDriveVersions:()=>nI,listEnv:()=>Nm,listFeaturedMarketplaces:()=>mg,listFields:()=>DE,listFiles:()=>on,listFolderPrincipals:()=>WT,listGatewayLogs:()=>Rp,listGitHubInstallations:()=>ma,listGitHubRepositories:()=>ya,listGitHubRepositoryBranches:()=>ha,listGroupMembers:()=>Jp,listGroupProjectGrants:()=>kC,listGroups:()=>Wp,listKortixProjectSessions:()=>zE,listKortixProjects:()=>WE,listKortixPty:()=>Gm,listLinkableGitHubInstallations:()=>fa,listManagedGitRepositories:()=>wa,listMarketplaceCatalogItems:()=>dg,listMarketplaceSources:()=>hg,listMarketplaces:()=>gg,listMemberGroups:()=>vC,listMemberProjectAccess:()=>AC,listMilestoneEvents:()=>ZE,listMilestones:()=>QE,listMyAccountInvites:()=>Gi,listNotifications:()=>am,listOAuthClients:()=>ud,listOAuthGrants:()=>Qd,listPendingApprovals:()=>Ba,listPendingProjectInvites:()=>Ea,listPermissions:()=>bd,listPipedreamApps:()=>Nc,listPipedreamSections:()=>Bc,listPolicies:()=>CC,listProjectAccess:()=>Ra,listProjectAccessRequests:()=>ka,listProjectAgentIdentities:()=>td,listProjectAgents:()=>FE,listProjectAudit:()=>sg,listProjectBranches:()=>gl,listProjectCliTokens:()=>Zd,listProjectCommits:()=>ml,listProjectDirectory:()=>il,listProjectFiles:()=>ol,listProjectGroupGrants:()=>Da,listProjectPolicies:()=>zc,listProjectProviderOAuth:()=>za,listProjectReminders:()=>Dd,listProjectResourceGrants:()=>Ua,listProjectSandboxTemplates:()=>Jc,listProjectSandboxes:()=>sl,listProjectSecrets:()=>Ga,listProjectSessions:()=>At,listProjectSessionsPage:()=>jl,listProjectSnapshots:()=>Qc,listProjectTriggerEventApps:()=>vu,listProjectTriggerEventTypes:()=>ku,listProjectTriggerRuns:()=>Pu,listProjectTriggers:()=>fu,listProjects:()=>Pt,listProjectsForAccount:()=>Xi,listPublicMarketplaceItems:()=>aU,listPublicMarketplaces:()=>cU,listReferrals:()=>iC,listReviewItems:()=>Sd,listRoles:()=>Zp,listRoomMessages:()=>Nd,listRoomPeople:()=>Vd,listRooms:()=>Ld,listSandboxProjectMembers:()=>D0,listSandboxShares:()=>Ad,listSandboxes:()=>C0,listScimTokens:()=>LC,listServiceAccountsApi:()=>sT,listServiceTemplates:()=>gM,listServices:()=>dM,listSessionConnectRequests:()=>hA,listSessionCosts:()=>ap,listSessionDrives:()=>oI,listSessionPrompts:()=>Ql,listSessionProviderSecretPools:()=>lc,listSessionPublicShares:()=>ql,listSessionReminders:()=>Td,listSessionsNeedingInput:()=>Ka,listSignedInDevices:()=>OT,listSsoGroupMappings:()=>YC,listTaskEvents:()=>fE,listTasks:()=>gE,listTemplates:()=>LE,listTicketEvents:()=>kE,listTickets:()=>PE,listTriggerRuns:()=>xu,loadHttpSessionHistory:()=>Qw,loadPreviewUrlTemplate:()=>it,looksLikeError:()=>uy,looksLikeHtml:()=>zj,looksLikeJsonPayload:()=>Kj,makeDriveFolder:()=>ZT,mapApiReviewItem:()=>bC,markInstanceError:()=>nU,markNotificationsRead:()=>cm,markRoomRead:()=>Kd,markSessionFresh:()=>Kn,maxWireIdClock:()=>Lm,memoryRelPath:()=>P$,mergeBurstSteps:()=>_y,mergeChangeRequest:()=>kl,messageCreatedAt:()=>OL,messageTime:()=>Jx,migrateAdminSandboxProvider:()=>vT,mintWireMessageId:()=>yo,mintWireMessageIdAbove:()=>$m,mkdir:()=>un,modelInDefaultView:()=>Fk,modelRefToKey:()=>kn,moveConnector:()=>Uc,moveDriveFile:()=>eI,narrateFailedStep:()=>my,narrateStep:()=>Fr,narrationToolName:()=>Ur,narrowChatEvent:()=>Hb,newestWireIdClock:()=>kb,nextConnectorPollDelay:()=>DU,normalizeActivityToolName:()=>fe,normalizeAppPathname:()=>d0,normalizeCaptureAppId:()=>WO,normalizeCaptureDomain:()=>GO,normalizeExternalInput:()=>OO,normalizeName:()=>Z,normalizeToolName:()=>ty,notifyHostSignal:()=>QP,openChangeRequest:()=>wl,openEventStream:()=>So,openStressTestStream:()=>CU,paginateConnector:()=>Vc,parseBillingError:()=>Rn,parseEmbeddedFailure:()=>Wj,parseFlagOverride:()=>JI,parseJsonFailure:()=>py,parseLocalhostUrl:()=>Rr,parseMemoryView:()=>w$,parseOpenCodeErrorPayload:()=>g0,parsePresentationOutput:()=>A$,parseProxyHop:()=>sf,parseQuestionAnswersFromOutput:()=>Iy,parseReadOutput:()=>R$,parseRuntimeErrorPayload:()=>Dy,parseScrapeInputUrls:()=>$x,parseScrapeOutput:()=>Fx,parseSubdomainUrl:()=>lf,parseTaskRows:()=>_$,parseWebProxyUrl:()=>IO,parseWebSearchOutput:()=>dy,partOutcome:()=>Uo,patchKortixProject:()=>JE,patchVerb:()=>v$,pickerProviderList:()=>Mk,pipedreamConnect:()=>Dc,pipedreamConnectConnection:()=>wc,pipedreamFinalize:()=>Hc,pipedreamFinalizeConnection:()=>kc,platformConfig:()=>I,pollConnectionOAuth2DeviceAuthorization:()=>gA,pollProjectProviderOAuth:()=>ds,postRoomMessage:()=>Bd,previewBillingPlan:()=>ep,previewGatewayRoute:()=>Ap,previewMfaRequired:()=>NC,previewSlackIdentity:()=>WR,previewTeamsIdentity:()=>HR,probeEffectivePermission:()=>cd,probeEffectivePermissions:()=>ld,probePreviewPort:()=>tF,projectArchiveRequest:()=>ul,projectCompacting:()=>wF,projectConfigAgentsToOpenCodeAgents:()=>Sk,projectConfigAgentsToRuntimeAgents:()=>rh,projectSessionConnection:()=>iF,projectSessionForRuntimeId:()=>KF,projectSessionStartSeed:()=>Ru,projectWorking:()=>_F,provisionProject:()=>sa,provisionProjectStream:()=>Lv,provisionProjectWithToken:()=>qv,proxyLocalhostUrl:()=>cf,proxyUrlToInternal:()=>AO,purchaseCredits:()=>Qu,putConnectionOAuth2Application:()=>iA,putCustomLlmProvider:()=>or,rawErrorText:()=>Cr,reactivateSandbox:()=>O0,reactivateSubscription:()=>Vu,readBlob:()=>cn,readDriveFile:()=>JT,readFile:()=>an,readKortixMember:()=>oi,readProjectFile:()=>cl,readSavedSessionCopy:()=>lk,reasoningIsRunning:()=>qo,rebuildProjectSnapshot:()=>Xc,reconcileConnection:()=>mc,reconcileMemberConnection:()=>fc,reconcileServices:()=>yM,recordPlatformLogout:()=>gU,recoverLinkResults:()=>Fo,recoverProjectSession:()=>ou,refreshReferralCode:()=>rC,refreshSession:()=>Jt,registerAppArtifact:()=>Fs,registerConnectionOAuth2Client:()=>uA,registerDeviceToken:()=>sm,registerService:()=>hM,registerWebPushSubscription:()=>dm,rejectProjectAccessRequest:()=>Aa,relativizePath:()=>VD,releaseDeviceToken:()=>im,reloadProjectSessionConfig:()=>cu,reloadProjectSessionConfigStream:()=>lu,removeAccountAuditWebhook:()=>lg,removeAccountBrandingAsset:()=>$i,removeAccountMember:()=>zi,removeGroupMember:()=>Xp,removeKortixPty:()=>Vm,removeMarketplaceSource:()=>bg,removeProjectSkill:()=>ua,removeQueued:()=>XS,removeRoomPerson:()=>Hd,removeRoomSession:()=>Gd,renameConnection:()=>Sc,renameFile:()=>vr,renameSandbox:()=>R0,reopenChangeRequest:()=>Al,reopenMilestone:()=>rM,reorderQueued:()=>ex,replaceColumns:()=>OE,replaceFields:()=>jE,replaceProjectRepository:()=>da,replaceTemplates:()=>$E,replayTriggerRun:()=>wu,repositoryDisconnectedReason:()=>dh,requestAccountDeletion:()=>hT,requestChangesOnChangeRequest:()=>Rl,requestProjectAccess:()=>Wv,requestProjectConnector:()=>pg,requestProjectSecret:()=>ug,requestTopUp:()=>jR,requireKortixMember:()=>yk,resendAccountInvite:()=>qi,resendPendingProjectInvite:()=>Oa,resetAccountBranding:()=>Ui,resetClient:()=>SM,resetGatewayRoutingPolicy:()=>vp,resetPassword:()=>oo,resetPublicClient:()=>wM,resetSandboxUpdateStatus:()=>Q0,resolveApproval:()=>qa,resolveComposerAgent:()=>bk,resolveComposerModel:()=>Wk,resolveConnectorStart:()=>OU,resolveModelDefault:()=>Nk,resolvePublicShareUrl:()=>gR,resolveScrapeResults:()=>Yj,resolveWorkingTurn:()=>wy,resolvedPlan:()=>MR,restartAppMachine:()=>qg,restartProjectSession:()=>Yn,restartSandbox:()=>I0,restoreAppVolume:()=>Zg,restoreBackup:()=>K0,restoreDriveVersion:()=>rI,restoreProjectSession:()=>iu,retryAccountSecretResource:()=>rc,retryFailed:()=>QS,retrySessionPrompt:()=>tu,revealCredential:()=>cM,reviewItemTarget:()=>qp,reviewSegmentForStatus:()=>P_,reviewVerdictAllowed:()=>wC,reviewVerdictForStatus:()=>lC,revokeAccountSecretResourceGrant:()=>ic,revokeAccountSession:()=>tT,revokeAccountToken:()=>Jd,revokeAssignment:()=>_d,revokeCaptureDevice:()=>yf,revokeCaptureEnrollmentToken:()=>Sf,revokeConnection:()=>hc,revokeGatewayKey:()=>Fp,revokeOAuthGrant:()=>Xd,revokePendingProjectInvite:()=>Ma,revokeProjectAccess:()=>Ta,revokeProjectCliToken:()=>tg,revokeSandboxProjectAccess:()=>L0,revokeSandboxShare:()=>Cd,revokeScimToken:()=>UC,revokeSessionPublicShare:()=>Wl,rewriteLocalhostUrl:()=>dt,rollbackApp:()=>Ug,rootRuntimeSession:()=>JP,rotateAccountSecretResource:()=>nc,rotateOAuthClientSecret:()=>md,runConnector:()=>ks,runGatewayPlayground:()=>Np,runProjectProviderOAuthFlow:()=>Jv,runSessionReminder:()=>Ed,runtimeSessionsOf:()=>Xo,runtimeSupports:()=>uS,sanitizePtyChunk:()=>Mb,saveGitHubInstallation:()=>_a,savedCopyEmptyRoot:()=>Xy,scaleApp:()=>Wg,scheduleDowngrade:()=>zu,searchCapture:()=>Ef,searchConnectorTools:()=>pc,searchMyCapture:()=>Nf,searchProjectFiles:()=>al,segmentTurn:()=>by,selectableProjectAgents:()=>XI,sendMagicLink:()=>to,sendReferralEmails:()=>aC,serverCompactionRevalidateAtMs:()=>vF,serviceAction:()=>fM,sessionConnectionLabel:()=>UF,sessionListStatus:()=>$F,sessionLogActivityText:()=>Rw,sessionLogAnsweredQuestionCall:()=>Ow,sessionLogBurstRunning:()=>Iw,sessionLogBurstSteps:()=>Aw,sessionLogBurstSummary:()=>Cw,sessionLogBurstWorkLabel:()=>Tw,sessionLogCallStatus:()=>_w,sessionLogFullTextAction:()=>Gw,sessionLogFullTextPlan:()=>Ww,sessionLogHarnessSwitches:()=>Fw,sessionLogOfV1Rows:()=>lw,sessionLogOpenCall:()=>Ew,sessionLogPromptMessage:()=>bw,sessionLogReferencedTexts:()=>Kw,sessionLogRestoreNotice:()=>Nw,sessionLogRetrying:()=>zy,sessionLogShowGroupCall:()=>Mw,sessionLogThreadMetrics:()=>Lw,sessionLogTurnSegments:()=>kw,sessionLogTurns:()=>ti,sessionLogWithFullTexts:()=>Hw,sessionModelCandidates:()=>Gk,sessionModelFallback:()=>Kk,sessionModelPin:()=>Qn,sessionParentId:()=>uR,sessionPickStands:()=>qk,sessionPromptActions:()=>_R,sessionStartKey:()=>vR,setAccountAutomationsPaused:()=>SR,setAccountSecretResourceAccess:()=>ac,setActiveInstanceCookie:()=>u0,setAdminBypass:()=>Ph,setAdminProviderDistribution:()=>wT,setAdminProviderFallback:()=>RT,setAgentScope:()=>Mu,setBillingPlan:()=>tp,setBootstrapAuthToken:()=>Xv,setCachedAuthToken:()=>Qv,setCaptureEnabled:()=>Ff,setCapturePolicy:()=>vf,setCaptureStorage:()=>Rf,setConnectionPolicies:()=>yA,setConnectorAuthorizationStrategy:()=>Cc,setConnectorCredential:()=>Gc,setConnectorCredentialMode:()=>Rc,setConnectorName:()=>Oc,setConnectorPolicies:()=>Ec,setConnectorSecretBinding:()=>wA,setConnectorSensitive:()=>Tc,setDefaultConnection:()=>bc,setEnterpriseDemo:()=>mT,setEnv:()=>Bm,setGatewayBudget:()=>jp,setGatewayRoutingPolicy:()=>kp,setGitHubAppFromExisting:()=>UU,setGitHubAppPat:()=>FU,setImpersonationSession:()=>fv,setMaintenanceConfig:()=>kU,setMemberSuperAdmin:()=>jC,setMfaRequired:()=>BC,setModelDefault:()=>Iu,setPersonalProjectSecret:()=>Qa,setProjectModelAccess:()=>rr,setProjectModelEnablement:()=>AR,setProjectOnboardingComplete:()=>ca,setProjectOnboardingProfile:()=>Bv,setProjectPolicies:()=>Yc,setProjectSecretStrategy:()=>Ha,setProjectSessionModel:()=>du,setProjectSessionScope:()=>pu,setProjectSessionSharing:()=>Ll,setProjectTriggersActivation:()=>bu,setSavedCopyStore:()=>oR,setSessionArchived:()=>Bl,setSessionOversight:()=>qC,setSessionPinned:()=>Nl,setSessionProviderSecretPool:()=>uc,setSessionWatch:()=>Fl,setTelegramAllowedUsers:()=>JR,settleSessionConnection:()=>uF,setupSSH:()=>G0,shareConnection:()=>Pc,shareFolder:()=>qT,shellActivityGroupLabel:()=>$I,shellExitCode:()=>My,shouldAttachImpersonation:()=>Sh,shouldHideResponsePart:()=>ZL,shouldShowToolPart:()=>gn,shouldSuppressWorkingTurnBusy:()=>GL,showGroupItems:()=>xy,showTurnBusyIndicator:()=>Py,signInWithPassword:()=>eo,signInWithProvider:()=>ro,signInWithSso:()=>lo,signOut:()=>po,signOutDevice:()=>DT,signUp:()=>Zs,skillDocumentPath:()=>D$,skillInputDir:()=>E$,sortSessions:()=>vj,splitSessionLogTurnWork:()=>vw,splitTurnWork:()=>Ty,splitUserParts:()=>LD,startApp:()=>jg,startAppMachine:()=>Bg,startConnectionOAuth2Authorization:()=>pA,startConnectionOAuth2DeviceAuthorization:()=>dA,startConnectorSetupLink:()=>hU,startGitHubAppManifest:()=>$U,startProjectProviderOAuth:()=>ps,startProjectSession:()=>nt,startProjectSessionOrThrow:()=>Cu,startSessionWithToken:()=>PU,startTask:()=>bE,stepLabel:()=>yn,stopApp:()=>Lg,stopAppMachine:()=>Kg,stopProjectSession:()=>Jn,stopSandbox:()=>E0,storeGitHubUserToken:()=>Sa,stripAnsi:()=>ey,stripInstancePrefix:()=>c0,stripTrailingSlashes:()=>le,subAgentCalls:()=>jw,submitAccessRequest:()=>dU,submitDemoRequest:()=>AU,submitOAuthConsent:()=>fU,submitReviewItem:()=>wd,submitSecretSetupLink:()=>SU,subscribeToImpersonation:()=>yv,supabaseClient:()=>Tv,syncConnectors:()=>Ac,syncSubscription:()=>FR,systemReload:()=>vM,toDaemonPath:()=>pt,toInstanceAwarePath:()=>p0,toInternalUrl:()=>wS,toSandboxAbsolutePath:()=>sn,toToolView:()=>sy,toWorkspaceRelative:()=>tf,toolCallBlock:()=>lr,toolCallError:()=>J_,toolCallMetadata:()=>H_,toolCallRawOutput:()=>Y_,toolCallStatus:()=>z_,toolInfo:()=>Mo,toolKind:()=>ae,toolViewModel:()=>gP,triggerControlsFrom:()=>xC,triggerSandboxUpdate:()=>J0,triggersRequest:()=>Tb,turnEndCause:()=>VP,turnEndNotice:()=>xF,turnHasSteps:()=>Ej,turnIsConfirmedActive:()=>VL,turnRendersQueued:()=>zL,turnRetryLabel:()=>NF,unassignTicket:()=>TE,unregisterDeviceToken:()=>om,unregisterWebPushSubscription:()=>gm,unshareFolder:()=>GT,untimedAnchorOf:()=>cy,unwrapError:()=>ye,updateAccountAuditWebhook:()=>cg,updateAccountBranding:()=>ji,updateAccountMemberRole:()=>Yi,updateAccountName:()=>Oi,updateAgentConfig:()=>TR,updateApp:()=>Pg,updateAppAccess:()=>Cg,updateAppVolume:()=>Yg,updateAuditWebhook:()=>uT,updateChangeRequest:()=>Tl,updateChannelBinding:()=>eC,updateConnectionCredential:()=>yc,updateEmailPolicy:()=>Pp,updateExperimentalFeature:()=>ia,updateFeatureFlag:()=>oa,updateGroup:()=>zp,updateKortixPty:()=>Hm,updateMilestone:()=>tM,updateNotificationPreferences:()=>um,updateOAuthClient:()=>gd,updatePassword:()=>io,updatePatPolicy:()=>rT,updatePolicy:()=>IC,updateProject:()=>On,updateProjectAccess:()=>Ca,updateProjectAgent:()=>BE,updateProjectDefaultAgent:()=>Du,updateProjectGroupGrant:()=>La,updateProjectSandboxProvider:()=>aa,updateProjectSession:()=>ru,updateProjectTrigger:()=>hu,updateRole:()=>od,updateRolePermissions:()=>id,updateRoom:()=>Fd,updateSandboxTemplate:()=>tl,updateSessionPolicy:()=>ZC,updateSessionReminder:()=>Ls,updateSessionReminders:()=>Md,updateTask:()=>_E,updateTemplateWarmPool:()=>Nv,updateTicket:()=>AE,updateTicketStatus:()=>RE,updateUserMetadata:()=>co,uploadAccountBrandingAsset:()=>Li,uploadAppArtifactArchive:()=>Ig,uploadConnectorAttachment:()=>bs,uploadDriveFile:()=>QT,uploadFile:()=>ln,uploadNativeFile:()=>tS,uploadPromptAttachment:()=>Bn,uploadSessionAttachment:()=>Tm,uploadSlackChannelFile:()=>yp,uploadTimeoutMsForBytes:()=>nn,upsertCredential:()=>aM,upsertProjectGitCredential:()=>Ja,upsertProjectSecret:()=>Wa,upsertSsoProvider:()=>WC,validateProjectManifest:()=>ea,validateReferralCode:()=>sC,validateToken:()=>Qi,verifyGatewayProvider:()=>tC,verifyKortixToken:()=>_k,verifyOtp:()=>no,verifySsoDomain:()=>VC,wakeEscalationAttemptSummary:()=>jF,wakeEscalationNote:()=>OF,wakeProgressFingerprint:()=>TF,wireIdClock:()=>Tt,wireIdClockAt:()=>Zt,wireIdClockDelta:()=>It,workedForLabel:()=>g$,workingExpiryAtMs:()=>bF,workingTurnDrawsBusyRow:()=>YL,writeActivityGroupLabel:()=>UI,writeFile:()=>kr,wsDomain:()=>Bo,wsFavicon:()=>Vj,wsRootDomain:()=>Hj});var Zk={backendUrl:"",getToken:async()=>null},li=null,Xr=null;function ev(e){Xr=e}function tv(){return Xr}function Zr(e,t){t?.global!==!1&&(li=e)}function I(){return Xr?.()??li??Zk}function es(){return li!==null||Xr?.()!==void 0}function nv(e){return new Promise(t=>setTimeout(t,e))}async function ts(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(o&&n?.(),s>0&&await nv(s)),i=await e(),i)return i;return i}var ui=12e4;function rv(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function lh(e,t,n=ui){let r=e instanceof Request?e.signal:t?.signal;if(rv(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function ns(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var P=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},re=class extends P{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},et=class extends P{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},bt=class extends P{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},sv="ENDPOINT_RETIRED";function N(e,t){let n=t?` ${t}`:"";return new P(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:sv})}var Dt="feature_disabled";function uh(e){if(!(e instanceof P)||e.status!==403||e.code!==Dt)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function pi(e){let t=uh(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function di(e){let t=uh(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}var An="repository_disconnected",ov=new Set(["app_uninstalled","app_suspended","repo_not_accessible"]);function ph(e){return!!e&&typeof e=="object"&&e.code===An}function dh(e){if(e?.status!=="error")return null;let t=e.last_error_code;return t&&ov.has(t)?t:null}function Rn(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 et(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 gi(e){return e instanceof et}function jt(e){if(e instanceof re)return!0;let t=e?.status;return t===401||t===403}function mi(e){if(!(e instanceof et))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 Ae(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function Re(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(Ae())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function rs(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(Ae())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var gh="request_deadline",iv=/^Request exceeded the \d+s server processing deadline$/,mh=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===gh||iv.test(n),av="git_mirror_unavailable",cv=/^git mirror is temporarily unavailable$/,lv=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===av||cv.test(n),uv="connectors_provider_unavailable",pv=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===uv;async function dv(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await Re(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 Ae();return{message:n,data:r}}function gv(e,t,n){return mh(e,t,n)||lv(e,t,n)||pv(e,t)||e===403&&t?.code===Dt||e===501&&t?.code===fi||e===409&&(t?.code===yi||t?.code===hi||t?.code===_i||t?.code===An)||e===503&&(t?.code===bi||t?.code===Si)}async function fh(e,t,n,r){let{message:s,data:o}=await dv(e,t),i=new P(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:mh(e.status,o,s)?gh:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=Rn(i));let a=e.status===403&&(o?.code==="account_mfa_required"||o?.code==="sso_required")?o.code:null;if(a){try{I().onAccessRemedy?.(a)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a==="account_mfa_required"?"kortix:mfa-required":"kortix:sso-required"))}catch{}}return e.status===431&&(i=new bt(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&&!gv(e.status,o,s)&&I().onError?.(i,r),{error:i,success:!1}}var yh="X-Kortix-Impersonate",Pi="kortix.impersonation",St=null,ss=!1,xi=new Set;function wi(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function hh(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 mv(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 _h(){for(let e of xi)try{e()}catch{}}function bh(){return ss||(ss=!0,St=mv(wi()?.getItem(Pi)??null)),St&&!hh(St)?(ki(),null):St}function fv(e){if(ss=!0,!e){ki();return}St=e;try{wi()?.setItem(Pi,JSON.stringify(e))}catch{}_h()}function ki(){ss=!0;let e=St!==null;St=null;try{wi()?.removeItem(Pi)}catch{}e&&_h()}function yv(e){return xi.add(e),()=>{xi.delete(e)}}var hv=/(^|\/)admin\/(api|analytics)(\/|$)/;function Sh(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!hv.test(t)}function vi(e){if(e!==void 0&&!Sh(e))return{};let t=bh();return t?{[yh]:t.grantId}:{}}function Ph(e){}function wh(){return!1}function _v(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function os(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Cn(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function is(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(_v))Cn(n,s,o);return n}function Ri(e,t,n){let r={...t},s=I().clientVersion?.trim();s&&!os(r,"x-kortix-client-version")&&Cn(r,"X-Kortix-Client-Version",s);for(let[i,a]of Object.entries(vi(e)))Cn(r,i,a);let o=I().credentialHeader?.trim();return o?os(r,o)||Cn(r,o,n):os(r,"authorization")||Cn(r,"Authorization",`Bearer ${n}`),r}async function Lt(e,t){let n=await as();if(!n)throw new re;return{headers:new Headers(Ri(e,is(e,{headers:t}),n)),rejected:()=>Tn(n)}}function bv(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function xh(e,t,n,r,s){if(t instanceof Request){let l=new Headers(Ri(t.url,is(t,n),r));return e(new Request(t,{headers:l,...s?{signal:s}:{}}))}let o=String(t),i=Ri(o,is(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var kh=null;async function Ci(e){let t=await ts(()=>I().getToken(),e);return t&&(kh=t),t}var as=Ci;function Tn(e=kh){e&&I().getToken.invalidate?.(e)}var Ai=new Map;function Sv(e){let t=Ai.get(e);if(t)return t;let n=(async()=>(Tn(e),as({attempts:2,baseDelayMs:200})))().finally(()=>Ai.delete(e));return Ai.set(e,n),n}async function xt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=ui}=n,o=n.fetch??I().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:lh(e,t,s);if(i?.aborted)throw Ae();let a=await(i?Re(as(),i):as());if(!a)throw new re;let l=r&&!bv(t)&&!os(is(e,t),"authorization"),p=l&&e instanceof Request?e.clone():e,d=await xh(o,e,t,a,i);if(d.status!==401||!l)return d;let g=await Sv(a);return!g||g===a?d:xh(o,p,t,g,i)}async function Le(e,t,n,r){let s=await xt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new P(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var vh=()=>I().backendUrl||"",xv=new Set([502,503,504]),Pv=e=>xv.has(e),Ah=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},wv=e=>Ah(e)||(e??"GET").toUpperCase()==="DELETE",kv=2,cs=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function $e(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...i}=t,a=new AbortController,l={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>l.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await vv(e,i,n,r,s,o,a,l)}finally{i.signal?.removeEventListener("abort",p)}}async function vv(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw Ae();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},s);let l={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Rv(e,t,l,s,o,i,a);if(p instanceof re)return{error:p,success:!1};if(!p.ok)return await fh(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await Re(p.json(),a.activeController.signal):g?.includes("text/")?d=await Re(p.text(),a.activeController.signal):d=await Re(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(l){return Cv(l,e,t.method,n,r,s,a)}finally{ls(a)}}function ls(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Av(e,t,n){try{await Re(e.arrayBuffer(),t)}catch(r){if(cs(r))throw r}finally{ls(n)}}async function Rv(e,t,n,r,s,o,i){let a=Ah(t.method),l=wv(t.method),p=l?kv+1:1,d;for(let g=0;g<p;g++){g>0&&await rs(250*2**(g-1),t.signal??void 0);let m=g===0?o:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await Re(xt(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 re)return new re;if(i.didTimeout&&cs(f)&&!t.signal?.aborted&&l&&g<p-1){i.didTimeout=!1;continue}if(cs(f)||g===p-1)throw f;continue}if(!a||!Pv(d.status)||g===p-1)return s||ls(i),d;await Av(d,m.signal,i)}return d}function Cv(e,t,n,r,s,o,i){ls(i);let a=cs(e);a&&(i.isAborted=!0);let l;if(a){if(!i.didTimeout)return{error:new P("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(vh(),"")||t;l=new P(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(l=new P(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(vh(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&I().onError?.(l,s)):(l=new P(String(e)),r&&I().onError?.(l,s));return{error:l,success:!1}}var Ue=()=>I().backendUrl||"",fi="feature_not_supported",yi="model_not_servable",hi="provision_in_flight",_i="sandbox_state_change_in_progress",bi="analytics_unavailable",Si="accounts_list_unavailable",Tv={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new P(r.message||"Database error",{code:r.code,details:r});return I().onError?.(s,t),{error:s,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new P(n.message,{name:n.name||"ApiError",stack:n.stack}):new P(String(n));return I().onError?.(r,t),{error:r,success:!1}}}};async function Iv(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await xt(`${Ue()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof re)return ns();throw a}finally{clearTimeout(i)}}var c={putRaw:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>$e(`${Ue()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>$e(`${Ue()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>$e(`${Ue()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],$e(`${Ue()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],$e(`${Ue()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:Iv};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function Ti(e){return e.replace(/\/v1\/?$/,"")}async function $t(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=Ti(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 Ii(){return u(await c.get("/accounts"))}async function Ei(e){return u(await c.post("/accounts",e))}async function Mi(e){return u(await c.get(`/accounts/${e}`))}async function Oi(e,t){return u(await c.patch(`/accounts/${e}`,{name:t}))}async function Di(e){return u(await c.get(`/accounts/${e}/branding`))}async function ji(e,t){return u(await c.put(`/accounts/${e}/branding`,t))}async function Li(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),u(await c.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function $i(e,t){return u(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function Ui(e){return u(await c.delete(`/accounts/${e}/branding`))}async function Fi(e){return u(await c.get(`/accounts/${e}/members`))}async function Ni(e,t){return u(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Bi(e){return u(await c.get(`/accounts/${e}/invites`))}async function Ki(e,t){return u(await c.delete(`/accounts/${e}/invites/${t}`))}async function qi(e,t){return u(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Gi(){return u(await c.get("/account-invites",{showErrors:!1})).invites}async function Wi(e){return u(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function us(e){return u(await c.post(`/account-invites/${e}/accept`,{}))}function Rh(e,t){let n=e.bootstrap_grants_applied?.[0]??t?.projects?.[0];return n?{kind:"project",projectId:n.project_id,accountId:e.account_id}:{kind:"account",accountId:e.account_id}}async function Hi(e,t){let n=await us(e);return{accepted:n,landing:Rh(n,t)}}async function Vi(e){return u(await c.post(`/account-invites/${e}/decline`,{}))}async function zi(e,t){return u(await c.delete(`/accounts/${e}/members/${t}`))}async function Yi(e,t,n){return u(await c.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Ji(e){return u(await c.post(`/accounts/${e}/leave`,{}))}async function Ev(e){return $t(e,"/v1/accounts")}async function Qi(){let e=await c.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var Mv=["marketplace","connectors_api_discover","agentmail_email","meta_agent","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","genui","us_region","event_triggers","notification_center","volumes","drives","session_log_restore","connectors_v2","agent_rooms","goals"];async function Pt(){return u(await c.get("/projects"))}async function Xi(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/projects${t}`))}async function wt(e,t){return u(await c.get(`/projects/${e}`,t))}async function Zi(e,t,n="write"){return u(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function ea(e,t){return u(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function ta(e){return u(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function Ov(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function In(e,t){let n=u(await c.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function En(e,t){return u(await c.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Mn(e,t){return u(await c.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function Dv(e,t){return u(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function na(e){return u(await c.post("/projects",e))}async function ra(e){return u(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function sa(e,t={}){return u(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Th="provision_stream_unterminated",Ch=200;function jv(e){let t=e.split(`
|
|
2
2
|
`).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
|
|
3
|
-
`);try{return JSON.parse(n)}catch(r){let s=n.length>
|
|
3
|
+
`);try{return JSON.parse(n)}catch(r){let s=n.length>Ch?`${n.slice(0,Ch)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function Lv(e,t,n={}){let r=await c.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let l=await r.json().catch(()=>null);throw new P(l?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:l?.code})}let s=r.body?.getReader();if(!s)throw new Error("Provision stream is unavailable on this runtime (no response body)");let o=new TextDecoder,i="",a=null;try{for(;;){let{done:l,value:p}=await s.read();if(l)break;i+=o.decode(p,{stream:!0});let d=i.indexOf(`
|
|
4
4
|
|
|
5
5
|
`);for(;d!==-1;){let g=i.slice(0,d);i=i.slice(d+2),d=i.indexOf(`
|
|
6
6
|
|
|
7
|
-
`);let m=Ov(g);if(m){if(t(m),m.type==="error")throw new x(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new x("Provision stream ended without a result",{code:Rh});return a}async function jv(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await c.get(`/projects/quota${t}`))}async function Lv(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function On(e,t){return u(await c.patch(`/projects/${e}`,t))}async function sa(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function oa(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function ia(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function $v(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function Uv(e,t){throw N("updateTemplateWarmPool")}async function aa(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function Fv(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Dn(e){return u(await c.delete(`/projects/${e}`))}async function Nv(e,t){return $t(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function Bv(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Ci(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let s=await r.json().catch(()=>null);return s?.project_id?{ok:!0,project:s}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function ca(e,t,n){return u(await c.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function la(e,t,n){return u(await c.post(`/projects/${e}/skills/remove`,t,{showErrors:!1,...n}))}async function Kv(e){return u(await c.get(`/projects/${e}/git/connection`),"Failed to read the Git connection")}async function ua(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function pa(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function da(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ga(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ma(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function fa(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await c.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function ya(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await c.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function ha(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function _a(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function ba(e){return u(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function Sa(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await c.delete(`/projects/github/installation?${n.toString()}`))}async function Pa(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function xa(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await c.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function qv(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function wa(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function ka(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function va(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Aa(e){return u(await c.get(`/projects/${e}/access`))}async function Ra(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function Ca(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function Gv(e){return"status"in e&&e.status==="invited"}async function Ta(e,t,n,r){return u(await c.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Ia(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function Ea(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Ma(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Oa(e){return u(await c.get(`/projects/${e}/group-grants`))}async function Da(e,t,n,r){return u(await c.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function ja(e,t,n,r){return u(await c.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function La(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function $a(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function Ua(e,t){return u(await c.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function Fa(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function Na(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Ba(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Ka(e,t,n,r={}){let s=r.note?.trim();return u(await c.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function qa(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Ga(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function Wa(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Ha(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Va(e){return u(await c.get(`/projects/${e}/oauth`)).items??[]}async function us(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function ps(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function za(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Wv=2e3,Hv=3e3,Vv=10*6e4;async function zv(e){let{projectId:t,provider:n,input:r,onChallenge:s,isCancelled:o,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,l=()=>o?.()??!1,p=await us(t,n,r);if(l())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Wv,p.interval_ms||Hv),g=p.expires_at||a()+Vv;for(;!l()&&a()<g;){if(await i(d),l())return{status:"cancelled"};let m;try{m=await ps(t,n,p.flow_id)}catch{continue}if(l())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return l()?{status:"cancelled"}:{status:"expired"}}async function Ya(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function jn(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Ja(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Qa(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var Xa=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Ut=(e,t)=>`${Xa(e)}/${encodeURIComponent(t)}`,Ch=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Za(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${Xa(e)}${n}`))}async function ec(e,t){return u(await c.post(Xa(e),t))}async function tc(e,t,n){return u(await c.put(`${Ut(e,t)}/value`,{value:n}))}async function nc(e,t){return u(await c.post(`${Ut(e,t)}/retry`))}async function rc(e,t){return u(await c.delete(Ut(e,t)))}async function sc(e,t,n,r){return u(await c.put(`${Ut(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function oc(e,t,n,r){return u(await c.delete(`${Ut(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function ic(e,t,n,r){return u(await c.put(`${Ut(e,t)}/access`,{mode:n,user_ids:r}))}async function ac(e,t,n){return u(await c.get(Ch(e,t,n)))}async function cc(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function lc(e,t,n,r){return u(await c.put(Ch(e,t,n),{secret_ids:r}))}async function ds(){return Ri()}async function Th(e){return es(()=>I().getToken(),e,gs)}function gs(){Tn()}function Yv(e){e===null&&Tn()}function Jv(e){}async function Ft(){return ds()}async function Qv(e){return Th(e)}async function $(e,t,n){try{return await Pt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof re)return ts();throw r}}function ms(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Nt(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 c.get(`${ms(e,"catalog")}${r}`)).connectors??[]}async function fs(e){let t=[];for(let n of await Nt(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 uc(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await fs(e)){let l=`${a.tool} ${a.description}`.toLowerCase();!r||l.includes(r)?o.push(a):s.every(p=>l.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function ys(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await Nt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===r);if(!s)return null;for(let o of s.actions){let i=`${s.slug}.${o.path}`;if(i===t)return{tool:i,connector:s.slug,action:o.path,risk:o.risk,description:o.description||o.name,inputSchema:o.inputSchema,outputSchema:o.outputSchema??null}}return null}function Xv(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 Zv=9e4;async function kt(e,t,n={},r={}){let{connector:s,action:o}=Xv(t),i=r.account?.trim(),a=r.approvalContext?.trim(),l=u(await c.post(ms(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??Zv,signal:r.signal}));return l.ok&&l.binding!==void 0&&!("output"in l)&&(l.output=l.data),l}async function hs(e,t){let n=await c.get(ms(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function eA(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 tA(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}async function _s(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(o["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=tA(I().backendUrl),a=ms(e,"attachments"),l=await $(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await l.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!l.ok)throw new x(eA(d,l.status),{status:l.status,code:String(d&&typeof d=="object"?d.code??l.status:l.status),details:d,response:l,endpoint:a});return d}function nA(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 pc(e){return u(await c.get(`/projects/${e}/connections`))}async function dc(e){return u(await c.get(`/projects/${e}/connections/all`))}async function gc(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function mc(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function fc(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function Fe(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function rA(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function sA(e,t,n){return u(await c.put(Fe(e,t,"application"),n))}async function oA(e,t){return u(await c.get(Fe(e,t,"application")))}async function iA(e,t,n){return u(await c.post(Fe(e,t,"discover"),n))}async function aA(e,t,n={}){return u(await c.post(Fe(e,t,"discover-resource"),n))}async function cA(e,t,n){return u(await c.post(Fe(e,t,"register"),n))}async function lA(e,t,n){return u(await c.post(Fe(e,t,"authorize"),n))}async function uA(e,t,n){return u(await c.post(Fe(e,t,"device"),n))}async function pA(e,t,n){return u(await c.post(Fe(e,t,`device/${encodeURIComponent(n)}`),{}))}async function dA(e,t){return u(await c.get(Fe(e,t,"status")))}async function yc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function hc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function _c(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function bc(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Sc(e,t){return u(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Pc(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function xc(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function wc(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function kc(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await c.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function vc(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Ac(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Rc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Cc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Tc(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Ic(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function gA(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function mA(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Ec(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Mc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Ih(e,t,n={}){return u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var Oc=Ih;async function fA(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Dc(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function jc(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function yA(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function Lc(e){return u(await c.get(`/projects/${e}/connector-moves`)).moves}async function $c(e,t,n={}){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/move`,n.connectionId?{connection_id:n.connectionId}:{}))}async function Uc(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Fc(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/apps${o?`?${o}`:""}`))}async function Nc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function hA(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=u(await c.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function _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 c.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function bs(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await c.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function Bc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function Ss(e,t){let n=new URLSearchParams({id:t});return u(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var bA=bs,SA=Ss;async function Kc(){return u(await c.get("/connectors/connect-status"))}async function qc(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function Gc(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function PA(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Eh(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Wc=Eh;var Ln=class extends x{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds:l,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=s,this.action=o,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=l??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},Ps=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},xs=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,s){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=s,Object.setPrototypeOf(this,new.target.prototype)}},Ce=e=>typeof e=="string"&&e?e:null;function Mh(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function xA(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function wA(e,t,n){if(!(e instanceof x)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Ce(r.reason)??Ce(r.error)??e.message,o=/^upstream_(\d{3})\b/.exec(s),i=typeof r.upstream_status=="number"?r.upstream_status:o?Number(o[1]):null;return new Ln(Ce(r.message)??Ce(r.hint)??s,{status:e.status,code:i===null?Mh(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Ce(r.connector)??t,action:Ce(r.action)??n,binding:Ce(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:xA(e.response),connectUrl:Ce(r.connect_url),hint:Ce(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Ce(r.requested_account)})}function kA(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function ws(e,t,n,r={},s={}){let o=t.trim(),i=n.trim();if(!o||!i)throw new Error("connector slug and action are required");let a;try{a=await kt(e,`${o}.${i}`,r,s)}catch(l){throw wA(l,o,i)}if(a.status==="pending_approval")throw new Ps(o,i,a);if(!a.ok||a.upstream_error){let l=a.upstream_error??a.reason??"connector_error";throw new Ln(l,{status:200,code:a.upstream_error?"upstream_error":Mh(l),details:a,data:a,reason:l,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return kA(a)}async function*Hc(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,l=r;for(let p=0;l;p++){if(p>=i)throw new xs(t,n,i,l);let d=await ws(e,t,n,l,a);yield d,l=o(d,l)}}async function Vc(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function zc(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Yc(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Jc(e){return u(await c.get(`/projects/${e}/snapshots`))}async function $n(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Qc(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Xc(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Zc(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function el(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function tl(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function nl(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function rl(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Un(e){let t=new URL(I().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 Lt(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function sl(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function ol(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),t?.cursor&&n.set("cursor",t.cursor),t?.limit!==void 0&&n.set("limit",String(t.limit)),u(await c.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function il(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await c.get(`/projects/${e}/files/search?${r.toString()}`))}async function al(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await c.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var vA=10*6e4;async function cl(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=`${I().backendUrl||""}/projects/${e}/files/archive${s}`;return await(await Le(o,{method:"GET"},{timeoutMs:vA},"Failed to download")).blob()}async function ll(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Un(`${I().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function AA(e,t,n,r){let s=new URLSearchParams({path:t});n&&s.set("ref",n);let o=s.toString()?`?${s.toString()}`:"",i=`${I().backendUrl||""}/projects/${e}/files/raw${o}`;return await(await Le(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var ul=52428800,RA=104857600,Oh=20;var vs=e=>`/projects/${encodeURIComponent(e)}/attachments`,As={showErrors:!1,deadlineCoversBody:!0},Dh=3e4,CA=12e4,TA=6e4,IA=5*6e4,EA=6e4,MA=6e4;function ks(){return new x("Request aborted",{name:"AbortError",code:"ABORTED"})}function Fn(e){if(e?.aborted)throw ks()}function OA(e){return!(e instanceof x)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Nn(e,t,n=!1){let r;for(let s=0;;s++){Fn(t);try{return await e()}catch(o){let i=n&&o instanceof x&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(OA(o)||i))throw o;r??=Date.now()+(n?IA:TA);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await ns(a,t)}catch{throw Fn(t),o}}}}function DA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function pl(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&DA(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!i)throw new Error("Invalid attachment upload handle");return e}async function jh(e,t,n,r){return u(await c.post(vs(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...As,signal:n,timeout:Dh}),"Failed to start attachment upload")}async function Lh(e,t,n,r){let s=pl({...await Nn(()=>jh(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function $h(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new x(r,{status:e,details:n,code:String(n?.statusCode??e)})}function jA(e){if(!(e instanceof x))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function LA(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,l=!1,p,d=f=>{l||(l=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?o(f):s())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new x("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},EA)},m=()=>{d(ks()),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($h(i.status,i.responseText))},i.onerror=()=>d(new x("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(ks()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function $A(e,t,n){let r=I().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?ks():new x(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw $h(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function UA(e,t,n){Fn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?LA(r,e,t,n):$A(e,t,n)}async function FA(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let i=s.upload;try{await Nn(()=>UA(i,t,r),r.signal)}catch(a){let l=jA(a);if(l!==409){if(o||!(l===400||l===401||l===403))throw a;o=!0,s=await Lh(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return Uh(e,t,s,r)}async function Uh(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${vs(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Fn(r.signal);let a=i.received_bytes,l=Math.min(a+s,t.size),p=t.slice(a,l),d=await Nn(async()=>u(await c.putRaw(`${o}/chunks/${a/s}`,p,{...As,signal:r.signal,timeout:Dh}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==l)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:l},r.onUpload?.(i),r.onProgress?.(l,t.size)}return i}async function Bn(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");Fn(n.signal);let r=n.resume?pl({...n.resume},t):pl({...await Nn(()=>jh(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()<MA&&(r=await Lh(e,t,r,n)),r=r.upload.kind==="direct"?await FA(e,t,r,n):await Uh(e,t,r,n)),n.onProcessing?.();let s=`${vs(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Nn(async()=>u(await c.post(`${s}/complete`,{},{...As,signal:n.signal,timeout:CA}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof x&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Bt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${vs(e)}/${encodeURIComponent(t)}`,{...As,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function dl(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/branches${r}`))}async function gl(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/commits${r}`))}async function ml(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function fl(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function yl(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await c.get(`/projects/${e}/files/history?${r.toString()}`))}async function hl(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await c.get(`/projects/${e}/version-diff?${n.toString()}`))}async function _l(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit)),n?.cursor&&r.set("cursor",n.cursor);let s=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function bl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function Sl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function Pl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function xl(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function wl(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function kl(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function vl(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Al(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Rl(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function Cl(e,t,n){return u(await c.patch(`/projects/${e}/change-requests/${t}`,n))}var Kt=new Set,NA=500;function Kn(e){e&&(Kt.add(e),Kt.size>NA&&Kt.delete(Kt.values().next().value))}function Tl(e){return!!e&&Kt.has(e)}function BA(e){e&&Kt.delete(e)}var ce="kortix.session/2",_e=1,Fh=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var se=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),z=e=>typeof e=="string",Te=e=>z(e)&&e.length>0,Be=e=>e===null||z(e),J=(e,t)=>e===void 0||t(e),Ne=(...e)=>t=>e.includes(t),qn=e=>Number.isInteger(e)&&e>=0,qt=e=>typeof e=="number",Kh=e=>e.schema===ce&&qn(e.v),vt=e=>J(e,z),Il=e=>e===void 0||se(e)&&Object.values(e).every(t=>se(t)&&z(t.version)),qh=e=>e===null||se(e)&&z(e.provider)&&z(e.model)&&vt(e.variant),KA=e=>e===null||se(e)&&qt(e.input)&&qt(e.output)&&qt(e.cache_read)&&qt(e.cache_write)&&J(e.reasoning,qt)&&J(e.cost,qt),Nh=e=>se(e)&&(e.type==="text"&&z(e.text)||e.type==="attachment"&&z(e.mime)),qA=e=>se(e)&&Array.isArray(e.content)&&e.content.every(Nh)&&J(e.model_content,t=>Array.isArray(t)&&t.every(Nh))&&typeof e.is_error=="boolean",Bh={text:e=>z(e.text)&&J(e.bytes,qn)&&vt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>z(e.text),attachment:e=>z(e.mime)&&vt(e.ref)&&J(e.bytes,qn)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>z(e.call_id)&&z(e.name)&&Te(e.kind)&&Ne("pending","running","complete","error")(e.status)&&J(e.result,qA),compaction:e=>Be(e.summary)&&Be(e.first_kept_message_id),subtask:e=>z(e.thread_id)&&z(e.agent)&&z(e.description),step:e=>Ne("start","finish")(e.phase),harness:e=>Te(e.harness)&&Te(e.kind)&&typeof e.model_visible=="boolean"};function GA(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!se(r)||!Te(r.id)||n.has(r.id)||!Object.hasOwn(Bh,r.type)||!Bh[r.type](r)||!Il(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function El(e){return se(e)&&Kh(e)&&Te(e.message_id)&&Te(e.thread_id)&&Number.isInteger(e.seq)&&Ne("user","assistant","system")(e.role)&&Ne("turn","compaction","context")(e.kind)&&Ne("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&J(e.hidden_reason,Ne("failed_attempt","aborted","retracted","reverted","superseded"))&&J(e.origin,Ne("prompt","steer","command","automation","subagent","notification"))&&J(e.agent,Be)&&J(e.reply_to,Be)&&J(e.parent_message_id,Be)&&vt(e.native_agent_id)&&vt(e.context_ref)&&qh(e.model)&&KA(e.usage)&&Ne("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||se(e.error)&&Te(e.error.code)&&z(e.error.message))&&z(e.created_at)&&Be(e.completed_at)&&se(e.producer)&&Te(e.producer.harness)&&z(e.producer.harness_version)&&z(e.producer.adapter_version)&&Il(e.ext)&&GA(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function Ml(e){return se(e)&&Kh(e)&&Te(e.thread_id)&&Be(e.parent_thread_id)&&(e.spawned_by===null||se(e.spawned_by))&&z(e.created_at)}function WA(e){return se(e)&&J(e.schema,t=>t===ce)&&J(e.v,qn)&&vt(e.session_id)&&J(e.title,Be)&&vt(e.created_at)&&J(e.restore_grade,Ne("native","converted","partial"))&&J(e.todos,Array.isArray)&&J(e.pending,t=>se(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&J(e.selection,t=>se(t)&&J(t.agent,Be)&&qh(t.model??null))&&J(e.harness,t=>se(t)&&z(t.current)&&Array.isArray(t.history))&&Il(e.ext)}function Gt(e){return se(e)&&qn(e.generation)&&typeof e.has_more=="boolean"&&WA(e.session)&&Array.isArray(e.threads)&&e.threads.every(Ml)&&(e.thread_id===null||Te(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>El(t)&&t.thread_id===e.thread_id)}var HA=e=>Gt(e)&&e.messages.length>0;function VA(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let s=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(s.length<=t)return s}return null}var Gh={paintable:HA,fit:VA,capturedAt:()=>0},zA=new WeakMap;function Wh(e,t,n){zA.set(e,{read:(r,s)=>t.read(r,s),write:async(r,s,o)=>{await t.write(r,s,o),await n(r,s)}})}function Rs(e){return!!e&&typeof e.then=="function"}function Hh(e,t){return Rs(e)?e.then(t):t(e)}function Vh(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:s,now:o}=e,i=`${n}index`,a=T=>{try{let _=t.getItem(T);return Rs(_)?_.catch(()=>null):_}catch{return null}},l=async T=>{try{await t.removeItem(T)}catch{}},p=T=>{if(!T)return[];try{let _=JSON.parse(T);return _?.v===1&&Array.isArray(_.entries)?_.entries:[]}catch{return[]}},d=Promise.resolve(),g=T=>{let _=d.then(T,T);return d=_.catch(()=>{}),_},m=async T=>{try{await t.setItem(i,JSON.stringify({v:1,entries:T}))}catch{}},f=async()=>p(await a(i));return{indexKey:i,safeGet:a,safeRemove:l,enqueue:g,loadIndex:f,saveIndex:m,evict:async(T,_)=>{let b=[...T].sort((y,w)=>y.u-w.u),O=b.reduce((y,w)=>y+w.b,0);for(;b.length>r||O>s;){let y=b.findIndex(P=>P.s!==_);if(y===-1)break;let[w]=b.splice(y,1);O-=w.b,await l(`${n}${w.s}`)}return b},touch:T=>{g(async()=>{let _=await f(),b=_.find(O=>O.s===T);b&&(b.u=o(),await m(_))})},forgetScope:T=>g(async()=>{await l(`${n}${T}`);let _=await f(),b=_.filter(O=>O.s!==T);b.length!==_.length&&await m(b)})}}function Jh(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 YA=12,JA=15e5,QA=3e5,XA=336*60*60*1e3,Qh="kortix.saved-copy";function ZA(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let s=a=>{let l=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:l,message_count:l.length,complete:!1,next_cursor:String(l[0].info.id)}})},o=s(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(o+a>t)break;o+=a,i+=1}for(;i>0;i-=1){let a=s(i);if(a.length<=t)return a}return null}function eR(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var tR={paintable:Jh,fit:ZA,capturedAt:eR};function nR(e){let t=Yh(e,tR),n=Yh({...e,namespace:`${e.namespace??Qh}.log`},Gh),r={...t,remove:async(s,o)=>{await Promise.all([t.remove(s,o),n.remove(s,o)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return Wh(r,n,t.remove),r}function Yh(e,t){let{storage:n,userId:r,maxSessions:s=YA,maxBytes:o=JA,maxEnvelopeBytes:i=QA,maxAgeMs:a=XA,namespace:l=Qh,now:p=()=>Date.now()}=e,d=`${l}:${r}:`,g=Vh({storage:n,prefix:d,maxSessions:s,maxBytes:o,now:p}),{indexKey:m,safeGet:f,safeRemove:h,enqueue:S,loadIndex:v,saveIndex:T,evict:_,touch:b,forgetScope:O}=g,y=(P,k)=>`${d}${P}/${k}`,w=P=>{try{let k=n.removeItem(P);Rs(k)&&k.catch(()=>{})}catch{}};return{keyFor:y,read(P,k){let C=`${P}/${k}`;return Hh(f(y(P,k)),j=>{if(!j)return null;let R;try{R=JSON.parse(j)}catch{return w(y(P,k)),O(C),null}return!R||R.v!==1||R.user!==r||p()-R.at>a||!t.paintable(R.e)?(w(y(P,k)),O(C),null):(b(C),R.e)})},write(P,k,C){let j=`${P}/${k}`;if(!t.paintable(C))return O(j);let R={v:1,user:r,at:p(),e:C},L=t.fit(R,i);if(L===null)return O(j);let pe=t.capturedAt(C);return S(async()=>{let D=await v(),q=D.find(ht=>ht.s===j);if(q&&pe>0&&q.c>pe)return;let W=D.filter(ht=>ht.s!==j),K={s:j,b:L.length,u:p(),c:pe},je=await _([...W,K],j),ii=y(P,k);try{await n.setItem(ii,L)}catch{let ht=je.filter(_t=>_t.s!==j).sort((_t,Gk)=>_t.u-Gk.u)[0];ht&&(await h(`${d}${ht.s}`),je=je.filter(_t=>_t.s!==ht.s));try{await n.setItem(ii,L)}catch{await h(ii),je=je.filter(_t=>_t.s!==j)}}await T(je)})},remove(P,k){return O(`${P}/${k}`)},clear(){return S(async()=>{let P=await v();for(let k of P)await h(`${d}${k.s}`);await h(m)})}}}var Xh=null;function rR(e){Xh=e}function Ol(){return Xh}var sR=new Set;function Zh(e){for(let t of sR)try{t(e)}catch{}}var oR=new Set;function e_(e){for(let t of oR)try{t(e)}catch{}}var Gn=async(e,t,n,r)=>{let s=new URLSearchParams;n.thread!==void 0&&s.set("thread",n.thread),n.before_seq!==void 0&&s.set("before_seq",String(n.before_seq)),n.limit!==void 0&&s.set("limit",String(n.limit));let o=s.toString(),i=await c.get(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/log${o?`?${o}`:""}`,{showErrors:!1,signal:r});if(!i.success)throw i.error??new Error("Session log request failed");return i.data},iR=40;async function aR(e,t,n,r,s){try{let o=await e(t,n,r,s);return Gt(o)?o:null}catch{return null}}function t_(e,t,n,r){return aR(e,t,n,{limit:iR},r)}function cR(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 lR=50,n_=200,uR=n_;function r_(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return e?.view&&t.set(e.view,"only"),t.size>0?`?${t}`:""}async function Dl(e,t){let n=await c.get(`/projects/${e}/sessions${r_(t)}`,{showErrors:!1});return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function At(e,t){return u(await c.get(`/projects/${e}/sessions${r_(t)}`))}async function jl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Ll(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function $l(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Ul(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Fl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Nl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function pR(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 dR(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 Bl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function Kl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function ql(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Gl(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Rt(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return!t?.initial_prompt&&!t?.fork_from_session_id&&Kn(n?.session_id),n}async function Wl(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await c.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Kn(r.session.session_id),r}async function Hl(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Kn(n.session_id),n}async function Wn(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Vl(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return u(await c.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function zl(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function Hn(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await c.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Yl(e,t,n={},r){let s;try{s=await Gn(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!Gt(s))throw new Error("The response is not a session log page");return s}async function Vn(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function gR(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function mR(e){if(e)return e==="interrupt"?"transcript":"composer"}async function zn(e,t,n){let r=n.placement??mR(n.delivery);return u(await c.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Jl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Ql(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Xl(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Zl(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function eu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function tu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function nu(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function ru(e,t){let n=u(await c.delete(`/projects/${e}/sessions/${t}`));return Ol()?.remove(e,t),e_(t),n}async function su(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function ou(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Yn(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Jn(e,t){let n=u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}));return Zh(t),n}async function iu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function fR(e){let t=e.split(`
|
|
7
|
+
`);let m=jv(g);if(m){if(t(m),m.type==="error")throw new P(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new P("Provision stream ended without a result",{code:Th});return a}async function $v(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await c.get(`/projects/quota${t}`))}async function Uv(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function On(e,t){return u(await c.patch(`/projects/${e}`,t))}async function oa(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function ia(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function aa(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function Fv(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function Nv(e,t){throw N("updateTemplateWarmPool")}async function ca(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function Bv(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Dn(e){return u(await c.delete(`/projects/${e}`))}async function Kv(e,t){return $t(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function qv(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Ti(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let s=await r.json().catch(()=>null);return s?.project_id?{ok:!0,project:s}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function la(e,t,n){return u(await c.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function ua(e,t,n){return u(await c.post(`/projects/${e}/skills/remove`,t,{showErrors:!1,...n}))}async function Gv(e){return u(await c.get(`/projects/${e}/git/connection`),"Failed to read the Git connection")}async function pa(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function da(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function ga(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ma(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function fa(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function ya(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await c.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function ha(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await c.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function _a(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function ba(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Sa(e){return u(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function xa(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await c.delete(`/projects/github/installation?${n.toString()}`))}async function Pa(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function wa(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await c.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function Wv(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function ka(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function va(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Aa(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Ra(e){return u(await c.get(`/projects/${e}/access`))}async function Ca(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function Ta(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function Hv(e){return"status"in e&&e.status==="invited"}async function Ia(e,t,n,r){return u(await c.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Ea(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function Ma(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Oa(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Da(e){return u(await c.get(`/projects/${e}/group-grants`))}async function ja(e,t,n,r){return u(await c.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function La(e,t,n,r){return u(await c.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function $a(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function Ua(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function Fa(e,t){return u(await c.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function Na(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function Ba(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Ka(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function qa(e,t,n,r={}){let s=r.note?.trim();return u(await c.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function Ga(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Wa(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function Ha(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Va(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function za(e){return u(await c.get(`/projects/${e}/oauth`)).items??[]}async function ps(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function ds(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Ya(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Vv=2e3,zv=3e3,Yv=10*6e4;async function Jv(e){let{projectId:t,provider:n,input:r,onChallenge:s,isCancelled:o,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,l=()=>o?.()??!1,p=await ps(t,n,r);if(l())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Vv,p.interval_ms||zv),g=p.expires_at||a()+Yv;for(;!l()&&a()<g;){if(await i(d),l())return{status:"cancelled"};let m;try{m=await ds(t,n,p.flow_id)}catch{continue}if(l())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return l()?{status:"cancelled"}:{status:"expired"}}async function Ja(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function jn(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Qa(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Xa(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var Za=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Ut=(e,t)=>`${Za(e)}/${encodeURIComponent(t)}`,Ih=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function ec(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${Za(e)}${n}`))}async function tc(e,t){return u(await c.post(Za(e),t))}async function nc(e,t,n){return u(await c.put(`${Ut(e,t)}/value`,{value:n}))}async function rc(e,t){return u(await c.post(`${Ut(e,t)}/retry`))}async function sc(e,t){return u(await c.delete(Ut(e,t)))}async function oc(e,t,n,r){return u(await c.put(`${Ut(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function ic(e,t,n,r){return u(await c.delete(`${Ut(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function ac(e,t,n,r){return u(await c.put(`${Ut(e,t)}/access`,{mode:n,user_ids:r}))}async function cc(e,t,n){return u(await c.get(Ih(e,t,n)))}async function lc(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function uc(e,t,n,r){return u(await c.put(Ih(e,t,n),{secret_ids:r}))}async function gs(){return Ci()}async function Eh(e){return ts(()=>I().getToken(),e,ms)}function ms(){Tn()}function Qv(e){e===null&&Tn()}function Xv(e){}async function Ft(){return gs()}async function Zv(e){return Eh(e)}async function $(e,t,n){try{return await xt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof re)return ns();throw r}}function fs(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Nt(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 c.get(`${fs(e,"catalog")}${r}`)).connectors??[]}async function ys(e){let t=[];for(let n of await Nt(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 pc(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await ys(e)){let l=`${a.tool} ${a.description}`.toLowerCase();!r||l.includes(r)?o.push(a):s.every(p=>l.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function hs(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await Nt(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===r);if(!s)return null;for(let o of s.actions){let i=`${s.slug}.${o.path}`;if(i===t)return{tool:i,connector:s.slug,action:o.path,risk:o.risk,description:o.description||o.name,inputSchema:o.inputSchema,outputSchema:o.outputSchema??null}}return null}function eA(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 tA=9e4;async function kt(e,t,n={},r={}){let{connector:s,action:o}=eA(t),i=r.account?.trim(),a=r.approvalContext?.trim(),l=u(await c.post(fs(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??tA,signal:r.signal}));return l.ok&&l.binding!==void 0&&!("output"in l)&&(l.output=l.data),l}async function _s(e,t){let n=await c.get(fs(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function nA(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 rA(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 bs(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(o["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=rA(I().backendUrl),a=fs(e,"attachments"),l=await $(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await l.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!l.ok)throw new P(nA(d,l.status),{status:l.status,code:String(d&&typeof d=="object"?d.code??l.status:l.status),details:d,response:l,endpoint:a});return d}function sA(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 dc(e){return u(await c.get(`/projects/${e}/connections`))}async function gc(e){return u(await c.get(`/projects/${e}/connections/all`))}async function mc(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function fc(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function yc(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function Fe(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function oA(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function iA(e,t,n){return u(await c.put(Fe(e,t,"application"),n))}async function aA(e,t){return u(await c.get(Fe(e,t,"application")))}async function cA(e,t,n){return u(await c.post(Fe(e,t,"discover"),n))}async function lA(e,t,n={}){return u(await c.post(Fe(e,t,"discover-resource"),n))}async function uA(e,t,n){return u(await c.post(Fe(e,t,"register"),n))}async function pA(e,t,n){return u(await c.post(Fe(e,t,"authorize"),n))}async function dA(e,t,n){return u(await c.post(Fe(e,t,"device"),n))}async function gA(e,t,n){return u(await c.post(Fe(e,t,`device/${encodeURIComponent(n)}`),{}))}async function mA(e,t){return u(await c.get(Fe(e,t,"status")))}async function hc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function _c(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function bc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function Sc(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function xc(e,t){return u(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Pc(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function wc(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function kc(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function vc(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await c.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function Ac(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Rc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Cc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Tc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Ic(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Ec(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function fA(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function yA(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Mc(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Oc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Mh(e,t,n={}){return u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var Dc=Mh;async function hA(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function jc(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function Lc(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function _A(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function $c(e){return u(await c.get(`/projects/${e}/connector-moves`)).moves}async function Uc(e,t,n={}){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/move`,n.connectionId?{connection_id:n.connectionId}:{}))}async function Fc(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Nc(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/apps${o?`?${o}`:""}`))}async function Bc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function bA(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=u(await c.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function SA(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function Ss(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await c.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function Kc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function xs(e,t){let n=new URLSearchParams({id:t});return u(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var xA=Ss,PA=xs;async function qc(){return u(await c.get("/connectors/connect-status"))}async function Gc(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function Wc(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function wA(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Oh(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Hc=Oh;var Ln=class extends P{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds:l,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=s,this.action=o,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=l??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},Ps=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},ws=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,s){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=s,Object.setPrototypeOf(this,new.target.prototype)}},Ce=e=>typeof e=="string"&&e?e:null;function Dh(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function kA(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function vA(e,t,n){if(!(e instanceof P)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Ce(r.reason)??Ce(r.error)??e.message,o=/^upstream_(\d{3})\b/.exec(s),i=typeof r.upstream_status=="number"?r.upstream_status:o?Number(o[1]):null;return new Ln(Ce(r.message)??Ce(r.hint)??s,{status:e.status,code:i===null?Dh(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Ce(r.connector)??t,action:Ce(r.action)??n,binding:Ce(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:kA(e.response),connectUrl:Ce(r.connect_url),hint:Ce(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Ce(r.requested_account)})}function AA(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 ks(e,t,n,r={},s={}){let o=t.trim(),i=n.trim();if(!o||!i)throw new Error("connector slug and action are required");let a;try{a=await kt(e,`${o}.${i}`,r,s)}catch(l){throw vA(l,o,i)}if(a.status==="pending_approval")throw new Ps(o,i,a);if(!a.ok||a.upstream_error){let l=a.upstream_error??a.reason??"connector_error";throw new Ln(l,{status:200,code:a.upstream_error?"upstream_error":Dh(l),details:a,data:a,reason:l,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return AA(a)}async function*Vc(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,l=r;for(let p=0;l;p++){if(p>=i)throw new ws(t,n,i,l);let d=await ks(e,t,n,l,a);yield d,l=o(d,l)}}async function zc(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function Yc(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Jc(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Qc(e){return u(await c.get(`/projects/${e}/snapshots`))}async function $n(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Xc(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Zc(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function el(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function tl(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function nl(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function rl(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function sl(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Un(e){let t=new URL(I().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 Lt(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function ol(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function il(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),t?.cursor&&n.set("cursor",t.cursor),t?.limit!==void 0&&n.set("limit",String(t.limit)),u(await c.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function al(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await c.get(`/projects/${e}/files/search?${r.toString()}`))}async function cl(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await c.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var RA=10*6e4;async function ll(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=`${I().backendUrl||""}/projects/${e}/files/archive${s}`;return await(await Le(o,{method:"GET"},{timeoutMs:RA},"Failed to download")).blob()}async function ul(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Un(`${I().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function CA(e,t,n,r){let s=new URLSearchParams({path:t});n&&s.set("ref",n);let o=s.toString()?`?${s.toString()}`:"",i=`${I().backendUrl||""}/projects/${e}/files/raw${o}`;return await(await Le(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var pl=52428800,TA=104857600,jh=20;var As=e=>`/projects/${encodeURIComponent(e)}/attachments`,Rs={showErrors:!1,deadlineCoversBody:!0},Lh=3e4,IA=12e4,EA=6e4,MA=5*6e4,OA=6e4,DA=6e4;function vs(){return new P("Request aborted",{name:"AbortError",code:"ABORTED"})}function Fn(e){if(e?.aborted)throw vs()}function jA(e){return!(e instanceof P)||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 Nn(e,t,n=!1){let r;for(let s=0;;s++){Fn(t);try{return await e()}catch(o){let i=n&&o instanceof P&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(jA(o)||i))throw o;r??=Date.now()+(n?MA:EA);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await rs(a,t)}catch{throw Fn(t),o}}}}function LA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function dl(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&LA(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!i)throw new Error("Invalid attachment upload handle");return e}async function $h(e,t,n,r){return u(await c.post(As(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Rs,signal:n,timeout:Lh}),"Failed to start attachment upload")}async function Uh(e,t,n,r){let s=dl({...await Nn(()=>$h(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function Fh(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 P(r,{status:e,details:n,code:String(n?.statusCode??e)})}function $A(e){if(!(e instanceof P))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function UA(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,l=!1,p,d=f=>{l||(l=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?o(f):s())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new P("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},OA)},m=()=>{d(vs()),i.abort()};i.open(t.method,t.url);for(let[f,h]of Object.entries(t.headers))i.setRequestHeader(f,h);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d(Fh(i.status,i.responseText))},i.onerror=()=>d(new P("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(vs()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function FA(e,t,n){let r=I().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?vs():new P(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw Fh(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function NA(e,t,n){Fn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?UA(r,e,t,n):FA(e,t,n)}async function BA(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let i=s.upload;try{await Nn(()=>NA(i,t,r),r.signal)}catch(a){let l=$A(a);if(l!==409){if(o||!(l===400||l===401||l===403))throw a;o=!0,s=await Uh(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return Nh(e,t,s,r)}async function Nh(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${As(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Fn(r.signal);let a=i.received_bytes,l=Math.min(a+s,t.size),p=t.slice(a,l),d=await Nn(async()=>u(await c.putRaw(`${o}/chunks/${a/s}`,p,{...Rs,signal:r.signal,timeout:Lh}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==l)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:l},r.onUpload?.(i),r.onProgress?.(l,t.size)}return i}async function Bn(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");Fn(n.signal);let r=n.resume?dl({...n.resume},t):dl({...await Nn(()=>$h(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()<DA&&(r=await Uh(e,t,r,n)),r=r.upload.kind==="direct"?await BA(e,t,r,n):await Nh(e,t,r,n)),n.onProcessing?.();let s=`${As(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Nn(async()=>u(await c.post(`${s}/complete`,{},{...Rs,signal:n.signal,timeout:IA}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof P&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Bt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${As(e)}/${encodeURIComponent(t)}`,{...Rs,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function gl(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/branches${r}`))}async function ml(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/commits${r}`))}async function fl(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function yl(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function hl(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await c.get(`/projects/${e}/files/history?${r.toString()}`))}async function _l(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await c.get(`/projects/${e}/version-diff?${n.toString()}`))}async function bl(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit)),n?.cursor&&r.set("cursor",n.cursor);let s=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function Sl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function xl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function Pl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function wl(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function kl(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function vl(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Al(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Rl(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Cl(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function Tl(e,t,n){return u(await c.patch(`/projects/${e}/change-requests/${t}`,n))}var Kt=new Set,KA=500;function Kn(e){e&&(Kt.add(e),Kt.size>KA&&Kt.delete(Kt.values().next().value))}function Il(e){return!!e&&Kt.has(e)}function qA(e){e&&Kt.delete(e)}var ce="kortix.session/2",_e=1,Bh=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var se=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),z=e=>typeof e=="string",Te=e=>z(e)&&e.length>0,Be=e=>e===null||z(e),J=(e,t)=>e===void 0||t(e),Ne=(...e)=>t=>e.includes(t),qn=e=>Number.isInteger(e)&&e>=0,qt=e=>typeof e=="number",Gh=e=>e.schema===ce&&qn(e.v),vt=e=>J(e,z),El=e=>e===void 0||se(e)&&Object.values(e).every(t=>se(t)&&z(t.version)),Wh=e=>e===null||se(e)&&z(e.provider)&&z(e.model)&&vt(e.variant),GA=e=>e===null||se(e)&&qt(e.input)&&qt(e.output)&&qt(e.cache_read)&&qt(e.cache_write)&&J(e.reasoning,qt)&&J(e.cost,qt),Kh=e=>se(e)&&(e.type==="text"&&z(e.text)||e.type==="attachment"&&z(e.mime)),WA=e=>se(e)&&Array.isArray(e.content)&&e.content.every(Kh)&&J(e.model_content,t=>Array.isArray(t)&&t.every(Kh))&&typeof e.is_error=="boolean",qh={text:e=>z(e.text)&&J(e.bytes,qn)&&vt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>z(e.text),attachment:e=>z(e.mime)&&vt(e.ref)&&J(e.bytes,qn)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>z(e.call_id)&&z(e.name)&&Te(e.kind)&&Ne("pending","running","complete","error")(e.status)&&J(e.result,WA),compaction:e=>Be(e.summary)&&Be(e.first_kept_message_id),subtask:e=>z(e.thread_id)&&z(e.agent)&&z(e.description),step:e=>Ne("start","finish")(e.phase),harness:e=>Te(e.harness)&&Te(e.kind)&&typeof e.model_visible=="boolean"};function HA(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!se(r)||!Te(r.id)||n.has(r.id)||!Object.hasOwn(qh,r.type)||!qh[r.type](r)||!El(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function Ml(e){return se(e)&&Gh(e)&&Te(e.message_id)&&Te(e.thread_id)&&Number.isInteger(e.seq)&&Ne("user","assistant","system")(e.role)&&Ne("turn","compaction","context")(e.kind)&&Ne("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&J(e.hidden_reason,Ne("failed_attempt","aborted","retracted","reverted","superseded"))&&J(e.origin,Ne("prompt","steer","command","automation","subagent","notification"))&&J(e.agent,Be)&&J(e.reply_to,Be)&&J(e.parent_message_id,Be)&&vt(e.native_agent_id)&&vt(e.context_ref)&&Wh(e.model)&&GA(e.usage)&&Ne("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||se(e.error)&&Te(e.error.code)&&z(e.error.message))&&z(e.created_at)&&Be(e.completed_at)&&se(e.producer)&&Te(e.producer.harness)&&z(e.producer.harness_version)&&z(e.producer.adapter_version)&&El(e.ext)&&HA(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function Ol(e){return se(e)&&Gh(e)&&Te(e.thread_id)&&Be(e.parent_thread_id)&&(e.spawned_by===null||se(e.spawned_by))&&z(e.created_at)}function VA(e){return se(e)&&J(e.schema,t=>t===ce)&&J(e.v,qn)&&vt(e.session_id)&&J(e.title,Be)&&vt(e.created_at)&&J(e.restore_grade,Ne("native","converted","partial"))&&J(e.todos,Array.isArray)&&J(e.pending,t=>se(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&J(e.selection,t=>se(t)&&J(t.agent,Be)&&Wh(t.model??null))&&J(e.harness,t=>se(t)&&z(t.current)&&Array.isArray(t.history))&&El(e.ext)}function Gt(e){return se(e)&&qn(e.generation)&&typeof e.has_more=="boolean"&&VA(e.session)&&Array.isArray(e.threads)&&e.threads.every(Ol)&&(e.thread_id===null||Te(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>Ml(t)&&t.thread_id===e.thread_id)}var zA=e=>Gt(e)&&e.messages.length>0;function YA(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let s=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(s.length<=t)return s}return null}var Hh={paintable:zA,fit:YA,capturedAt:()=>0},JA=new WeakMap;function Vh(e,t,n){JA.set(e,{read:(r,s)=>t.read(r,s),write:async(r,s,o)=>{await t.write(r,s,o),await n(r,s)}})}function Cs(e){return!!e&&typeof e.then=="function"}function zh(e,t){return Cs(e)?e.then(t):t(e)}function Yh(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:s,now:o}=e,i=`${n}index`,a=T=>{try{let _=t.getItem(T);return Cs(_)?_.catch(()=>null):_}catch{return null}},l=async T=>{try{await t.removeItem(T)}catch{}},p=T=>{if(!T)return[];try{let _=JSON.parse(T);return _?.v===1&&Array.isArray(_.entries)?_.entries:[]}catch{return[]}},d=Promise.resolve(),g=T=>{let _=d.then(T,T);return d=_.catch(()=>{}),_},m=async T=>{try{await t.setItem(i,JSON.stringify({v:1,entries:T}))}catch{}},f=async()=>p(await a(i));return{indexKey:i,safeGet:a,safeRemove:l,enqueue:g,loadIndex:f,saveIndex:m,evict:async(T,_)=>{let b=[...T].sort((y,w)=>y.u-w.u),O=b.reduce((y,w)=>y+w.b,0);for(;b.length>r||O>s;){let y=b.findIndex(x=>x.s!==_);if(y===-1)break;let[w]=b.splice(y,1);O-=w.b,await l(`${n}${w.s}`)}return b},touch:T=>{g(async()=>{let _=await f(),b=_.find(O=>O.s===T);b&&(b.u=o(),await m(_))})},forgetScope:T=>g(async()=>{await l(`${n}${T}`);let _=await f(),b=_.filter(O=>O.s!==T);b.length!==_.length&&await m(b)})}}function Xh(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 QA=12,XA=15e5,ZA=3e5,eR=336*60*60*1e3,Zh="kortix.saved-copy";function tR(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let s=a=>{let l=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:l,message_count:l.length,complete:!1,next_cursor:String(l[0].info.id)}})},o=s(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(o+a>t)break;o+=a,i+=1}for(;i>0;i-=1){let a=s(i);if(a.length<=t)return a}return null}function nR(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var rR={paintable:Xh,fit:tR,capturedAt:nR};function sR(e){let t=Qh(e,rR),n=Qh({...e,namespace:`${e.namespace??Zh}.log`},Hh),r={...t,remove:async(s,o)=>{await Promise.all([t.remove(s,o),n.remove(s,o)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return Vh(r,n,t.remove),r}function Qh(e,t){let{storage:n,userId:r,maxSessions:s=QA,maxBytes:o=XA,maxEnvelopeBytes:i=ZA,maxAgeMs:a=eR,namespace:l=Zh,now:p=()=>Date.now()}=e,d=`${l}:${r}:`,g=Yh({storage:n,prefix:d,maxSessions:s,maxBytes:o,now:p}),{indexKey:m,safeGet:f,safeRemove:h,enqueue:S,loadIndex:v,saveIndex:T,evict:_,touch:b,forgetScope:O}=g,y=(x,k)=>`${d}${x}/${k}`,w=x=>{try{let k=n.removeItem(x);Cs(k)&&k.catch(()=>{})}catch{}};return{keyFor:y,read(x,k){let C=`${x}/${k}`;return zh(f(y(x,k)),j=>{if(!j)return null;let R;try{R=JSON.parse(j)}catch{return w(y(x,k)),O(C),null}return!R||R.v!==1||R.user!==r||p()-R.at>a||!t.paintable(R.e)?(w(y(x,k)),O(C),null):(b(C),R.e)})},write(x,k,C){let j=`${x}/${k}`;if(!t.paintable(C))return O(j);let R={v:1,user:r,at:p(),e:C},L=t.fit(R,i);if(L===null)return O(j);let pe=t.capturedAt(C);return S(async()=>{let D=await v(),q=D.find(ht=>ht.s===j);if(q&&pe>0&&q.c>pe)return;let W=D.filter(ht=>ht.s!==j),K={s:j,b:L.length,u:p(),c:pe},je=await _([...W,K],j),ai=y(x,k);try{await n.setItem(ai,L)}catch{let ht=je.filter(_t=>_t.s!==j).sort((_t,Hk)=>_t.u-Hk.u)[0];ht&&(await h(`${d}${ht.s}`),je=je.filter(_t=>_t.s!==ht.s));try{await n.setItem(ai,L)}catch{await h(ai),je=je.filter(_t=>_t.s!==j)}}await T(je)})},remove(x,k){return O(`${x}/${k}`)},clear(){return S(async()=>{let x=await v();for(let k of x)await h(`${d}${k.s}`);await h(m)})}}}var e_=null;function oR(e){e_=e}function Dl(){return e_}var iR=new Set;function t_(e){for(let t of iR)try{t(e)}catch{}}var aR=new Set;function n_(e){for(let t of aR)try{t(e)}catch{}}var Gn=async(e,t,n,r)=>{let s=new URLSearchParams;n.thread!==void 0&&s.set("thread",n.thread),n.before_seq!==void 0&&s.set("before_seq",String(n.before_seq)),n.limit!==void 0&&s.set("limit",String(n.limit));let o=s.toString(),i=await c.get(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/log${o?`?${o}`:""}`,{showErrors:!1,signal:r});if(!i.success)throw i.error??new Error("Session log request failed");return i.data},cR=40;async function lR(e,t,n,r,s){try{let o=await e(t,n,r,s);return Gt(o)?o:null}catch{return null}}function r_(e,t,n,r){return lR(e,t,n,{limit:cR},r)}function uR(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 pR=50,s_=200,dR=s_;function o_(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return e?.view&&t.set(e.view,"only"),t.size>0?`?${t}`:""}async function jl(e,t){let n=await c.get(`/projects/${e}/sessions${o_(t)}`,{showErrors:!1});return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function At(e,t){return u(await c.get(`/projects/${e}/sessions${o_(t)}`))}async function Ll(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function $l(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Ul(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Fl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Nl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Bl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function gR(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 mR(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 Kl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function ql(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Gl(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Wl(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Rt(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return!t?.initial_prompt&&!t?.fork_from_session_id&&Kn(n?.session_id),n}async function Hl(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await c.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Kn(r.session.session_id),r}async function Vl(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Kn(n.session_id),n}async function Wn(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function zl(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return u(await c.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function Yl(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function Hn(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await c.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Jl(e,t,n={},r){let s;try{s=await Gn(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!Gt(s))throw new Error("The response is not a session log page");return s}async function Vn(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function fR(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function yR(e){if(e)return e==="interrupt"?"transcript":"composer"}async function zn(e,t,n){let r=n.placement??yR(n.delivery);return u(await c.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Ql(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Xl(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Zl(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function eu(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function tu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function nu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function ru(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function su(e,t){let n=u(await c.delete(`/projects/${e}/sessions/${t}`));return Dl()?.remove(e,t),n_(t),n}async function ou(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function iu(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Yn(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Jn(e,t){let n=u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}));return t_(t),n}async function au(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function hR(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 cu(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function lu(e,t,n,r,s={}){let o=await c.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,s);if(!o.ok){let d=await o.json().catch(()=>null);throw new P(d?.error||`Reload failed: HTTP ${o.status}`,{status:o.status,code:d?.code,data:d})}let i=o.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,l="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;l+=a.decode(g,{stream:!0});let m=l.indexOf(`
|
|
10
10
|
|
|
11
11
|
`);for(;m!==-1;){let f=l.slice(0,m);l=l.slice(m+2),m=l.indexOf(`
|
|
12
12
|
|
|
13
|
-
`);let h=fR(f);if(h){if(r(h),h.type==="error")throw new x(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function lu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function uu(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function pu(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Qn(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function du(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function gu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function yR(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 mu(e){return u(await c.get(`/projects/${e}/triggers`))}async function fu(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function yu(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function hu(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function hR(e){return u(await c.get(`/accounts/${e}/automations`))}async function _R(e,t){return u(await c.patch(`/accounts/${e}/automations`,{paused:t},{showErrors:!1}))}async function _u(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function s_(e){let t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.limit!=null&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function bu(e,t,n){let r={};return n?.payload!==void 0&&(r.payload=n.payload),n?.dryRun!==void 0&&(r.dry_run=n.dryRun),u(await c.post(`/projects/${e}/triggers/${t}/fire`,r))}async function Su(e,t,n){return u(await c.get(`/projects/${e}/triggers/${t}/runs${s_(n)}`))}async function Pu(e,t){return u(await c.get(`/projects/${e}/trigger-runs${s_(t)}`))}async function xu(e,t,n,r){return u(await c.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function wu(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await c.get(`/projects/${e}/triggers/event-types?${n}`))}async function ku(e){return u(await c.get(`/projects/${e}/triggers/event-apps`))}var tt=new Map;function vu(e,t){return`${e}::${t}`}function o_(e,t){tt.delete(e),tt.set(e,t)}function i_(e,t){let n=vu(e,t),r=tt.get(n);return r&&o_(n,r),r}function Cs(e,t,n){let r=vu(e,t);if(!tt.has(r)&&tt.size>=512){let s=tt.keys().next().value;s!==void 0&&tt.delete(s)}o_(r,n)}function a_(e,t){tt.delete(vu(e,t))}function bR(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Xn(){return bR(I().backendUrl||"http://localhost:8008/v1")}function c_(){let e=I().sandboxId;return e?`${Xn()}/p/${e}/8000`:""}function SR(e,t=8e3){return`${Xn()}/p/${e}/${t}`}function Ie(e,t=8e3){return SR(e,t)}function Au(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 Ts=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 PR(e){return e instanceof Error&&e.name==="SessionStartError"}function xR(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Ts(s,{status:n,code:r,terminal:!0}):null}function l_(e,t,n){let r=typeof n=="number"?n:n?.waitMs,s=typeof n=="number"?void 0:n?.repositoryMode,o=new URLSearchParams;r&&r>0&&o.set("wait_ms",String(Math.floor(r))),s&&o.set("repository_mode",s),typeof n=="object"&&n?.keepStopped&&o.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&o.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=o.size>0?`?${o.toString()}`:"";return c.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function nt(e,t,n){let r=await l_(e,t,n);if(!r.success||!r.data){let s=xR(r.error);if(s&&!(s.status===404&&Tl(t)))throw s;return null}return u_(e,t,r.data)}async function Ru(e,t,n){let r=await l_(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return u_(e,t,r.data)}function u_(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Cs(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Ie(r),sandboxId:r}),n}function wR(e,t){return["session-start",e,t]}async function Cu(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function Tu(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function Iu(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await c.delete(`/projects/${e}/model-defaults?${n}`))}async function kR(e,t){return u(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function p_(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function vR(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Is(e){let t=e.connectors_required?p_(e.connectors_required):void 0,n=e.connectors_personal?p_(e.connectors_personal):void 0;if(t&&n&&!vR(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 Eu(e,t,n){let r=Is(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function AR(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Mu(n.block):null}}async function RR(e,t,n){let r=Mu(n,!0),s=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Mu(s.block):null}}function Mu(e,t=!1){let n=Is(e);if(n.workspace===void 0)return n;let r=n.workspace==="branch";if(n.repository_access!==void 0&&n.repository_access!==r)throw new Error("repository_access conflicts with workspace");if(t&&n.workspace==="read"&&n.repository_access===void 0)throw new Error("Legacy read is unavailable. Set repository_access explicitly.");return n.repository_access??=r,delete n.workspace,n}async function CR(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Ou(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}var Es="Use setBillingPlan().",d_="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Du(){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",monthly_usd:null,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 TR(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function IR(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,monthlyUsd:t.monthly_usd??null};let n=e??Du(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:TR(r),label:s,sublabel:null,monthlyUsd:null}}function g_(e){return!!e&&e.can_manage_billing!==!1}function ER(e){return e?.subscription?.can_purchase_credits===!0&&g_(e)}async function m_(e){let t=await c.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?Du():t.data}function f_(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 ju(e){return m_(`/billing/account-state${f_(e)}`)}async function Lu(e){return m_(`/billing/account-state/minimal${f_(e)}`)}async function $u(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await c.get(`/billing/transactions${n?`?${n}`:""}`))}async function Uu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await c.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Fu(){return u(await c.get("/billing/credit-breakdown"))}async function Nu(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function Bu(){return u(await c.get("/billing/tier-configurations"))}async function MR(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return $t(e,`/v1/billing/account-state${t}`)}async function Ku(e){throw N("createCheckoutSession",Es)}async function qu(e,t){throw N("confirmCheckoutSession",Es)}async function Gu(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Wu(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Hu(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Vu(e,t,n){throw N("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function zu(e){throw N("cancelScheduledChange",d_)}async function Yu(e,t){throw N("getProrationPreview",d_)}async function Ju(e){return u(await c.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Qu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function OR(e){return u(await c.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Xu(e){return u(await c.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function DR(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function Zu(e){return u(await c.post("/billing/plan/preview",{monthly_usd:e.monthlyUsd,account_id:e.accountId}),"Failed to preview the plan change")}async function ep(e){return u(await c.post("/billing/plan",{monthly_usd:e.monthlyUsd,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale,account_id:e.accountId}),"Failed to set billing plan")}async function tp(e){return u(await c.post("/billing/enterprise-offer/checkout",{success_url:e.successUrl,cancel_url:e.cancelUrl,account_id:e.accountId}),"Failed to start the Enterprise checkout")}async function np(e={}){return u(await c.post("/billing/enterprise/contact",{account_id:e.accountId,...e.note?{note:e.note}:{}}),"Failed to reach Kortix sales")}async function jR(e){throw N("createPerSeatCheckout",Es)}async function LR(e){throw N("claimPerSeatBilling",Es)}async function $R(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function rp(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await c.get(`/usage${n?`?${n}`:""}`))}function op(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Ms(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Os(e){return e.size>0?`?${e}`:""}async function ip(e={}){let t=new URLSearchParams;return op(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Ms(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/session-costs${Os(t)}`))}async function Zn(e,t={}){let n=new URLSearchParams;return op(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Os(n)}`))}async function UR(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Ms(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/cost-by-project${Os(t)}`))}async function FR(e={}){let t=new URLSearchParams;return op(t,e),e.sessionId&&t.set("session_id",e.sessionId),Ms(t,e),u(await c.get(`/usage/cost-summary${Os(t)}`))}function sp(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let s=t;s.ownerId&&n.set("owner_id",s.ownerId)}Ms(n,t),t.sort&&n.set("sort",t.sort),n.set("format","csv");let r=e==="projects"?"/usage/cost-by-project":"/usage/session-costs";return`${I().backendUrl||""}${r}?${n}`}async function NR(e,t={}){let n=sp(e==="projects"?"projects":"sessions",t),r=await Le(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),s=r.headers.get("x-kortix-row-cap"),o=s!=null?Number(s):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(o)?o:null}}async function y_(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function BR(e){return y_("slack",e)}function KR(e){return y_("teams",e)}async function h_(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function qR(e){return h_("slack",e)}function GR(e){return h_("teams",e)}async function ap(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function cp(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var WR={oauth_available:!1,install_url:null};async function lp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?WR:t.data}async function __(e,t,n){return u(await c.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function up(e,t){return __("slack",e,t)}function pp(e,t){return __("teams",e,t)}async function dp(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function gp(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function HR(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/telegram/installation`,{showErrors:!1});return t.success?t.data??null:null}async function VR(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/telegram/connect`,t,{showErrors:!1}),"Failed to connect Telegram")}async function zR(e,t){return u(await c.put(`/projects/${encodeURIComponent(e)}/channels/telegram/allowed-users`,{user_ids:t},{showErrors:!1}),"Failed to update allowed Telegram users")}async function YR(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/telegram`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect Telegram")}async function mp(e,t){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function fp(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function yp(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 JR={provider:"agentmail",managed_available:!1};async function hp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?yp(r.data):null}async function _p(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?JR:t.data}async function bp(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return yp(n)}async function Sp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function Pp(e,t,n){let r=u(await c.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return yp(r)}async function QR(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function XR(e,t,n){return u(await c.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function xp(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function wp(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function kp(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function vp(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Ap(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await c.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function Rp(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Cp(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Tp(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ip(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ep(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Mp(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Op(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Dp(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function jp(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Lp(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function $p(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Up(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Fp(e,t,n,r,s){return u(await c.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function ZR(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function eC(){throw N("getReferralCode")}async function tC(){throw N("refreshReferralCode")}async function nC(e){throw N("validateReferralCode")}async function rC(){throw N("getReferralStats")}async function sC(e={}){throw N("listReferrals")}async function oC(e){throw N("sendReferralEmails")}var Np="call:";function Kp(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Np)&&e.length>Np.length?{type:"connector_call",executionId:e.slice(Np.length)}:{type:"review_item",reviewItemId:e}}function S_(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function iC(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[S_(n.status)]+=1;return t}function aC(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 Bp(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function qp(e){let t=e.indexOf(".");return t<=0?Bp(e):`(${Bp(e.slice(0,t))}) ${Bp(e.slice(t+1))}`}function cC(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Wt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,Ee=e=>Array.isArray(e)?e:void 0,b_=e=>typeof e=="number"?e:0,lC=e=>e.split(`
|
|
14
|
-
`).map(t=>t.trim()).filter(Boolean);function uC(e,t){let n=Wt(e.advanced),r=U(e.description),s=Ee(e.whatChanged)??(r?lC(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:U(e.impact)??"",verification:Ee(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:Ee(e.conflicts),requestedChanges:Ee(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:b_(n.additions),deletions:b_(n.deletions),files:Ee(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function pC(e,t){let n=Ee(e.actions);if(n)return{actions:n.map((l,p)=>({id:U(l.id)??`${t.review_item_id}-${p}`,title:U(l.title)??"Action",connector:U(l.connector)??"",action:U(l.action)??"",consequence:U(l.consequence)??"",risk:U(l.risk)??t.risk,icon:U(l.icon)??"generic",argsPreview:Ee(l.argsPreview)??[],policySource:U(l.policySource)??"Requires approval",decided:l.decided==="approved"||l.decided==="denied"?l.decided:void 0}))};let r=U(e.action_path)??"",{connector:s,action:o}=cC(r),i=Wt(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?qp(r):t.title||"Run action",connector:s,connectorName:U(e.connector_name),action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([l,p])=>({key:l,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:U(e.approval_context),...Object.keys(Wt(e.resolved_preview)).length>0?{resolvedPreview:Wt(e.resolved_preview)}:{},...U(e.resolved_error)?{resolvedError:U(e.resolved_error)}:{},connectorRisk:U(e.risk)??null,policySource:"Requires approval",expiresAt:U(t.expires_at)}]}}function dC(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:Ee(e.files),note:U(e.note)??t.summary??""}}function gC(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:Ee(e.options)??[]}}function mC(e,t){return{note:U(e.note)??t.summary??"",children:Ee(e.children)??[]}}function fC(e){let t=Wt(e.detail);switch(e.kind){case"change":return uC(t,e);case"approval":return pC(t,e);case"output":return dC(t,e);case"decision":return gC(t,e);case"batch":return mC(t,e)}}function yC(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 hC(e,t={}){let n=Wt(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?U(n.action_path):void 0,i=e.kind==="change"?yC(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:o?qp(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,expiresAt:U(e.expires_at),detail:fC(e)}}var Q={PROJECT_READ:"project.read",PROJECT_WRITE:"project.write",PROJECT_DELETE:"project.delete",PROJECT_SESSION_READ:"project.session.read",PROJECT_SESSION_START:"project.session.start",PROJECT_SESSION_STOP:"project.session.stop",PROJECT_SESSION_BINDINGS_WRITE:"project.session.bindings.write",PROJECT_MEMBERS_READ:"project.members.read",PROJECT_MEMBERS_MANAGE:"project.members.manage",PROJECT_TRIGGER_READ:"project.trigger.read",PROJECT_TRIGGER_CREATE:"project.trigger.create",PROJECT_TRIGGER_UPDATE:"project.trigger.update",PROJECT_TRIGGER_DELETE:"project.trigger.delete",PROJECT_TRIGGER_FIRE:"project.trigger.fire",PROJECT_GATEWAY_LOGS_READ:"project.gateway.logs.read",PROJECT_GATEWAY_SPEND_READ:"project.gateway.spend.read",PROJECT_USAGE_READ:"project.usage.read",PROJECT_GATEWAY_BUDGET_SET:"project.gateway.budget.set",PROJECT_GATEWAY_KEYS_MANAGE:"project.gateway.keys.manage",PROJECT_AGENT_READ:"project.agent.read",PROJECT_AGENT_WRITE:"project.agent.write",PROJECT_SKILL_READ:"project.skill.read",PROJECT_SKILL_WRITE:"project.skill.write",PROJECT_COMMAND_READ:"project.command.read",PROJECT_COMMAND_WRITE:"project.command.write",PROJECT_FILE_READ:"project.file.read",PROJECT_FILE_WRITE:"project.file.write",PROJECT_SETTINGS_WRITE:"project.settings.write",PROJECT_SANDBOX_WRITE:"project.sandbox.write",PROJECT_MODEL_READ:"project.model.read",PROJECT_MODEL_WRITE:"project.model.write",PROJECT_GITOPS_READ:"project.gitops.read",PROJECT_GITOPS_PUSH:"project.gitops.push",PROJECT_GITOPS_MERGE:"project.gitops.merge",PROJECT_GITOPS_REF_ANY:"project.gitops.ref.any",PROJECT_GITOPS_REF_DELETE:"project.gitops.ref.delete",PROJECT_SECRET_READ:"project.secret.read",PROJECT_SECRET_WRITE:"project.secret.write",PROJECT_CONNECTOR_READ:"project.connector.read",PROJECT_CONNECTOR_CONNECTIONS_MANAGE:"project.connector.connections.manage",PROJECT_CONNECTOR_WRITE:"project.connector.write",PROJECT_APP_READ:"project.app.read",PROJECT_APP_WRITE:"project.app.write",PROJECT_APP_DEPLOY:"project.app.deploy",PROJECT_APP_ADMIN:"project.app.admin",PROJECT_REVIEW_READ:"project.review.read",PROJECT_REVIEW_SUBMIT:"project.review.submit",PROJECT_REVIEW_ACT:"project.review.act",PROJECT_ROOM_READ:"project.room.read",PROJECT_ROOM_WRITE:"project.room.write",PROJECT_CREDENTIALS_ISSUE:"project.credentials.issue"},_C=[Q.PROJECT_WRITE,Q.PROJECT_TRIGGER_CREATE,Q.PROJECT_TRIGGER_FIRE,Q.PROJECT_TRIGGER_UPDATE,Q.PROJECT_TRIGGER_DELETE];function bC(e){let t=r=>e[r]?.allowed===!0,n=t(Q.PROJECT_WRITE);return{canCreate:n&&t(Q.PROJECT_TRIGGER_CREATE),canFire:t(Q.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(Q.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(Q.PROJECT_TRIGGER_DELETE)}}var SC=[Q.PROJECT_WRITE,Q.PROJECT_GITOPS_PUSH,Q.PROJECT_GITOPS_MERGE,Q.PROJECT_REVIEW_ACT];function P_(e){let t=r=>e[r]?.allowed===!0,n=t(Q.PROJECT_WRITE);return{canOpen:n&&t(Q.PROJECT_GITOPS_PUSH),canMerge:n&&t(Q.PROJECT_GITOPS_MERGE),canClose:n}}function PC(e,t,n){let r=Kp(e.id);if(r.type==="connector_call"){let s=e.kind==="approval"?e.detail.actions?.[0]:void 0;return(t==="approve"||t==="reject")&&s?.canResolve!==!1&&s?.previewAuthorized!==!1}if(r.type==="change_request"){if(t==="answer")return!1;if(t==="approve")return P_(n).canMerge}return n[Q.PROJECT_WRITE]?.allowed===!0&&n[Q.PROJECT_REVIEW_ACT]?.allowed===!0}function F(e){return c.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function Gp(e){return A(await F(`/accounts/${e}/iam/groups`)).groups}async function Wp(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}`))}async function Hp(e,t){return A(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Vp(e,t,n){return A(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function zp(e,t){return A(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function Yp(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Jp(e,t,n){return A(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function xC(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Qp(e,t,n){return A(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function wC(e,t){return A(await F(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function kC(e,t){let n=A(await F(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function rt(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function vC(e,t={}){let n=rt({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await F(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function AC(e,t={}){let n=rt({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await F(`/accounts/${e}/iam/policies${n}`)).policies}async function RC(e,t){return A(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function CC(e,t,n){return A(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function TC(e,t){return A(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function IC(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function EC(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Xp(e){return A(await F(`/accounts/${e}/iam/roles`)).roles}async function Zp(e){return A(await F(`/accounts/${e}/iam/agent-identities`)).agents}async function ed(e){return A(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function td(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/permissions`))}async function MC(e){return A(await F(`/accounts/${e}/iam/actions`)).actions}async function nd(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/usage`))}async function rd(e,t){return A(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function sd(e,t,n){return A(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function od(e,t,n){return A(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function id(e,t){return A(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function OC(e,t,n){return A(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function DC(e){return A(await F(`/accounts/${e}/iam/scim/tokens`)).tokens}async function jC(e,t){return A(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function LC(e,t){return A(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function $C(e){return A(await F(`/accounts/${e}/iam/mfa-required`))}async function UC(e){return A(await F(`/accounts/${e}/iam/mfa-required/preview`))}async function FC(e,t){return A(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function NC(e){return A(await F(`/accounts/${e}/iam/session-oversight`))}async function BC(e,t){return A(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function KC(e){return A(await F(`/accounts/${e}/iam/sso/provider`)).provider}async function qC(e,t){return A(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function GC(e,t){return A(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function WC(e){return A(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function HC(e){return A(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function VC(e){return A(await F(`/accounts/${e}/iam/sso/mappings`)).mappings}async function zC(e,t){return A(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function YC(e,t){return A(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function JC(e){return A(await F(`/accounts/${e}/iam/session-policy`))}async function QC(e,t){return A(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function XC(e){return A(await F(`/accounts/${e}/iam/sessions`)).sessions}async function ZC(e,t){return A(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function eT(e){return A(await F(`/accounts/${e}/iam/pat-policy`))}async function tT(e,t){return A(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function nT(e){return A(await F(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function rT(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function sT(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function oT(e,t){return A(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function iT(e){return A(await F(`/accounts/${e}/audit/webhooks`)).webhooks}async function aT(e,t){return A(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function cT(e,t,n){return A(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function lT(e,t){return A(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function uT(e,t={}){let n=rt({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 F(`/accounts/${e}/audit${n}`))}async function ad(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 F(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function cd(e,t,n){return n.length===0?[]:A(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function pT(e){return A(await F(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function dT(e,t){return A(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function ld(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function ud(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function pd(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function dd(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function gd(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function md(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function gT(e){return rt({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 fd(e,t){return u(await F(`/accounts/${e}/iam/assignments${gT(t)}`)).assignments}async function yd(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await c.post(`/accounts/${e}/iam/assignments`,n))}async function hd(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function _d(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await F(`/accounts/${e}/iam/permissions${n}`)).permissions}async function mT(){let e=await c.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function fT(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function yT(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function hT(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function _T(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function bT(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function ST(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function PT(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function xT(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function wT(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function kT(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function vT(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var x_="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function AT(e){throw N("getGoogleAuthUrl",x_)}async function RT(e,t){throw N("convertPresentationToGoogleSlides",x_)}async function bd(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind),t?.sessionId&&n.set("session_id",t.sessionId),t?.limit!=null&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);let r=n.toString();return u(await c.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function Sd(e){return u(await c.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function Pd(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function xd(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function wd(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function kd(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}async function vd(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Ad(e){return u(await c.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Rd(e,t){let n=await c.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var Ds=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function w_(e,t=""){return`${Xn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function k_(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let s=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new Ds(s,t.status)}return r}async function CT(e){return k_(w_(e))}async function TT(e){return k_(w_(e,"/messages"))}async function Cd(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function Td(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function js(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Ls(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var IT=4;async function v_(e,t){let n=new Array(e.length),r=0,s=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(IT,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let l=n[a];l.ok?o.done.push(i):o.failed.push({reminder:i,error:l.error})}),o}function Id(e,t,n){return v_(t,r=>js(e,r.sessionId,r.reminderId,n))}function Ed(e,t){return v_(t,n=>Ls(e,n.sessionId,n.reminderId))}async function Md(e){return u(await c.get(`/projects/${e}/reminders`))}var xe=e=>`/projects/${e}/rooms`;function Od(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&s!==!1&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function Dd(e,t={}){return u(await c.get(`${xe(e)}${Od({name:t.name,archived:t.archived,mine:t.mine})}`))}async function jd(e,t){return u(await c.post(xe(e),t))}async function Ld(e,t){return u(await c.get(`${xe(e)}/${t}`))}async function $d(e,t,n){return u(await c.patch(`${xe(e)}/${t}`,n))}async function Ud(e,t,n={}){return u(await c.get(`${xe(e)}/${t}/messages${Od({after:n.after,before:n.before,limit:n.limit,top:n.top,thread:n.thread})}`))}async function Fd(e,t,n){return u(await c.post(`${xe(e)}/${t}/messages`,n))}async function Nd(e,t,n){return u(await c.post(`${xe(e)}/${t}/read`,n===void 0?{}:{seq:n}))}async function Bd(e,t,n,r={}){return u(await c.put(`${xe(e)}/${t}/members/sessions/${n}`,r))}async function Kd(e,t,n){return u(await c.delete(`${xe(e)}/${t}/members/sessions/${n}`))}async function qd(e,t,n,r={}){return u(await c.put(`${xe(e)}/${t}/members/people/${n}`,r))}async function Gd(e,t,n){return u(await c.delete(`${xe(e)}/${t}/members/people/${n}`))}async function Wd(e,t){return u(await c.get(`${xe(e)}/people${Od({q:t})}`))}async function Hd(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await c.get(`/accounts/tokens${r}`))}async function Vd(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await c.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function zd(e,t,n){let r=new URLSearchParams;t&&r.set("account_id",t),n?.deleteRevoked&&r.set("delete_revoked","true");let s=r.size>0?`?${r.toString()}`:"";return u(await c.delete(`/accounts/tokens/${encodeURIComponent(e)}${s}`))}async function Yd(){return u(await c.get("/oauth/grants")).grants}async function Jd(e){return u(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function ET(){return u(await c.get("/accounts/me/devices")).devices}async function MT(e){return u(await c.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function Qd(e){return u(await c.get(`/projects/${e}/cli-token`))}async function Xd(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function Zd(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}function Ht(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,s]of Object.entries(e))n.includes(` ${r} `)&&s!=null&&s!==""&&t.set(r,String(s));return t}function eg(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 tg(e,t){let n=Ht(eg(t)).toString();return u(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function ng(e,t){let n=Ht(eg({...t,projectId:void 0})).toString();return u(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function rg(e,t){let n=Ht(eg(t)).toString();return u(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function sg(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function og(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function ig(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function ag(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function cg(e,t){return u(await c.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function lg(e,t){return u(await c.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function OT(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function ug(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await c.get(`/marketplace/items${n}`))}async function pg(){return u(await c.get("/marketplace/marketplaces"))}async function dg(){return u(await c.get("/marketplace/marketplaces/featured"))}async function gg(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function mg(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function fg(){return u(await c.get("/marketplace/sources"))}async function yg(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function hg(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function DT(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function jT(e){throw N("getTemplate")}async function LT(e,t){throw N("installTemplate")}async function _g(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function bg(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function $s(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Sg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Pg(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function xg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function wg(e,t){let n=await $s(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await c.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),s=new TextEncoder().encode(JSON.stringify(r)),o="";for(let i of s)o+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(o)}`}}async function kg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function vg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function Ag(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Rg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Us(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Fs(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function $T(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function UT(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 Cg(e,t,n={}){let r=await $T(t),s=n.mediaType??"application/gzip",o=await Us(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),Fs(e,o.artifact.artifact_id,{sha256:await UT(r),size_bytes:r.byteLength})}async function Tg(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Ig(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Eg(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Mg(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function Og(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Dg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function jg(e,t,n){return u(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Lg(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var be=(e,t)=>`/projects/${e}/apps/${t}`;async function $g(e,t){return u(await c.get(`${be(e,t)}/machines`),"Failed to list machines").machines}async function Ug(e,t,n,r){return u(await c.post(`${be(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Fg=(e,t,n)=>Ug(e,t,n,"start"),Ng=(e,t,n)=>Ug(e,t,n,"stop"),Bg=(e,t,n)=>Ug(e,t,n,"restart");async function Kg(e,t,n){return u(await c.delete(`${be(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function qg(e,t,n,r={}){return u(await c.put(`${be(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function Gg(e,t,n){return u(await c.post(`${be(e,t)}/exec`,n),"Failed to run the command")}async function Wg(e,t){return u(await c.get(`${be(e,t)}/volumes`),"Failed to list volumes").volumes}async function Hg(e,t,n){return u(await c.post(`${be(e,t)}/volumes`,n),"Failed to create the volume")}async function Vg(e,t,n,r){return u(await c.patch(`${be(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function zg(e,t,n,r){u(await c.delete(`${be(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Yg(e,t,n){return u(await c.get(`${be(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Jg(e,t,n){return u(await c.post(`${be(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Qg(e,t,n,r){return u(await c.post(`${be(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function Xg(e,t,n,r){return u(await c.post(`${be(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function le(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var ge=e=>`/drives/${encodeURIComponent(e)}`;async function FT(e){let t=u(await c.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new x("Files not found",{status:404});return t[0]}async function NT(e,t){return u(await c.get(`${ge(e)}/access?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load sharing")}async function BT(e,t){return u(await c.put(`${ge(e)}/access`,t),"Failed to share folder")}async function KT(e,t){let n=u(await c.delete(`${ge(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function qT(e){return u(await c.get(`${ge(e)}/principals`),"Failed to load people")}async function GT(e){return u(await c.get(`${ge(e)}/conflicts`),"Failed to load conflicts").conflicts}async function WT(e,t){u(await c.post(`${ge(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function HT(e,t="/"){return(await A_(e,t)).entries}async function A_(e,t="/"){return u(await c.get(`${ge(e)}/files?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load files")}function Zg(e,t,n){let r=le(I().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${ge(e)}/files/content?${new URLSearchParams(s)}`}async function VT(e,t,n){let r=await $(Zg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new x(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function zT(e,t,n){let r=await $(Zg(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new x(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function YT(e,t,n,r){let s=`${ge(e)}/files/content?${new URLSearchParams({path:t})}`,o=r?.ifMatch?{"If-Match":r.ifMatch}:{},i=r?.onProgress,a=globalThis.XMLHttpRequest;if(i&&a){let d=n instanceof Blob?n:new Blob([n]);return JT(a,s,d,o,i,r?.signal)}let l=u(await c.putRaw(s,n,{signal:r?.signal,headers:o}),"Failed to upload file"),p=n instanceof Blob?n.size:n.byteLength;return i?.(p,p),l}async function JT(e,t,n,r,s,o){let i=`${le(I().backendUrl)}${t}`,{headers:a,rejected:l}=await Lt(i,{"Content-Type":"application/octet-stream",...r});return new Promise((p,d)=>{let g=new e,m=()=>new x("Request aborted",{name:"AbortError",code:"ABORTED"});if(o?.aborted)return d(m());let f=()=>g.abort();o?.addEventListener("abort",f,{once:!0});let h=()=>o?.removeEventListener("abort",f);g.open("PUT",i),a.forEach((S,v)=>g.setRequestHeader(v,S)),g.upload.onprogress=S=>s(S.loaded,n.size),g.onload=()=>{h();let S=null;try{S=g.responseText?JSON.parse(g.responseText):null}catch{S=null}if(g.status>=200&&g.status<300)return p(S);g.status===401&&l(),d(new x(S?.message||"Failed to upload file",{status:g.status,code:S?.code,url:i}))},g.onerror=()=>{h(),d(new x("Network error while uploading",{name:"TypeError",url:i}))},g.onabort=()=>{h(),d(m())},g.send(n)})}async function QT(e,t){return u(await c.post(`${ge(e)}/files/mkdir`,{path:t},{showErrors:!1}),"Failed to create folder")}async function XT(e,t,n){return u(await c.post(`${ge(e)}/files/move`,{from:t,to:n},{showErrors:!1}),"Failed to move")}async function ZT(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await c.delete(`${ge(e)}/files?${new URLSearchParams(r)}`,{showErrors:!1}),"Failed to delete")}async function eI(e){return u(await c.get(`${ge(e)}/versions`),"Failed to load versions").versions}async function tI(e,t){u(await c.post(`${ge(e)}/restore`,{versionId:t}),"Failed to restore version")}var nI=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function rI(e,t){return(await R_(e,t)).drives}async function R_(e,t){return u(await c.get(nI(e,t)),"Failed to load session files")}function st(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}var Ke={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function ot(){let e=st("BACKEND_URL")||I().backendUrl;return e||"http://localhost:8008/v1"}function qe(e){let t=le(e);return t.endsWith("/v1")?t:`${t}/v1`}function er(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=er(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return er(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function sI(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 Ns(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||"platinum",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${ot()}/p/${n.external_id}/${Ke.KORTIX_MASTER}`:""),status:sI(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 em(){let e=await xt(),t=[];for(let n of e){let r=await At(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Ns(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function tm(e){let t=await c.get(`/sessions/${encodeURIComponent(e)}`,{showErrors:!1});if(t.success&&t.data)return t.data;if(t.error?.status===400||t.error?.status===404)return null;throw t.error??new Error("Session request failed")}async function Bs(e){let t=await tm(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await tr(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function tr(e){let t=await em();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}async function nm(e){return u(await c.post("/notifications/device-token",e))}async function rm(e,t){return u(await c.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}async function sm(e,t){let n=I().fetch??((o,i)=>fetch(o,i)),r=qe(t?.backendUrl??I().backendUrl),s=await n(`${r}/notifications/device-token/release`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({device_token:e}),credentials:"omit",...t?.signal?{signal:t.signal}:{}});if(!s.ok)throw new x(`Device token release failed (HTTP ${s.status})`,{status:s.status,response:s});return{ok:!0}}var oI=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered","message"];async function om(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 c.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function im(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await c.post("/notifications/read",t))}var iI={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1},capture_device_down:{push:!0,email:!0},capture_device_recovered:{push:!0,email:!1},message:{push:!0,email:!0}};async function am(){return u(await c.get("/notifications/preferences",{showErrors:!1}))}async function cm(e){return u(await c.put("/notifications/preferences",e))}async function lm(){return u(await c.get("/notifications/web-push/key",{showErrors:!1}))}async function um(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await c.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function pm(e,t){return u(await c.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function nr(e){return u(await c.get(`/projects/${e}/model-access`))}async function rr(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}async function sr(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/custom-providers`)).providers}async function or(e,t,n){return u(await c.put(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,n))}var C_=e=>e?.status===404;async function ir(e,t){let n=await c.delete(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,{showErrors:!1});if(!n.success&&!C_(n.error))throw n.error??new Error("Failed to delete the custom provider");let r=`CUSTOM_${t.toUpperCase().replace(/-/g,"_")}_API_KEY`;await jn(e,r).catch(s=>{if(!C_(s))throw s})}function aI(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:o,previewIsLinkOnly:i}=e;return t||n?!1:s?o&&!i:r==="error"}function dm(e){return typeof e=="string"&&e.trim().length>0}function T_(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return dm(t)||dm(n)||dm(r)}function cI(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 ar(e){if(!e)return!0;let t=cI(e.items);return t?!t.some(T_):!T_(e)}var ke="kortix.transcript.v1",I_=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function gm(e){return typeof e=="string"&&I_.includes(e)}var lI=["once","always","reject"],uI=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var O_="kortix-v1-import",pI={harness:O_,harness_version:ke,adapter_version:"1"},mm={schema:ce,v:1},dI={opencode:"[Tool execution was interrupted]",pi:"No result provided"},gI="[Old tool result content cleared]",mI="The following tool was executed by the user",fI=new Map(Object.entries({bash:"shell",powershell:"shell",read:"read",write:"write",edit:"edit",multiedit:"edit",patch:"patch",apply_patch:"patch",list:"list",ls:"list",glob:"glob",find:"glob",grep:"grep",webfetch:"web_fetch",websearch:"web_search",codesearch:"web_search",todowrite:"todo",todoread:"todo",task:"task",question:"question",plan_enter:"plan",plan_exit:"plan"})),yI=e=>fI.get(e)??(e.includes("_")?"mcp":"other"),hI=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),_I=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),X=e=>typeof e=="string"?e:void 0,Ge=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ws=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,D_=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Vt=e=>Ge(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,zt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function fm(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>fm(r,t[s]));if(!B(e)||!B(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0);return n.length===Object.keys(t).filter(r=>t[r]!==void 0).length&&n.every(r=>fm(e[r],Ws(t,r)))}function qs(e,t){if(fm(e,t))return;if(e===void 0)return{del:!0};if(!B(e)||!B(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let s=qs(Ws(e,r),Ws(t,r));s&&D_(n,r,s)}return{sub:n}}function Gs(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=B(e)?{...e}:{};for(let[r,s]of Object.entries(t.sub)){let o=Gs(Ws(n,r),s);o===void 0?delete n[r]:D_(n,r,o)}return n}var cr=e=>Object.values(e??{}).find(t=>t.version===ke),Hs=(e,t)=>({[e]:{version:ke,...t}}),j_=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},E_=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),bI=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),SI=e=>{if(B(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==ke&&B(n.data?.details));return t?t.data.details:{}};function PI(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=zt(e.started_at)??t.created,i=zt(e.ended_at)??o,a=r?.exit_code!==void 0?{exit:r.exit_code}:{};if(e.status==="pending")return{status:"pending",input:e.input??{},raw:""};if(e.status==="running")return{status:"running",input:e.input??{},...e.title&&{title:e.title},time:{start:o}};if(e.status==="error")return{status:"error",...s,error:E_(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:o,end:i}};let l=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...j_(d,t)}]:[]),p=zt(r?.cleared_at);return{status:"completed",...s,output:E_(r?.content),title:e.title??"",metadata:{...SI(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...l.length&&{attachments:l}}}function L_(e,t){let n=bI(e,t);switch(e.type){case"text":return{...n,type:"text",text:e.text,...e.synthetic!==void 0&&{synthetic:e.synthetic}};case"reasoning":return{...n,type:"reasoning",text:e.text,time:{start:t.created}};case"attachment":return{...n,type:"file",mime:e.mime,...e.name!==void 0&&{filename:e.name},...j_(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:PI(e,t,{...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID})};case"step":return e.phase==="start"?{...n,type:"step-start"}:{...n,type:"step-finish",reason:"stop",cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};case"compaction":return{...n,type:"compaction",auto:e.trigger==="auto"||e.trigger==="overflow",...e.trigger==="overflow"&&{overflow:!0},...e.first_kept_message_id!==null&&{tail_start_id:e.first_kept_message_id}};case"harness":return t.fromV1&&(e.harness==="opencode"||e.harness==="pi")?e.data:e.model_visible&&e.fallback_text!==void 0?{...n,type:"text",text:e.fallback_text,synthetic:!0}:void 0;case"subtask":return}}function xI(e){return gm(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function $_(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:_I.get(e.finish);return{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"assistant",time:{created:t.created,...e.completed_at!==null&&{completed:zt(e.completed_at)}},...e.reply_to&&{parentID:e.reply_to},modelID:e.model?.model??"",providerID:e.model?.provider??"",...e.model?.variant!==void 0&&{variant:e.model.variant},mode:e.agent??"",agent:e.agent??"",path:{cwd:"",root:""},cost:r?.cost??0,tokens:{input:r?.input??0,output:r?.output??0,reasoning:r?.reasoning??0,cache:{read:r?.cache_read??0,write:r?.cache_write??0}},...s&&{finish:s},...e.error&&{error:xI(e.error)},...n}}function U_(e,t){return e.role==="assistant"?$_(e,t):{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"user",time:{created:t.created},agent:e.agent??"",model:{providerID:e.model?.provider??"",modelID:e.model?.model??"",...e.model?.variant!==void 0&&{variant:e.model.variant}}}}function F_(e,t,n){let r=`${e.message_id}-summary`;return{info:$_({...e,reply_to:e.message_id,agent:"compaction",finish:e.status==="complete"?"stop":null},n,{id:r,summary:!0}),parts:[{id:`${r}-p0`,...n.sessionID!==null&&{sessionID:n.sessionID},messageID:r,type:"text",text:t.summary}]}}function wI(e,t,n){let r=n||e.producer.harness===O_;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=cr(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:zt(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=L_(d,i);return g===void 0?[]:[Gs(g,cr(d.ext)?.data)]}),l=[{runtime_session_id:o,info:Gs(U_(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=Gs(F_(e,p,i),s?.summary);l.push({runtime_session_id:o,info:d.info,parts:d.parts})}return l}var ym=e=>Ge(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,Ks=e=>String(B(e.info)?e.info.id:""),N_=(e,t)=>ym(e)-ym(t)||(Ks(e)<Ks(t)?-1:Ks(e)>Ks(t)?1:0),M_=e=>{let t=cr(e.ext);return t?t.native_id??null:e.thread_id};function Vs(e){let t=structuredClone(e),n=t.threads.find(i=>i.parent_thread_id===null)??t.threads[0],r=t.threads.flatMap(i=>i.messages.flatMap(a=>wI(a,M_(i),cr(i.ext)!==void 0))),s=cr(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?M_(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(N_)}}function kI(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:B(e.model)?{p:e.model.providerID,m:e.model.modelID,v:e.model.variant}:{},n=X(t.p),r=X(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...X(t.v)!==void 0&&{variant:t.v}}}function vI(e){if(!B(e.tokens))return null;let t=e.tokens,n=B(t.cache)?t.cache:{};return{input:Ge(t.input)??0,output:Ge(t.output)??0,cache_read:Ge(n.read)??0,cache_write:Ge(n.write)??0,...Ge(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Ge(e.cost)!==void 0&&{cost:e.cost}}}var AI=e=>({code:X(e.code)||X(e.name)||"UnknownError",message:X(B(e.data)?e.data.message:void 0)??""});function B_(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:X(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...X(e.url)!==void 0&&{url:e.url}}}function RI(e,t,n,r){let s=e.state,o=B(s.time)?s.time:{};B(s.input)||r.tool_input++;let i=B(s.metadata)&&Ge(s.metadata.exit)!==void 0?{exit_code:s.metadata.exit}:{},a,l,p=s.input??null;if(s.status==="completed"){let m=(Array.isArray(s.attachments)?s.attachments:[]).filter(B).map(h=>{let{bytes:S,...v}=B_(h,n,r);return{type:"attachment",...v}}),f=Vt(o.compacted);a="complete",l={content:[...X(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:gI}],cleared_at:f}}}else if(s.status==="error"){let m=X(s.error);a="error",l={content:m!==void 0?[{type:"text",text:m}]:[],is_error:!0,...m!==void 0&&{error:{message:m}},...i}}else if(n.live)a=s.status==="pending"?"pending":"running",a==="pending"&&X(s.raw)&&!(B(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=dI[n.h];a="error",l={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=Vt(o.start),g=Vt(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:yI(e.tool),input:p,status:a,...l&&{result:l},...X(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function CI(e,t,n,r,s,o){let i=(a,l=!1)=>({type:"harness",id:t,harness:s.h,kind:a,data:e,model_visible:l,...l&&{fallback_text:mI}});if(!B(e))return i("unknown");switch(e.type){case"text":return typeof e.text!="string"||e.ignored===!0?i("text"):{type:"text",id:t,text:e.text,...typeof e.synthetic=="boolean"&&{synthetic:e.synthetic}};case"reasoning":return typeof e.text!="string"?i("reasoning"):{type:"reasoning",id:t,text:e.text};case"file":return e.mime==="text/plain"||e.mime==="application/x-directory"?i("file"):{type:"attachment",id:t,...B_(e,s,o),...X(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&B(e.state)?RI(e,t,s,o):i("tool");case"step-start":case"step-finish":return{type:"step",id:t,phase:e.type==="step-start"?"start":"finish"};case"compaction":{if(e!==n)return i("compaction");let a=e.overflow===!0?"overflow":e.auto===!0?"auto":"manual";return{type:"compaction",id:t,summary:r,first_kept_message_id:X(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(X(e.type)||"unknown")}}function TI(e){let t=e.map((s,o)=>B(s)&&typeof s.id=="string"&&s.id?s.id:`#${o}`),n=new Set(t),r=new Set;return t.map(s=>{if(!r.has(s))return r.add(s),s;let o=2;for(;n.has(`${s}#${o}`);)o++;return n.add(`${s}#${o}`),`${s}#${o}`})}function II(e,t,n,r,s,o){let i=B(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],l=i.role==="user"?a.find(R=>B(R)&&R.type==="compaction"):void 0,p=t&&B(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",g=l?p:d==="assistant"?i:void 0,m=g&&B(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",h=g&&B(g.time)?Vt(g.time.completed):null,S=o.live?"streaming":"interrupted",v=g?m?f?"aborted":"error":h?"complete":S:l?S:"complete",T=Vt(B(i.time)?i.time.created:void 0)??"",_=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(R=>B(R)&&R.type==="text"&&typeof R.text=="string"?[R.text]:[]).join(""):null,b={tool_input:0,cut_point:0,attachment:0},O=TI(a),y=a.map((R,L)=>CI(R,O[L],l,_,o,b)),w=y.some(R=>R.type==="text"||R.type==="attachment"||R.type==="tool_call"||R.type==="harness"&&R.model_visible),P=!s&&d!=="system"&&(l?v==="complete":!m||f&&w),k=o.live&&P&&v!=="streaming"&&y.some(R=>R.type==="tool_call"&&(R.status==="pending"||R.status==="running"))?"streaming":v,C=s?"superseded":P||!m?void 0:f?"aborted":"failed_attempt";return l&&B(l)&&X(l.tail_start_id)===void 0&&b.cut_point++,{m:{...mm,message_id:X(i.id)??"",thread_id:n,seq:r,role:d,kind:l?"compaction":"turn",status:k,in_context:P,...C&&{hidden_reason:C},agent:X(i.agent)??null,...d==="assistant"&&{reply_to:X(i.parentID)??null},model:kI(i),usage:g?vI(g):null,finish:!g||l?null:f?"aborted":m?"error":hI.get(i.finish)??null,error:m?AI(m):null,created_at:T,completed_at:g||l?h:T||null,producer:pI,blocks:y},lost:b}}function EI(e,t,n,r,s){let o={};t.runtime_session_id!==r&&(o.runtime_session_id=t.runtime_session_id);let i={sessionID:t.runtime_session_id,messageID:e.message_id,created:zt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=qs(t.parts[d],L_(p,i));g&&(p.ext=Hs(s,{data:g}))}):o.parts=t.parts;let a=qs(t.info,U_(e,i));a&&(o.info=a);let l=e.blocks.find(p=>p.type==="compaction");if(n&&l){let p=qs({info:n.info,parts:n.parts},F_(e,l,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Hs(s,{data:o}))}function MI(e,t,n){if(t){for(let r of[!0,!1])for(let s of e)if(!(s.runtime_session_id===t||!Array.isArray(s.parts))){for(let o of s.parts)if(!(!B(o)||o.type!=="tool"||!B(o.state))&&(r?B(o.state.metadata)&&o.state.metadata.sessionId===t:n(o.state).includes(t)))return{row:s,part:o}}}}function zs(e,t={}){let n={h:t.harness??"opencode",resolve:t.resolveAttachment??(()=>null),counts:{tool_input:0,cut_point:0,attachment:0},live:t.live===!0},r=structuredClone(e.rows).sort(N_),s=new Map;for(let b of r){let O=s.get(b.runtime_session_id);O?O.push(b):s.set(b.runtime_session_id,[b])}let o=e.root_id,i=s.has(o),a=new Map,l=b=>a.get(b)??(a.set(b,JSON.stringify(b)),a.get(b)),p=new Map;for(let b of s.keys()){let O=i&&b===o?void 0:MI(r,b,l);O&&p.set(b,O)}let d=[...r].reverse().find(b=>b.runtime_session_id===null||!p.has(b.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=b=>b!==null&&p.has(b)?b:m,h=Vt(r.map(ym).find(Number.isFinite))??"",S=[];for(let[b,O]of s){if(b!==g&&(b===null||!p.has(b)))continue;let y=b===g,w=y?r.filter(D=>D.runtime_session_id!==g&&f(D.runtime_session_id)===m):[],P=[...w,...O],k=new Set(w),C=new Map,j=new Set;for(let D of P){let q=B(D.info)?D.info:{};if(q.role!=="user"||!Array.isArray(D.parts)||!D.parts.some(K=>B(K)&&K.type==="compaction"))continue;let W=P.find(K=>!j.has(K)&&K.runtime_session_id===D.runtime_session_id&&B(K.info)&&K.info.role==="assistant"&&K.info.summary===!0&&K.info.parentID===q.id);W&&(C.set(D,W),j.add(W))}let R=[];for(let D of P){if(j.has(D))continue;let q=C.get(D),{m:W,lost:K}=II(D,q,y?m:b,R.length+1,k.has(D),n);if(EI(W,D,q,b,n.h),W.in_context)for(let je of["tool_input","cut_point","attachment"])n.counts[je]+=K[je];R.push(W)}let L=b===null?void 0:p.get(b),pe=R.find(D=>D.role==="user"&&D.kind==="turn");S.push({...mm,thread_id:y?m:b,parent_thread_id:L?f(L.row.runtime_session_id):null,spawned_by:L&&typeof L.part.callID=="string"?{message_id:X(L.row.info?.id)??"",call_id:L.part.callID}:null,agent:pe?.agent??null,title:null,created_at:R[0]?.created_at||h,messages:R,ext:Hs(n.h,b===null?{}:{native_id:b})})}S.sort((b,O)=>b.parent_thread_id===null?-1:O.parent_thread_id===null?1:_(b)-_(O));let v=S[0]?.messages.filter(b=>b.role==="user"&&b.kind==="turn").at(-1),T=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...mm,session_id:e.session_id,title:null,created_at:h,restore_grade:T?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:v?.agent??null,model:v?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:S,...g!==o&&{ext:Hs(n.h,{data:{root_id:o}})}};function _(b){return r.findIndex(O=>O.runtime_session_id===b.thread_id)}}var hm={schema:ce,v:1},OI=Object.freeze({}),K_=new WeakMap;function lr(e){let t=K_.get(e);if(t&&t.state===e.state)return t.block;let n=e.sessionID??null,r={id:e.messageID,sessionID:e.sessionID,role:"assistant"},o=zs({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return K_.set(e,{state:e.state,block:o}),o}var _m=new WeakMap;function bm(e){if(_m.has(e))return _m.get(e);let t={...hm,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:ke}},messages:[{...hm,message_id:"",thread_id:"",seq:1,role:"assistant",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:"",completed_at:null,producer:{harness:"",harness_version:"",adapter_version:""},blocks:[e]}]},{rows:n}=Vs({...hm,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[t]}),r=n[0].parts[0];return _m.set(e,r),r}function oe(e){return bm(e)}var me=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",We=e=>me(e)?oe(e):e;function G_(e){let t=oe(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:OI}var W_=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function H_(e){return e.status==="complete"?"completed":e.status}var q_=new WeakMap;function V_(e){if(e.status!=="complete")return"";let t=q_.get(e);return t===void 0&&q_.set(e,t=W_(e)),t}function z_(e){return e.status==="error"?e.result?.error?.message||W_(e):void 0}function fe(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function DI(e){return fe(e)==="bash"}function Sm(e){let t=fe(e);return t==="question"||t==="ask"}function jI(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Y_=new Set(["show","show_user"]);function Pm(e){return Y_.has(fe(e))}function LI(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function xm(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Ys(e))}function Ys(e){let t=me(e)?oe(e):e,n=fe(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:ar(t.state?.input)}var J_=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function wm(e){return J_.has(fe(e))}var $I=50*1024*1024,km="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",UI=new RegExp(`^kortix-attachment://(${km})/(${km})/(${km})$`);function Am(e){if(typeof e!="string")return null;let t=UI.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function FI(e){return Am(e)!==null}var vm=new WeakMap;async function Rm(e,t,n,r={}){if(n.size>$I)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:vm.get(n)?.get(s);if(o?.promise)return o.promise;let i=o??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let l=vm.get(n)??new Map;l.set(s,i),vm.set(n,l)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=c.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(l=>{throw i.promise=void 0,l}),i.promise}async function Cm(e,t){let n=Am(e);if(!n)throw new Error("Invalid attachment reference");let r=I().backendUrl.replace(/\/$/,""),s=await $(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new x("Could not load attachment",{status:s.status});return s.blob()}var NI=new Set(["show","show_user"]);function BI(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return t;let i=e.indexOf("</file>",o+1);if(i===-1)return t;t.push(e.slice(s,o).trimStart()),n=i+7}}var He=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ur=e=>typeof e=="string"&&e.length>0?e:null,Q_=e=>typeof e=="string"?ur(e.split("/").pop()):null;function Js(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 KI(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 qI(e){let t=e.blocks.filter(He).map(n=>n.type==="attachment"?{type:"file",url:n.ref??n.url,filename:n.name,mime:n.mime}:n.type==="tool_call"?{type:"tool",tool:n.name,state:{input:n.input}}:n.type==="harness"&&He(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function GI(e,t){for(let n of BI(e))t(Js(n,"attachment"),Js(n,"filename")??Q_(Js(n,"path")),Js(n,"mime"))}function WI(e,t){for(let n of[e,...KI(e.items)])He(n)&&t(n.attachment,Q_(n.path),null)}function HI(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=He(r)&&Array.isArray(r.blocks)?qI(r):r;if(!He(s)||!He(s.info)||!Array.isArray(s.parts))continue;let o=ur(s.info.id);if(!o)continue;let i=ur(s.info.role)??"unknown",a=(l,p,d)=>{let g=Am(l);!g||n.has(l)||(n.add(l),t.push({url:l,attachment_id:g.attachmentId,filename:p,mime:d,message_id:o,role:i}))};for(let l of s.parts)He(l)&&(l.type==="file"?a(l.url,ur(l.filename),ur(l.mime)):l.type==="text"&&typeof l.text=="string"?GI(l.text,a):l.type==="tool"&&typeof l.tool=="string"&&NI.has(fe(l.tool))&&He(l.state)&&He(l.state.input)&&WI(l.state.input,a))}return t}function VI(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 zI(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 Tm(e,t,n){return e!==void 0?e:VI(st(t),n)}var Im={get disableMobileAdvertising(){return Tm(I().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Tm(I().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Tm(I().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var YI=new Set(["project-manager"]);function Qs(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Im.enableProjects||!YI.has(e.name)}function JI(e){let t=e.agents.filter(Qs),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function X_(){return{projects:{list:xt,listForAccount:Qi,get:wt,detail:In,create:ta,createRepo:na,provision:ra,update:On,archive:Dn,llmCatalog:En,modelPicker:Mn,modelAccess:nr,setModelAccess:rr,customLlmProviders:sr,setCustomLlmProvider:or,deleteCustomLlmProvider:ir,sandboxHealth:$n,sandboxTemplates:Yc,sessions:At,createSession:Rt},github:{linkRepository:ua,replaceProjectRepository:pa,getInstallation:da,listInstallations:ga,listLinkableInstallations:ma,listRepositories:fa,listRepositoryBranches:ya,linkInstallation:_a,saveInstallation:ha,deleteInstallation:Sa,storeUserToken:ba},gitBackend:{get:Pa,repositories:xa},connectStatus:Kc,marketplace:{items:o=>ug(o),item:o=>gg(o),itemFile:(o,i)=>mg(o,i),marketplaces:()=>pg(),featured:()=>dg(),sources:{list:()=>fg(),add:o=>yg(o),remove:o=>hg(o)}}}}function Z_(){return{billing:{accountState:ju,accountStateMinimal:Lu,transactions:$u,transactionsSummary:Uu,creditBreakdown:Fu,usageHistory:Nu,usageRollup:rp,sessionCosts:{list:ip,get:Zn},tierConfigurations:Bu,setPlan:ep,previewPlan:Zu,acceptEnterpriseOffer:tp,contactSales:np,checkout:{createSession:n=>Ku(n),confirmSession:(n,r)=>qu(n,r)},subscription:{createPortalSession:(n,r)=>Gu(n,r),cancel:(n,r)=>Wu(n,r),reactivate:n=>Hu(n),scheduleDowngrade:(n,r,s)=>Vu(n,r,s),cancelScheduledChange:n=>zu(n),prorationPreview:(n,r)=>Yu(n,r)},credits:{purchase:n=>Ju(n),autoTopupSettings:n=>Qu(n),configureAutoTopup:n=>Xu(n)}},sandboxShares:{list:vd,create:Ad,revoke:Rd}}}var Yt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function ie(e,t,n){let r=n?.fetch??I().fetch??((p,d)=>fetch(p,d)),s=le(n?.backendUrl??I().backendUrl??"");if(!s)throw new Yt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let o={accept:"application/json"};t.body!==void 0&&(o["content-type"]="application/json"),t.bearer&&(o.authorization=`Bearer ${t.bearer}`);let i=await r(`${qe(s)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:o,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),l=null;try{l=a?JSON.parse(a):null}catch{l=a}if(!i.ok){let p=l&&typeof l=="object"?l:{};throw new Yt(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return l}function Xs(e,t){return ie("/auth/signup",{body:e},t)}function Zs(e,t){return ie("/auth/sign-in/password",{body:e},t)}function eo(e,t){return ie("/auth/sign-in/magic-link",{body:e},t)}function to(e,t){return ie("/auth/verify-otp",{body:e},t)}function no(e,t){return ie("/auth/sign-in/oauth",{body:e},t)}function ro(e,t){return ie("/auth/oauth/exchange",{body:e},t)}function Jt(e,t){return ie("/auth/refresh",{body:e},t)}function so(e,t){return ie("/auth/password/reset",{body:e},t)}function oo(e,t,n){return ie("/auth/password/update",{body:e,bearer:t},n)}function io(e,t){return ie("/auth/user",{bearer:e},t)}function ao(e,t,n){return ie("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function co(e,t){return ie("/auth/sign-in/sso",{body:e},t)}var lo={enroll:(e,t,n)=>ie("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function uo(e,t={},n){return ie("/auth/sign-out",{body:t,bearer:e},n)}function po(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,l=0,p=new Set,d=S=>(S.expires_at??0)*1e3,g=S=>d(S)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let S of[...p])try{S(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let S=l,v=(async()=>{let T=await e.storage.get();if(S===l&&T)try{let _=JSON.parse(T);_.session?.access_token&&_.session?.refresh_token&&(r=_.session,s=_.user??null)}catch{r=null}return o=!0,r})();i=v,v.then(()=>{i===v&&(i=null)},()=>{i===v&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let S=r.refresh_token,v=l,T=Jt({refresh_token:S},e.request).then(async _=>(v!==l||(r=_.session,_.user&&(s=_.user),await m()),r)).catch(async _=>{if(v!==l)return r;let b=_&&typeof _=="object"&&"status"in _?_.status:0;if(b>=400&&b<500)return r=null,s=null,await m(),null;throw _}).finally(()=>{a===T&&(a=null)});a=T}return a}return{subscribe(S){return p.add(S),()=>{p.delete(S)}},current:()=>r,user:()=>s,load:f,async set(S,v){await f(),l+=1,a=null,r=S,v!==void 0&&(s=v),S||(s=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){l+=1,a=null,r=null,s=null,o=!0,await m()}}}function eb(){return{list:Ti,get:Ei,create:Ii,secretResources:{list:Za,create:ec,rotate:tc,retry:nc,remove:rc,grant:sc,revoke:oc,setAccess:ic},updateName:Mi,branding:{get:Oi,update:Di,uploadAsset:ji,removeAsset:Li,reset:$i},leave:Yi,members:Ui,invite:Fi,removeMember:Vi,updateMemberRole:zi,invites:Ni,cancelInvite:Bi,resendInvite:Ki,tokens:{list:Hd,create:Vd,revoke:zd},connectedApps:{list:Yd,revoke:Jd},audit:{log:tg,export:rg,webhooks:{list:sg,create:og,update:ig,remove:ag}}}}function tb(){return{assignments:{list:fd,create:yd,revoke:hd},permissions:{list:_d,forRole:td},roles:{list:Xp,create:rd,update:sd,setPermissions:od,remove:id,usage:nd},groups:{list:Gp,get:Wp,create:Hp,update:Vp,remove:zp,members:{list:Yp,add:Jp,remove:Qp}},agentIdentities:Zp,oauthClients:{list:ld,get:ud,create:pd,update:dd,rotateSecret:gd,remove:md},can:ad,canBatch:cd}}function nb(){let e={signUp:Xs,signInWithPassword:Zs,sendMagicLink:eo,verifyOtp:to,signInWithProvider:no,exchangeCode:ro,refresh:Jt,resetPassword:so,updatePassword:oo,updateUserMetadata:ao,signInWithSso:co,mfa:lo,user:io,signOut:uo,session:po},t=eb(),n=tb();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:qi,describe:Gi,accept:ls,acceptAndLand:Wi,decline:Hi}}}var pr=new Map,Em=new Map;function Mm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function rb(e){return pr.get(Mm(e))??null}function sb(){return[...pr.values()].filter(e=>typeof e=="string")}function ob(e){return pr.has(Mm(e))}async function it(e){let t=Mm(e),n=pr.get(t);if(n!==void 0)return n;let r=Em.get(t);if(r)return r;let s=(async()=>{try{let o=await c.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let i=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return pr.set(t,i),i}catch{return null}finally{Em.delete(t)}})();return Em.set(t,s),s}function ib(e){let{apiBaseUrl:t}=e;return ob(t)||it(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:rb(t)}}function ab(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new x(`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 s=I().backendUrl??e.backendUrl,o=80,i=t(s);return i&&(o=i.port?Number(i.port):i.protocol==="https:"?443:80),ib({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function cb(e,t){let n=null;async function r(){n||(n=Wn(e,t,{showErrors:!1}).then(s=>{let o=Qn(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,l=s.agent_name?.trim()||void 0;return{model:a,agent:l}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var Qt={url:null,sandboxId:null,dbSandboxId:null,version:0},XI=new Set;function go(e,t=null,n=null){if(!(Qt.url===e&&Qt.sandboxId===t&&Qt.dbSandboxId===n)){Qt={url:e,sandboxId:t,dbSandboxId:n,version:Qt.version+1};for(let r of XI)r()}}function lb(){return Qt.url}var dr=new Map;function ub(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Ct=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function pb(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await nt(e,t,Math.min(3e4,o()));for(;Date.now()<s&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,o()))),i=await nt(e,t,Math.min(3e4,o()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new x(ub(i),{code:"RUNTIME_UNAVAILABLE"});let l=i.sandbox.external_id;if(!l)throw new x("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ie(l);return go(p,l),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:l}}return n}function db(e,t,n){let r=null;function s(){if(r)return r;let p=i_(e,t);return p&&(r=p),r}let o=pb(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=it(I().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?Au(p.session):null,h=f?.sandbox?.external_id,S=f?.runtime_session_id;if(h&&S){let b=Ie(h);return go(b,h),r={runtimeSessionId:S,opencodeSessionId:S,runtimeUrl:b,sandboxId:h},Cs(e,t,r),await m,r}let v=`${e}
|
|
15
|
-
${t}`,T=dr.get(v);if(T)return r=await T,await m,r;let _=o(g);dr.set(v,_);try{return r=await _,await m,r}finally{dr.get(v)===_&&dr.delete(v)}}function a(p){let d=s();if(!d)throw new Ct(p);return d}function l(){r=null,
|
|
13
|
+
`);let h=hR(f);if(h){if(r(h),h.type==="error")throw new P(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 uu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function pu(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function du(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Qn(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function gu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function mu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function _R(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 fu(e){return u(await c.get(`/projects/${e}/triggers`))}async function yu(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function hu(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function _u(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function bR(e){return u(await c.get(`/accounts/${e}/automations`))}async function SR(e,t){return u(await c.patch(`/accounts/${e}/automations`,{paused:t},{showErrors:!1}))}async function bu(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function i_(e){let t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.limit!=null&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function Su(e,t,n){let r={};return n?.payload!==void 0&&(r.payload=n.payload),n?.dryRun!==void 0&&(r.dry_run=n.dryRun),u(await c.post(`/projects/${e}/triggers/${t}/fire`,r))}async function xu(e,t,n){return u(await c.get(`/projects/${e}/triggers/${t}/runs${i_(n)}`))}async function Pu(e,t){return u(await c.get(`/projects/${e}/trigger-runs${i_(t)}`))}async function wu(e,t,n,r){return u(await c.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function ku(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await c.get(`/projects/${e}/triggers/event-types?${n}`))}async function vu(e){return u(await c.get(`/projects/${e}/triggers/event-apps`))}var tt=new Map;function Au(e,t){return`${e}::${t}`}function a_(e,t){tt.delete(e),tt.set(e,t)}function c_(e,t){let n=Au(e,t),r=tt.get(n);return r&&a_(n,r),r}function Ts(e,t,n){let r=Au(e,t);if(!tt.has(r)&&tt.size>=512){let s=tt.keys().next().value;s!==void 0&&tt.delete(s)}a_(r,n)}function l_(e,t){tt.delete(Au(e,t))}function xR(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Xn(){return xR(I().backendUrl||"http://localhost:8008/v1")}function u_(){let e=I().sandboxId;return e?`${Xn()}/p/${e}/8000`:""}function PR(e,t=8e3){return`${Xn()}/p/${e}/${t}`}function Ie(e,t=8e3){return PR(e,t)}function Ru(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 Is=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 wR(e){return e instanceof Error&&e.name==="SessionStartError"}function kR(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Is(s,{status:n,code:r,terminal:!0}):null}function p_(e,t,n){let r=typeof n=="number"?n:n?.waitMs,s=typeof n=="number"?void 0:n?.repositoryMode,o=new URLSearchParams;r&&r>0&&o.set("wait_ms",String(Math.floor(r))),s&&o.set("repository_mode",s),typeof n=="object"&&n?.keepStopped&&o.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&o.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=o.size>0?`?${o.toString()}`:"";return c.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function nt(e,t,n){let r=await p_(e,t,n);if(!r.success||!r.data){let s=kR(r.error);if(s&&!(s.status===404&&Il(t)))throw s;return null}return d_(e,t,r.data)}async function Cu(e,t,n){let r=await p_(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return d_(e,t,r.data)}function d_(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Ts(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Ie(r),sandboxId:r}),n}function vR(e,t){return["session-start",e,t]}async function Tu(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function Iu(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function Eu(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await c.delete(`/projects/${e}/model-defaults?${n}`))}async function AR(e,t){return u(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function g_(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function RR(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Es(e){let t=e.connectors_required?g_(e.connectors_required):void 0,n=e.connectors_personal?g_(e.connectors_personal):void 0;if(t&&n&&!RR(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 Mu(e,t,n){let r=Es(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function CR(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Ou(n.block):null}}async function TR(e,t,n){let r=Ou(n,!0),s=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Ou(s.block):null}}function Ou(e,t=!1){let n=Es(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 IR(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Du(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}var Ms="Use setBillingPlan().",m_="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function ju(){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",monthly_usd:null,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 ER(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function MR(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,monthlyUsd:t.monthly_usd??null};let n=e??ju(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:ER(r),label:s,sublabel:null,monthlyUsd:null}}function f_(e){return!!e&&e.can_manage_billing!==!1}function OR(e){return e?.subscription?.can_purchase_credits===!0&&f_(e)}async function y_(e){let t=await c.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?ju():t.data}function h_(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 Lu(e){return y_(`/billing/account-state${h_(e)}`)}async function $u(e){return y_(`/billing/account-state/minimal${h_(e)}`)}async function Uu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await c.get(`/billing/transactions${n?`?${n}`:""}`))}async function Fu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await c.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Nu(){return u(await c.get("/billing/credit-breakdown"))}async function Bu(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function Ku(){return u(await c.get("/billing/tier-configurations"))}async function DR(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return $t(e,`/v1/billing/account-state${t}`)}async function qu(e){throw N("createCheckoutSession",Ms)}async function Gu(e,t){throw N("confirmCheckoutSession",Ms)}async function Wu(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Hu(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Vu(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function zu(e,t,n){throw N("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Yu(e){throw N("cancelScheduledChange",m_)}async function Ju(e,t){throw N("getProrationPreview",m_)}async function Qu(e){return u(await c.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Xu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function jR(e){return u(await c.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function Zu(e){return u(await c.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function LR(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function ep(e){return u(await c.post("/billing/plan/preview",{monthly_usd:e.monthlyUsd,account_id:e.accountId}),"Failed to preview the plan change")}async function tp(e){return u(await c.post("/billing/plan",{monthly_usd:e.monthlyUsd,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale,account_id:e.accountId}),"Failed to set billing plan")}async function np(e){return u(await c.post("/billing/enterprise-offer/checkout",{success_url:e.successUrl,cancel_url:e.cancelUrl,account_id:e.accountId}),"Failed to start the Enterprise checkout")}async function rp(e={}){return u(await c.post("/billing/enterprise/contact",{account_id:e.accountId,...e.note?{note:e.note}:{}}),"Failed to reach Kortix sales")}async function $R(e){throw N("createPerSeatCheckout",Ms)}async function UR(e){throw N("claimPerSeatBilling",Ms)}async function FR(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function sp(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await c.get(`/usage${n?`?${n}`:""}`))}function ip(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Os(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Ds(e){return e.size>0?`?${e}`:""}async function ap(e={}){let t=new URLSearchParams;return ip(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Os(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/session-costs${Ds(t)}`))}async function Zn(e,t={}){let n=new URLSearchParams;return ip(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Ds(n)}`))}async function NR(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Os(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/cost-by-project${Ds(t)}`))}async function BR(e={}){let t=new URLSearchParams;return ip(t,e),e.sessionId&&t.set("session_id",e.sessionId),Os(t,e),u(await c.get(`/usage/cost-summary${Ds(t)}`))}function op(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let s=t;s.ownerId&&n.set("owner_id",s.ownerId)}Os(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`${I().backendUrl||""}${r}?${n}`}async function KR(e,t={}){let n=op(e==="projects"?"projects":"sessions",t),r=await Le(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),s=r.headers.get("x-kortix-row-cap"),o=s!=null?Number(s):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(o)?o:null}}async function __(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function qR(e){return __("slack",e)}function GR(e){return __("teams",e)}async function b_(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function WR(e){return b_("slack",e)}function HR(e){return b_("teams",e)}async function cp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function lp(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var VR={oauth_available:!1,install_url:null};async function up(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?VR:t.data}async function S_(e,t,n){return u(await c.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function pp(e,t){return S_("slack",e,t)}function dp(e,t){return S_("teams",e,t)}async function gp(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function mp(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function zR(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/telegram/installation`,{showErrors:!1});return t.success?t.data??null:null}async function YR(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/telegram/connect`,t,{showErrors:!1}),"Failed to connect Telegram")}async function JR(e,t){return u(await c.put(`/projects/${encodeURIComponent(e)}/channels/telegram/allowed-users`,{user_ids:t},{showErrors:!1}),"Failed to update allowed Telegram users")}async function QR(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/telegram`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect Telegram")}async function fp(e,t){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function yp(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function hp(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 XR={provider:"agentmail",managed_available:!1};async function _p(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?hp(r.data):null}async function bp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?XR:t.data}async function Sp(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return hp(n)}async function xp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function Pp(e,t,n){let r=u(await c.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return hp(r)}async function ZR(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function eC(e,t,n){return u(await c.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function wp(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function kp(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function vp(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Ap(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Rp(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await c.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function Cp(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Tp(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ip(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ep(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Mp(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Op(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Dp(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function jp(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Lp(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function $p(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Up(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Fp(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Np(e,t,n,r,s){return u(await c.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function tC(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function nC(){throw N("getReferralCode")}async function rC(){throw N("refreshReferralCode")}async function sC(e){throw N("validateReferralCode")}async function oC(){throw N("getReferralStats")}async function iC(e={}){throw N("listReferrals")}async function aC(e){throw N("sendReferralEmails")}var Bp="call:";function qp(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Bp)&&e.length>Bp.length?{type:"connector_call",executionId:e.slice(Bp.length)}:{type:"review_item",reviewItemId:e}}function P_(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function cC(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[P_(n.status)]+=1;return t}function lC(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 Kp(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Gp(e){let t=e.indexOf(".");return t<=0?Kp(e):`(${Kp(e.slice(0,t))}) ${Kp(e.slice(t+1))}`}function uC(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Wt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,Ee=e=>Array.isArray(e)?e:void 0,x_=e=>typeof e=="number"?e:0,pC=e=>e.split(`
|
|
14
|
+
`).map(t=>t.trim()).filter(Boolean);function dC(e,t){let n=Wt(e.advanced),r=U(e.description),s=Ee(e.whatChanged)??(r?pC(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:U(e.impact)??"",verification:Ee(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:Ee(e.conflicts),requestedChanges:Ee(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:x_(n.additions),deletions:x_(n.deletions),files:Ee(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function gC(e,t){let n=Ee(e.actions);if(n)return{actions:n.map((l,p)=>({id:U(l.id)??`${t.review_item_id}-${p}`,title:U(l.title)??"Action",connector:U(l.connector)??"",action:U(l.action)??"",consequence:U(l.consequence)??"",risk:U(l.risk)??t.risk,icon:U(l.icon)??"generic",argsPreview:Ee(l.argsPreview)??[],policySource:U(l.policySource)??"Requires approval",decided:l.decided==="approved"||l.decided==="denied"?l.decided:void 0}))};let r=U(e.action_path)??"",{connector:s,action:o}=uC(r),i=Wt(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?Gp(r):t.title||"Run action",connector:s,connectorName:U(e.connector_name),action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([l,p])=>({key:l,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:U(e.approval_context),...Object.keys(Wt(e.resolved_preview)).length>0?{resolvedPreview:Wt(e.resolved_preview)}:{},...U(e.resolved_error)?{resolvedError:U(e.resolved_error)}:{},connectorRisk:U(e.risk)??null,policySource:"Requires approval",expiresAt:U(t.expires_at)}]}}function mC(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:Ee(e.files),note:U(e.note)??t.summary??""}}function fC(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:Ee(e.options)??[]}}function yC(e,t){return{note:U(e.note)??t.summary??"",children:Ee(e.children)??[]}}function hC(e){let t=Wt(e.detail);switch(e.kind){case"change":return dC(t,e);case"approval":return gC(t,e);case"output":return mC(t,e);case"decision":return fC(t,e);case"batch":return yC(t,e)}}function _C(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 bC(e,t={}){let n=Wt(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?U(n.action_path):void 0,i=e.kind==="change"?_C(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:o?Gp(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,expiresAt:U(e.expires_at),detail:hC(e)}}var Q={PROJECT_READ:"project.read",PROJECT_WRITE:"project.write",PROJECT_DELETE:"project.delete",PROJECT_SESSION_READ:"project.session.read",PROJECT_SESSION_START:"project.session.start",PROJECT_SESSION_STOP:"project.session.stop",PROJECT_SESSION_BINDINGS_WRITE:"project.session.bindings.write",PROJECT_MEMBERS_READ:"project.members.read",PROJECT_MEMBERS_MANAGE:"project.members.manage",PROJECT_TRIGGER_READ:"project.trigger.read",PROJECT_TRIGGER_CREATE:"project.trigger.create",PROJECT_TRIGGER_UPDATE:"project.trigger.update",PROJECT_TRIGGER_DELETE:"project.trigger.delete",PROJECT_TRIGGER_FIRE:"project.trigger.fire",PROJECT_GATEWAY_LOGS_READ:"project.gateway.logs.read",PROJECT_GATEWAY_SPEND_READ:"project.gateway.spend.read",PROJECT_USAGE_READ:"project.usage.read",PROJECT_GATEWAY_BUDGET_SET:"project.gateway.budget.set",PROJECT_GATEWAY_KEYS_MANAGE:"project.gateway.keys.manage",PROJECT_AGENT_READ:"project.agent.read",PROJECT_AGENT_WRITE:"project.agent.write",PROJECT_SKILL_READ:"project.skill.read",PROJECT_SKILL_WRITE:"project.skill.write",PROJECT_COMMAND_READ:"project.command.read",PROJECT_COMMAND_WRITE:"project.command.write",PROJECT_FILE_READ:"project.file.read",PROJECT_FILE_WRITE:"project.file.write",PROJECT_SETTINGS_WRITE:"project.settings.write",PROJECT_SANDBOX_WRITE:"project.sandbox.write",PROJECT_MODEL_READ:"project.model.read",PROJECT_MODEL_WRITE:"project.model.write",PROJECT_GITOPS_READ:"project.gitops.read",PROJECT_GITOPS_PUSH:"project.gitops.push",PROJECT_GITOPS_MERGE:"project.gitops.merge",PROJECT_GITOPS_REF_ANY:"project.gitops.ref.any",PROJECT_GITOPS_REF_DELETE:"project.gitops.ref.delete",PROJECT_SECRET_READ:"project.secret.read",PROJECT_SECRET_WRITE:"project.secret.write",PROJECT_CONNECTOR_READ:"project.connector.read",PROJECT_CONNECTOR_CONNECTIONS_MANAGE:"project.connector.connections.manage",PROJECT_CONNECTOR_WRITE:"project.connector.write",PROJECT_APP_READ:"project.app.read",PROJECT_APP_WRITE:"project.app.write",PROJECT_APP_DEPLOY:"project.app.deploy",PROJECT_APP_ADMIN:"project.app.admin",PROJECT_REVIEW_READ:"project.review.read",PROJECT_REVIEW_SUBMIT:"project.review.submit",PROJECT_REVIEW_ACT:"project.review.act",PROJECT_ROOM_READ:"project.room.read",PROJECT_ROOM_WRITE:"project.room.write",PROJECT_CREDENTIALS_ISSUE:"project.credentials.issue"},SC=[Q.PROJECT_WRITE,Q.PROJECT_TRIGGER_CREATE,Q.PROJECT_TRIGGER_FIRE,Q.PROJECT_TRIGGER_UPDATE,Q.PROJECT_TRIGGER_DELETE];function xC(e){let t=r=>e[r]?.allowed===!0,n=t(Q.PROJECT_WRITE);return{canCreate:n&&t(Q.PROJECT_TRIGGER_CREATE),canFire:t(Q.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(Q.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(Q.PROJECT_TRIGGER_DELETE)}}var PC=[Q.PROJECT_WRITE,Q.PROJECT_GITOPS_PUSH,Q.PROJECT_GITOPS_MERGE,Q.PROJECT_REVIEW_ACT];function w_(e){let t=r=>e[r]?.allowed===!0,n=t(Q.PROJECT_WRITE);return{canOpen:n&&t(Q.PROJECT_GITOPS_PUSH),canMerge:n&&t(Q.PROJECT_GITOPS_MERGE),canClose:n}}function wC(e,t,n){let r=qp(e.id);if(r.type==="connector_call"){let s=e.kind==="approval"?e.detail.actions?.[0]:void 0;return(t==="approve"||t==="reject")&&s?.canResolve!==!1&&s?.previewAuthorized!==!1}if(r.type==="change_request"){if(t==="answer")return!1;if(t==="approve")return w_(n).canMerge}return n[Q.PROJECT_WRITE]?.allowed===!0&&n[Q.PROJECT_REVIEW_ACT]?.allowed===!0}function F(e){return c.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function Wp(e){return A(await F(`/accounts/${e}/iam/groups`)).groups}async function Hp(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}`))}async function Vp(e,t){return A(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function zp(e,t,n){return A(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Yp(e,t){return A(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function Jp(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Qp(e,t,n){return A(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function kC(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Xp(e,t,n){return A(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function vC(e,t){return A(await F(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function AC(e,t){let n=A(await F(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function rt(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function RC(e,t={}){let n=rt({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await F(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function CC(e,t={}){let n=rt({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await F(`/accounts/${e}/iam/policies${n}`)).policies}async function TC(e,t){return A(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function IC(e,t,n){return A(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function EC(e,t){return A(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function MC(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function OC(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Zp(e){return A(await F(`/accounts/${e}/iam/roles`)).roles}async function ed(e){return A(await F(`/accounts/${e}/iam/agent-identities`)).agents}async function td(e){return A(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function nd(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/permissions`))}async function DC(e){return A(await F(`/accounts/${e}/iam/actions`)).actions}async function rd(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/usage`))}async function sd(e,t){return A(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function od(e,t,n){return A(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function id(e,t,n){return A(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function ad(e,t){return A(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function jC(e,t,n){return A(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function LC(e){return A(await F(`/accounts/${e}/iam/scim/tokens`)).tokens}async function $C(e,t){return A(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function UC(e,t){return A(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function FC(e){return A(await F(`/accounts/${e}/iam/mfa-required`))}async function NC(e){return A(await F(`/accounts/${e}/iam/mfa-required/preview`))}async function BC(e,t){return A(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function KC(e){return A(await F(`/accounts/${e}/iam/session-oversight`))}async function qC(e,t){return A(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function GC(e){return A(await F(`/accounts/${e}/iam/sso/provider`)).provider}async function WC(e,t){return A(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function HC(e,t){return A(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function VC(e){return A(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function zC(e){return A(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function YC(e){return A(await F(`/accounts/${e}/iam/sso/mappings`)).mappings}async function JC(e,t){return A(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function QC(e,t){return A(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function XC(e){return A(await F(`/accounts/${e}/iam/session-policy`))}async function ZC(e,t){return A(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function eT(e){return A(await F(`/accounts/${e}/iam/sessions`)).sessions}async function tT(e,t){return A(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function nT(e){return A(await F(`/accounts/${e}/iam/pat-policy`))}async function rT(e,t){return A(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function sT(e){return A(await F(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function oT(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function iT(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function aT(e,t){return A(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function cT(e){return A(await F(`/accounts/${e}/audit/webhooks`)).webhooks}async function lT(e,t){return A(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function uT(e,t,n){return A(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function pT(e,t){return A(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function dT(e,t={}){let n=rt({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 F(`/accounts/${e}/audit${n}`))}async function cd(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 F(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function ld(e,t,n){return n.length===0?[]:A(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function gT(e){return A(await F(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function mT(e,t){return A(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function ud(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function pd(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function dd(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function gd(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function md(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function fd(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function fT(e){return rt({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 yd(e,t){return u(await F(`/accounts/${e}/iam/assignments${fT(t)}`)).assignments}async function hd(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await c.post(`/accounts/${e}/iam/assignments`,n))}async function _d(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function bd(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await F(`/accounts/${e}/iam/permissions${n}`)).permissions}async function yT(){let e=await c.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function hT(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function _T(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function bT(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function ST(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function xT(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function PT(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function wT(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function kT(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function vT(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function AT(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function RT(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var k_="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function CT(e){throw N("getGoogleAuthUrl",k_)}async function TT(e,t){throw N("convertPresentationToGoogleSlides",k_)}async function Sd(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind),t?.sessionId&&n.set("session_id",t.sessionId),t?.limit!=null&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);let r=n.toString();return u(await c.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function xd(e){return u(await c.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function Pd(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function wd(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function kd(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function vd(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}async function Ad(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Rd(e){return u(await c.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Cd(e,t){let n=await c.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var js=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function v_(e,t=""){return`${Xn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function A_(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let s=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new js(s,t.status)}return r}async function IT(e){return A_(v_(e))}async function ET(e){return A_(v_(e,"/messages"))}async function Td(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function Id(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Ls(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function $s(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}async function Ed(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders/${n}/run`,{}))}var MT=4;async function R_(e,t){let n=new Array(e.length),r=0,s=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(MT,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let l=n[a];l.ok?o.done.push(i):o.failed.push({reminder:i,error:l.error})}),o}function Md(e,t,n){return R_(t,r=>Ls(e,r.sessionId,r.reminderId,n))}function Od(e,t){return R_(t,n=>$s(e,n.sessionId,n.reminderId))}async function Dd(e){return u(await c.get(`/projects/${e}/reminders`))}var Pe=e=>`/projects/${e}/rooms`;function jd(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&s!==!1&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function Ld(e,t={}){return u(await c.get(`${Pe(e)}${jd({name:t.name,archived:t.archived,mine:t.mine})}`))}async function $d(e,t){return u(await c.post(Pe(e),t))}async function Ud(e,t){return u(await c.get(`${Pe(e)}/${t}`))}async function Fd(e,t,n){return u(await c.patch(`${Pe(e)}/${t}`,n))}async function Nd(e,t,n={}){return u(await c.get(`${Pe(e)}/${t}/messages${jd({after:n.after,before:n.before,limit:n.limit,top:n.top,thread:n.thread})}`))}async function Bd(e,t,n){return u(await c.post(`${Pe(e)}/${t}/messages`,n))}async function Kd(e,t,n){return u(await c.post(`${Pe(e)}/${t}/read`,n===void 0?{}:{seq:n}))}async function qd(e,t,n,r={}){return u(await c.put(`${Pe(e)}/${t}/members/sessions/${n}`,r))}async function Gd(e,t,n){return u(await c.delete(`${Pe(e)}/${t}/members/sessions/${n}`))}async function Wd(e,t,n,r={}){return u(await c.put(`${Pe(e)}/${t}/members/people/${n}`,r))}async function Hd(e,t,n){return u(await c.delete(`${Pe(e)}/${t}/members/people/${n}`))}async function Vd(e,t){return u(await c.get(`${Pe(e)}/people${jd({q:t})}`))}async function zd(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await c.get(`/accounts/tokens${r}`))}async function Yd(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await c.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function Jd(e,t,n){let r=new URLSearchParams;t&&r.set("account_id",t),n?.deleteRevoked&&r.set("delete_revoked","true");let s=r.size>0?`?${r.toString()}`:"";return u(await c.delete(`/accounts/tokens/${encodeURIComponent(e)}${s}`))}async function Qd(){return u(await c.get("/oauth/grants")).grants}async function Xd(e){return u(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function OT(){return u(await c.get("/accounts/me/devices")).devices}async function DT(e){return u(await c.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function Zd(e){return u(await c.get(`/projects/${e}/cli-token`))}async function eg(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function tg(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}function Ht(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,s]of Object.entries(e))n.includes(` ${r} `)&&s!=null&&s!==""&&t.set(r,String(s));return t}function ng(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 rg(e,t){let n=Ht(ng(t)).toString();return u(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function sg(e,t){let n=Ht(ng({...t,projectId:void 0})).toString();return u(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function og(e,t){let n=Ht(ng(t)).toString();return u(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function ig(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function ag(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function cg(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function lg(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function ug(e,t){return u(await c.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function pg(e,t){return u(await c.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function jT(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function dg(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await c.get(`/marketplace/items${n}`))}async function gg(){return u(await c.get("/marketplace/marketplaces"))}async function mg(){return u(await c.get("/marketplace/marketplaces/featured"))}async function fg(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function yg(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function hg(){return u(await c.get("/marketplace/sources"))}async function _g(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function bg(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function LT(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function $T(e){throw N("getTemplate")}async function UT(e,t){throw N("installTemplate")}async function Sg(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function xg(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Us(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Pg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function wg(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function kg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function vg(e,t){let n=await Us(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await c.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),s=new TextEncoder().encode(JSON.stringify(r)),o="";for(let i of s)o+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(o)}`}}async function Ag(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Rg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function Cg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Tg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Fs(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Ns(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function FT(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function NT(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 Ig(e,t,n={}){let r=await FT(t),s=n.mediaType??"application/gzip",o=await Fs(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),Ns(e,o.artifact.artifact_id,{sha256:await NT(r),size_bytes:r.byteLength})}async function Eg(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Mg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Og(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Dg(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function jg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Lg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function $g(e,t,n){return u(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Ug(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var be=(e,t)=>`/projects/${e}/apps/${t}`;async function Fg(e,t){return u(await c.get(`${be(e,t)}/machines`),"Failed to list machines").machines}async function Ng(e,t,n,r){return u(await c.post(`${be(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Bg=(e,t,n)=>Ng(e,t,n,"start"),Kg=(e,t,n)=>Ng(e,t,n,"stop"),qg=(e,t,n)=>Ng(e,t,n,"restart");async function Gg(e,t,n){return u(await c.delete(`${be(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Wg(e,t,n,r={}){return u(await c.put(`${be(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function Hg(e,t,n){return u(await c.post(`${be(e,t)}/exec`,n),"Failed to run the command")}async function Vg(e,t){return u(await c.get(`${be(e,t)}/volumes`),"Failed to list volumes").volumes}async function zg(e,t,n){return u(await c.post(`${be(e,t)}/volumes`,n),"Failed to create the volume")}async function Yg(e,t,n,r){return u(await c.patch(`${be(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function Jg(e,t,n,r){u(await c.delete(`${be(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function Qg(e,t,n){return u(await c.get(`${be(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function Xg(e,t,n){return u(await c.post(`${be(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function Zg(e,t,n,r){return u(await c.post(`${be(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function em(e,t,n,r){return u(await c.post(`${be(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function le(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var ge=e=>`/drives/${encodeURIComponent(e)}`;async function BT(e){let t=u(await c.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new P("Files not found",{status:404});return t[0]}async function KT(e,t){return u(await c.get(`${ge(e)}/access?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load sharing")}async function qT(e,t){return u(await c.put(`${ge(e)}/access`,t),"Failed to share folder")}async function GT(e,t){let n=u(await c.delete(`${ge(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function WT(e){return u(await c.get(`${ge(e)}/principals`),"Failed to load people")}async function HT(e){return u(await c.get(`${ge(e)}/conflicts`),"Failed to load conflicts").conflicts}async function VT(e,t){u(await c.post(`${ge(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function zT(e,t="/"){return(await C_(e,t)).entries}async function C_(e,t="/"){return u(await c.get(`${ge(e)}/files?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load files")}function tm(e,t,n){let r=le(I().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${ge(e)}/files/content?${new URLSearchParams(s)}`}async function YT(e,t,n){let r=await $(tm(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new P(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function JT(e,t,n){let r=await $(tm(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new P(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function QT(e,t,n,r){let s=`${ge(e)}/files/content?${new URLSearchParams({path:t})}`,o=r?.ifMatch?{"If-Match":r.ifMatch}:{},i=r?.onProgress,a=globalThis.XMLHttpRequest;if(i&&a){let d=n instanceof Blob?n:new Blob([n]);return XT(a,s,d,o,i,r?.signal)}let l=u(await c.putRaw(s,n,{signal:r?.signal,headers:o}),"Failed to upload file"),p=n instanceof Blob?n.size:n.byteLength;return i?.(p,p),l}async function XT(e,t,n,r,s,o){let i=`${le(I().backendUrl)}${t}`,{headers:a,rejected:l}=await Lt(i,{"Content-Type":"application/octet-stream",...r});return new Promise((p,d)=>{let g=new e,m=()=>new P("Request aborted",{name:"AbortError",code:"ABORTED"});if(o?.aborted)return d(m());let f=()=>g.abort();o?.addEventListener("abort",f,{once:!0});let h=()=>o?.removeEventListener("abort",f);g.open("PUT",i),a.forEach((S,v)=>g.setRequestHeader(v,S)),g.upload.onprogress=S=>s(S.loaded,n.size),g.onload=()=>{h();let S=null;try{S=g.responseText?JSON.parse(g.responseText):null}catch{S=null}if(g.status>=200&&g.status<300)return p(S);g.status===401&&l(),d(new P(S?.message||"Failed to upload file",{status:g.status,code:S?.code,url:i}))},g.onerror=()=>{h(),d(new P("Network error while uploading",{name:"TypeError",url:i}))},g.onabort=()=>{h(),d(m())},g.send(n)})}async function ZT(e,t){return u(await c.post(`${ge(e)}/files/mkdir`,{path:t},{showErrors:!1}),"Failed to create folder")}async function eI(e,t,n){return u(await c.post(`${ge(e)}/files/move`,{from:t,to:n},{showErrors:!1}),"Failed to move")}async function tI(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await c.delete(`${ge(e)}/files?${new URLSearchParams(r)}`,{showErrors:!1}),"Failed to delete")}async function nI(e){return u(await c.get(`${ge(e)}/versions`),"Failed to load versions").versions}async function rI(e,t){u(await c.post(`${ge(e)}/restore`,{versionId:t}),"Failed to restore version")}var sI=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function oI(e,t){return(await T_(e,t)).drives}async function T_(e,t){return u(await c.get(sI(e,t)),"Failed to load session files")}function st(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}var Ke={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function ot(){let e=st("BACKEND_URL")||I().backendUrl;return e||"http://localhost:8008/v1"}function qe(e){let t=le(e);return t.endsWith("/v1")?t:`${t}/v1`}function er(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=er(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return er(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function iI(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 Bs(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||"platinum",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${ot()}/p/${n.external_id}/${Ke.KORTIX_MASTER}`:""),status:iI(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 nm(){let e=await Pt(),t=[];for(let n of e){let r=await At(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Bs(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function rm(e){let t=await c.get(`/sessions/${encodeURIComponent(e)}`,{showErrors:!1});if(t.success&&t.data)return t.data;if(t.error?.status===400||t.error?.status===404)return null;throw t.error??new Error("Session request failed")}async function Ks(e){let t=await rm(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await tr(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function tr(e){let t=await nm();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}async function sm(e){return u(await c.post("/notifications/device-token",e))}async function om(e,t){return u(await c.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}async function im(e,t){let n=I().fetch??((o,i)=>fetch(o,i)),r=qe(t?.backendUrl??I().backendUrl),s=await n(`${r}/notifications/device-token/release`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({device_token:e}),credentials:"omit",...t?.signal?{signal:t.signal}:{}});if(!s.ok)throw new P(`Device token release failed (HTTP ${s.status})`,{status:s.status,response:s});return{ok:!0}}var aI=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered","message"];async function am(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 c.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function cm(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await c.post("/notifications/read",t))}var cI={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1},capture_device_down:{push:!0,email:!0},capture_device_recovered:{push:!0,email:!1},message:{push:!0,email:!0}};async function lm(){return u(await c.get("/notifications/preferences",{showErrors:!1}))}async function um(e){return u(await c.put("/notifications/preferences",e))}async function pm(){return u(await c.get("/notifications/web-push/key",{showErrors:!1}))}async function dm(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await c.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function gm(e,t){return u(await c.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function nr(e){return u(await c.get(`/projects/${e}/model-access`))}async function rr(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}async function sr(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/custom-providers`)).providers}async function or(e,t,n){return u(await c.put(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,n))}var I_=e=>e?.status===404;async function ir(e,t){let n=await c.delete(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,{showErrors:!1});if(!n.success&&!I_(n.error))throw n.error??new Error("Failed to delete the custom provider");let r=`CUSTOM_${t.toUpperCase().replace(/-/g,"_")}_API_KEY`;await jn(e,r).catch(s=>{if(!I_(s))throw s})}function lI(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:o,previewIsLinkOnly:i}=e;return t||n?!1:s?o&&!i:r==="error"}function mm(e){return typeof e=="string"&&e.trim().length>0}function E_(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return mm(t)||mm(n)||mm(r)}function uI(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 ar(e){if(!e)return!0;let t=uI(e.items);return t?!t.some(E_):!E_(e)}var ke="kortix.transcript.v1",M_=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function fm(e){return typeof e=="string"&&M_.includes(e)}var pI=["once","always","reject"],dI=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var j_="kortix-v1-import",gI={harness:j_,harness_version:ke,adapter_version:"1"},ym={schema:ce,v:1},mI={opencode:"[Tool execution was interrupted]",pi:"No result provided"},fI="[Old tool result content cleared]",yI="The following tool was executed by the user",hI=new Map(Object.entries({bash:"shell",powershell:"shell",read:"read",write:"write",edit:"edit",multiedit:"edit",patch:"patch",apply_patch:"patch",list:"list",ls:"list",glob:"glob",find:"glob",grep:"grep",webfetch:"web_fetch",websearch:"web_search",codesearch:"web_search",todowrite:"todo",todoread:"todo",task:"task",question:"question",plan_enter:"plan",plan_exit:"plan"})),_I=e=>hI.get(e)??(e.includes("_")?"mcp":"other"),bI=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),SI=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),X=e=>typeof e=="string"?e:void 0,Ge=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Hs=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,L_=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Vt=e=>Ge(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,zt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function hm(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>hm(r,t[s]));if(!B(e)||!B(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0);return n.length===Object.keys(t).filter(r=>t[r]!==void 0).length&&n.every(r=>hm(e[r],Hs(t,r)))}function Gs(e,t){if(hm(e,t))return;if(e===void 0)return{del:!0};if(!B(e)||!B(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let s=Gs(Hs(e,r),Hs(t,r));s&&L_(n,r,s)}return{sub:n}}function Ws(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=B(e)?{...e}:{};for(let[r,s]of Object.entries(t.sub)){let o=Ws(Hs(n,r),s);o===void 0?delete n[r]:L_(n,r,o)}return n}var cr=e=>Object.values(e??{}).find(t=>t.version===ke),Vs=(e,t)=>({[e]:{version:ke,...t}}),$_=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},O_=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),xI=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),PI=e=>{if(B(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==ke&&B(n.data?.details));return t?t.data.details:{}};function wI(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=zt(e.started_at)??t.created,i=zt(e.ended_at)??o,a=r?.exit_code!==void 0?{exit:r.exit_code}:{};if(e.status==="pending")return{status:"pending",input:e.input??{},raw:""};if(e.status==="running")return{status:"running",input:e.input??{},...e.title&&{title:e.title},time:{start:o}};if(e.status==="error")return{status:"error",...s,error:O_(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:o,end:i}};let l=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...$_(d,t)}]:[]),p=zt(r?.cleared_at);return{status:"completed",...s,output:O_(r?.content),title:e.title??"",metadata:{...PI(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...l.length&&{attachments:l}}}function U_(e,t){let n=xI(e,t);switch(e.type){case"text":return{...n,type:"text",text:e.text,...e.synthetic!==void 0&&{synthetic:e.synthetic}};case"reasoning":return{...n,type:"reasoning",text:e.text,time:{start:t.created}};case"attachment":return{...n,type:"file",mime:e.mime,...e.name!==void 0&&{filename:e.name},...$_(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:wI(e,t,{...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID})};case"step":return e.phase==="start"?{...n,type:"step-start"}:{...n,type:"step-finish",reason:"stop",cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};case"compaction":return{...n,type:"compaction",auto:e.trigger==="auto"||e.trigger==="overflow",...e.trigger==="overflow"&&{overflow:!0},...e.first_kept_message_id!==null&&{tail_start_id:e.first_kept_message_id}};case"harness":return t.fromV1&&(e.harness==="opencode"||e.harness==="pi")?e.data:e.model_visible&&e.fallback_text!==void 0?{...n,type:"text",text:e.fallback_text,synthetic:!0}:void 0;case"subtask":return}}function kI(e){return fm(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function F_(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:SI.get(e.finish);return{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"assistant",time:{created:t.created,...e.completed_at!==null&&{completed:zt(e.completed_at)}},...e.reply_to&&{parentID:e.reply_to},modelID:e.model?.model??"",providerID:e.model?.provider??"",...e.model?.variant!==void 0&&{variant:e.model.variant},mode:e.agent??"",agent:e.agent??"",path:{cwd:"",root:""},cost:r?.cost??0,tokens:{input:r?.input??0,output:r?.output??0,reasoning:r?.reasoning??0,cache:{read:r?.cache_read??0,write:r?.cache_write??0}},...s&&{finish:s},...e.error&&{error:kI(e.error)},...n}}function N_(e,t){return e.role==="assistant"?F_(e,t):{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"user",time:{created:t.created},agent:e.agent??"",model:{providerID:e.model?.provider??"",modelID:e.model?.model??"",...e.model?.variant!==void 0&&{variant:e.model.variant}}}}function B_(e,t,n){let r=`${e.message_id}-summary`;return{info:F_({...e,reply_to:e.message_id,agent:"compaction",finish:e.status==="complete"?"stop":null},n,{id:r,summary:!0}),parts:[{id:`${r}-p0`,...n.sessionID!==null&&{sessionID:n.sessionID},messageID:r,type:"text",text:t.summary}]}}function vI(e,t,n){let r=n||e.producer.harness===j_;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=cr(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:zt(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=U_(d,i);return g===void 0?[]:[Ws(g,cr(d.ext)?.data)]}),l=[{runtime_session_id:o,info:Ws(N_(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=Ws(B_(e,p,i),s?.summary);l.push({runtime_session_id:o,info:d.info,parts:d.parts})}return l}var _m=e=>Ge(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,qs=e=>String(B(e.info)?e.info.id:""),K_=(e,t)=>_m(e)-_m(t)||(qs(e)<qs(t)?-1:qs(e)>qs(t)?1:0),D_=e=>{let t=cr(e.ext);return t?t.native_id??null:e.thread_id};function zs(e){let t=structuredClone(e),n=t.threads.find(i=>i.parent_thread_id===null)??t.threads[0],r=t.threads.flatMap(i=>i.messages.flatMap(a=>vI(a,D_(i),cr(i.ext)!==void 0))),s=cr(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?D_(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(K_)}}function AI(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:B(e.model)?{p:e.model.providerID,m:e.model.modelID,v:e.model.variant}:{},n=X(t.p),r=X(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...X(t.v)!==void 0&&{variant:t.v}}}function RI(e){if(!B(e.tokens))return null;let t=e.tokens,n=B(t.cache)?t.cache:{};return{input:Ge(t.input)??0,output:Ge(t.output)??0,cache_read:Ge(n.read)??0,cache_write:Ge(n.write)??0,...Ge(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Ge(e.cost)!==void 0&&{cost:e.cost}}}var CI=e=>({code:X(e.code)||X(e.name)||"UnknownError",message:X(B(e.data)?e.data.message:void 0)??""});function q_(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:X(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...X(e.url)!==void 0&&{url:e.url}}}function TI(e,t,n,r){let s=e.state,o=B(s.time)?s.time:{};B(s.input)||r.tool_input++;let i=B(s.metadata)&&Ge(s.metadata.exit)!==void 0?{exit_code:s.metadata.exit}:{},a,l,p=s.input??null;if(s.status==="completed"){let m=(Array.isArray(s.attachments)?s.attachments:[]).filter(B).map(h=>{let{bytes:S,...v}=q_(h,n,r);return{type:"attachment",...v}}),f=Vt(o.compacted);a="complete",l={content:[...X(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:fI}],cleared_at:f}}}else if(s.status==="error"){let m=X(s.error);a="error",l={content:m!==void 0?[{type:"text",text:m}]:[],is_error:!0,...m!==void 0&&{error:{message:m}},...i}}else if(n.live)a=s.status==="pending"?"pending":"running",a==="pending"&&X(s.raw)&&!(B(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=mI[n.h];a="error",l={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=Vt(o.start),g=Vt(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:_I(e.tool),input:p,status:a,...l&&{result:l},...X(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function II(e,t,n,r,s,o){let i=(a,l=!1)=>({type:"harness",id:t,harness:s.h,kind:a,data:e,model_visible:l,...l&&{fallback_text:yI}});if(!B(e))return i("unknown");switch(e.type){case"text":return typeof e.text!="string"||e.ignored===!0?i("text"):{type:"text",id:t,text:e.text,...typeof e.synthetic=="boolean"&&{synthetic:e.synthetic}};case"reasoning":return typeof e.text!="string"?i("reasoning"):{type:"reasoning",id:t,text:e.text};case"file":return e.mime==="text/plain"||e.mime==="application/x-directory"?i("file"):{type:"attachment",id:t,...q_(e,s,o),...X(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&B(e.state)?TI(e,t,s,o):i("tool");case"step-start":case"step-finish":return{type:"step",id:t,phase:e.type==="step-start"?"start":"finish"};case"compaction":{if(e!==n)return i("compaction");let a=e.overflow===!0?"overflow":e.auto===!0?"auto":"manual";return{type:"compaction",id:t,summary:r,first_kept_message_id:X(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(X(e.type)||"unknown")}}function EI(e){let t=e.map((s,o)=>B(s)&&typeof s.id=="string"&&s.id?s.id:`#${o}`),n=new Set(t),r=new Set;return t.map(s=>{if(!r.has(s))return r.add(s),s;let o=2;for(;n.has(`${s}#${o}`);)o++;return n.add(`${s}#${o}`),`${s}#${o}`})}function MI(e,t,n,r,s,o){let i=B(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],l=i.role==="user"?a.find(R=>B(R)&&R.type==="compaction"):void 0,p=t&&B(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",g=l?p:d==="assistant"?i:void 0,m=g&&B(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",h=g&&B(g.time)?Vt(g.time.completed):null,S=o.live?"streaming":"interrupted",v=g?m?f?"aborted":"error":h?"complete":S:l?S:"complete",T=Vt(B(i.time)?i.time.created:void 0)??"",_=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(R=>B(R)&&R.type==="text"&&typeof R.text=="string"?[R.text]:[]).join(""):null,b={tool_input:0,cut_point:0,attachment:0},O=EI(a),y=a.map((R,L)=>II(R,O[L],l,_,o,b)),w=y.some(R=>R.type==="text"||R.type==="attachment"||R.type==="tool_call"||R.type==="harness"&&R.model_visible),x=!s&&d!=="system"&&(l?v==="complete":!m||f&&w),k=o.live&&x&&v!=="streaming"&&y.some(R=>R.type==="tool_call"&&(R.status==="pending"||R.status==="running"))?"streaming":v,C=s?"superseded":x||!m?void 0:f?"aborted":"failed_attempt";return l&&B(l)&&X(l.tail_start_id)===void 0&&b.cut_point++,{m:{...ym,message_id:X(i.id)??"",thread_id:n,seq:r,role:d,kind:l?"compaction":"turn",status:k,in_context:x,...C&&{hidden_reason:C},agent:X(i.agent)??null,...d==="assistant"&&{reply_to:X(i.parentID)??null},model:AI(i),usage:g?RI(g):null,finish:!g||l?null:f?"aborted":m?"error":bI.get(i.finish)??null,error:m?CI(m):null,created_at:T,completed_at:g||l?h:T||null,producer:gI,blocks:y},lost:b}}function OI(e,t,n,r,s){let o={};t.runtime_session_id!==r&&(o.runtime_session_id=t.runtime_session_id);let i={sessionID:t.runtime_session_id,messageID:e.message_id,created:zt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=Gs(t.parts[d],U_(p,i));g&&(p.ext=Vs(s,{data:g}))}):o.parts=t.parts;let a=Gs(t.info,N_(e,i));a&&(o.info=a);let l=e.blocks.find(p=>p.type==="compaction");if(n&&l){let p=Gs({info:n.info,parts:n.parts},B_(e,l,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Vs(s,{data:o}))}function DI(e,t,n){if(t){for(let r of[!0,!1])for(let s of e)if(!(s.runtime_session_id===t||!Array.isArray(s.parts))){for(let o of s.parts)if(!(!B(o)||o.type!=="tool"||!B(o.state))&&(r?B(o.state.metadata)&&o.state.metadata.sessionId===t:n(o.state).includes(t)))return{row:s,part:o}}}}function Ys(e,t={}){let n={h:t.harness??"opencode",resolve:t.resolveAttachment??(()=>null),counts:{tool_input:0,cut_point:0,attachment:0},live:t.live===!0},r=structuredClone(e.rows).sort(K_),s=new Map;for(let b of r){let O=s.get(b.runtime_session_id);O?O.push(b):s.set(b.runtime_session_id,[b])}let o=e.root_id,i=s.has(o),a=new Map,l=b=>a.get(b)??(a.set(b,JSON.stringify(b)),a.get(b)),p=new Map;for(let b of s.keys()){let O=i&&b===o?void 0:DI(r,b,l);O&&p.set(b,O)}let d=[...r].reverse().find(b=>b.runtime_session_id===null||!p.has(b.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=b=>b!==null&&p.has(b)?b:m,h=Vt(r.map(_m).find(Number.isFinite))??"",S=[];for(let[b,O]of s){if(b!==g&&(b===null||!p.has(b)))continue;let y=b===g,w=y?r.filter(D=>D.runtime_session_id!==g&&f(D.runtime_session_id)===m):[],x=[...w,...O],k=new Set(w),C=new Map,j=new Set;for(let D of x){let q=B(D.info)?D.info:{};if(q.role!=="user"||!Array.isArray(D.parts)||!D.parts.some(K=>B(K)&&K.type==="compaction"))continue;let W=x.find(K=>!j.has(K)&&K.runtime_session_id===D.runtime_session_id&&B(K.info)&&K.info.role==="assistant"&&K.info.summary===!0&&K.info.parentID===q.id);W&&(C.set(D,W),j.add(W))}let R=[];for(let D of x){if(j.has(D))continue;let q=C.get(D),{m:W,lost:K}=MI(D,q,y?m:b,R.length+1,k.has(D),n);if(OI(W,D,q,b,n.h),W.in_context)for(let je of["tool_input","cut_point","attachment"])n.counts[je]+=K[je];R.push(W)}let L=b===null?void 0:p.get(b),pe=R.find(D=>D.role==="user"&&D.kind==="turn");S.push({...ym,thread_id:y?m:b,parent_thread_id:L?f(L.row.runtime_session_id):null,spawned_by:L&&typeof L.part.callID=="string"?{message_id:X(L.row.info?.id)??"",call_id:L.part.callID}:null,agent:pe?.agent??null,title:null,created_at:R[0]?.created_at||h,messages:R,ext:Vs(n.h,b===null?{}:{native_id:b})})}S.sort((b,O)=>b.parent_thread_id===null?-1:O.parent_thread_id===null?1:_(b)-_(O));let v=S[0]?.messages.filter(b=>b.role==="user"&&b.kind==="turn").at(-1),T=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...ym,session_id:e.session_id,title:null,created_at:h,restore_grade:T?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:v?.agent??null,model:v?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:S,...g!==o&&{ext:Vs(n.h,{data:{root_id:o}})}};function _(b){return r.findIndex(O=>O.runtime_session_id===b.thread_id)}}var bm={schema:ce,v:1},jI=Object.freeze({}),G_=new WeakMap;function lr(e){let t=G_.get(e);if(t&&t.state===e.state)return t.block;let n=e.sessionID??null,r={id:e.messageID,sessionID:e.sessionID,role:"assistant"},o=Ys({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return G_.set(e,{state:e.state,block:o}),o}var Sm=new WeakMap;function xm(e){if(Sm.has(e))return Sm.get(e);let t={...bm,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:ke}},messages:[{...bm,message_id:"",thread_id:"",seq:1,role:"assistant",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:"",completed_at:null,producer:{harness:"",harness_version:"",adapter_version:""},blocks:[e]}]},{rows:n}=zs({...bm,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[t]}),r=n[0].parts[0];return Sm.set(e,r),r}function oe(e){return xm(e)}var me=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",We=e=>me(e)?oe(e):e;function H_(e){let t=oe(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:jI}var V_=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function z_(e){return e.status==="complete"?"completed":e.status}var W_=new WeakMap;function Y_(e){if(e.status!=="complete")return"";let t=W_.get(e);return t===void 0&&W_.set(e,t=V_(e)),t}function J_(e){return e.status==="error"?e.result?.error?.message||V_(e):void 0}function fe(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function LI(e){return fe(e)==="bash"}function Pm(e){let t=fe(e);return t==="question"||t==="ask"}function $I(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Q_=new Set(["show","show_user"]);function wm(e){return Q_.has(fe(e))}function UI(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function km(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Js(e))}function Js(e){let t=me(e)?oe(e):e,n=fe(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:ar(t.state?.input)}var X_=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function vm(e){return X_.has(fe(e))}var FI=50*1024*1024,Am="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",NI=new RegExp(`^kortix-attachment://(${Am})/(${Am})/(${Am})$`);function Cm(e){if(typeof e!="string")return null;let t=NI.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function BI(e){return Cm(e)!==null}var Rm=new WeakMap;async function Tm(e,t,n,r={}){if(n.size>FI)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:Rm.get(n)?.get(s);if(o?.promise)return o.promise;let i=o??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let l=Rm.get(n)??new Map;l.set(s,i),Rm.set(n,l)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=c.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(l=>{throw i.promise=void 0,l}),i.promise}async function Im(e,t){let n=Cm(e);if(!n)throw new Error("Invalid attachment reference");let r=I().backendUrl.replace(/\/$/,""),s=await $(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new P("Could not load attachment",{status:s.status});return s.blob()}var KI=new Set(["show","show_user"]);function qI(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return t;let i=e.indexOf("</file>",o+1);if(i===-1)return t;t.push(e.slice(s,o).trimStart()),n=i+7}}var He=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ur=e=>typeof e=="string"&&e.length>0?e:null,Z_=e=>typeof e=="string"?ur(e.split("/").pop()):null;function Qs(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 GI(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 WI(e){let t=e.blocks.filter(He).map(n=>n.type==="attachment"?{type:"file",url:n.ref??n.url,filename:n.name,mime:n.mime}:n.type==="tool_call"?{type:"tool",tool:n.name,state:{input:n.input}}:n.type==="harness"&&He(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function HI(e,t){for(let n of qI(e))t(Qs(n,"attachment"),Qs(n,"filename")??Z_(Qs(n,"path")),Qs(n,"mime"))}function VI(e,t){for(let n of[e,...GI(e.items)])He(n)&&t(n.attachment,Z_(n.path),null)}function zI(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=He(r)&&Array.isArray(r.blocks)?WI(r):r;if(!He(s)||!He(s.info)||!Array.isArray(s.parts))continue;let o=ur(s.info.id);if(!o)continue;let i=ur(s.info.role)??"unknown",a=(l,p,d)=>{let g=Cm(l);!g||n.has(l)||(n.add(l),t.push({url:l,attachment_id:g.attachmentId,filename:p,mime:d,message_id:o,role:i}))};for(let l of s.parts)He(l)&&(l.type==="file"?a(l.url,ur(l.filename),ur(l.mime)):l.type==="text"&&typeof l.text=="string"?HI(l.text,a):l.type==="tool"&&typeof l.tool=="string"&&KI.has(fe(l.tool))&&He(l.state)&&He(l.state.input)&&VI(l.state.input,a))}return t}function YI(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 JI(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 Em(e,t,n){return e!==void 0?e:YI(st(t),n)}var Mm={get disableMobileAdvertising(){return Em(I().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Em(I().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Em(I().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var QI=new Set(["project-manager"]);function Xs(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Mm.enableProjects||!QI.has(e.name)}function XI(e){let t=e.agents.filter(Xs),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function eb(){return{projects:{list:Pt,listForAccount:Xi,get:wt,detail:In,create:na,createRepo:ra,provision:sa,update:On,archive:Dn,llmCatalog:En,modelPicker:Mn,modelAccess:nr,setModelAccess:rr,customLlmProviders:sr,setCustomLlmProvider:or,deleteCustomLlmProvider:ir,sandboxHealth:$n,sandboxTemplates:Jc,sessions:At,createSession:Rt},github:{linkRepository:pa,replaceProjectRepository:da,getInstallation:ga,listInstallations:ma,listLinkableInstallations:fa,listRepositories:ya,listRepositoryBranches:ha,linkInstallation:ba,saveInstallation:_a,deleteInstallation:xa,storeUserToken:Sa},gitBackend:{get:Pa,repositories:wa},connectStatus:qc,marketplace:{items:o=>dg(o),item:o=>fg(o),itemFile:(o,i)=>yg(o,i),marketplaces:()=>gg(),featured:()=>mg(),sources:{list:()=>hg(),add:o=>_g(o),remove:o=>bg(o)}}}}function tb(){return{billing:{accountState:Lu,accountStateMinimal:$u,transactions:Uu,transactionsSummary:Fu,creditBreakdown:Nu,usageHistory:Bu,usageRollup:sp,sessionCosts:{list:ap,get:Zn},tierConfigurations:Ku,setPlan:tp,previewPlan:ep,acceptEnterpriseOffer:np,contactSales:rp,checkout:{createSession:n=>qu(n),confirmSession:(n,r)=>Gu(n,r)},subscription:{createPortalSession:(n,r)=>Wu(n,r),cancel:(n,r)=>Hu(n,r),reactivate:n=>Vu(n),scheduleDowngrade:(n,r,s)=>zu(n,r,s),cancelScheduledChange:n=>Yu(n),prorationPreview:(n,r)=>Ju(n,r)},credits:{purchase:n=>Qu(n),autoTopupSettings:n=>Xu(n),configureAutoTopup:n=>Zu(n)}},sandboxShares:{list:Ad,create:Rd,revoke:Cd}}}var Yt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function ie(e,t,n){let r=n?.fetch??I().fetch??((p,d)=>fetch(p,d)),s=le(n?.backendUrl??I().backendUrl??"");if(!s)throw new Yt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let o={accept:"application/json"};t.body!==void 0&&(o["content-type"]="application/json"),t.bearer&&(o.authorization=`Bearer ${t.bearer}`);let i=await r(`${qe(s)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:o,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),l=null;try{l=a?JSON.parse(a):null}catch{l=a}if(!i.ok){let p=l&&typeof l=="object"?l:{};throw new Yt(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return l}function Zs(e,t){return ie("/auth/signup",{body:e},t)}function eo(e,t){return ie("/auth/sign-in/password",{body:e},t)}function to(e,t){return ie("/auth/sign-in/magic-link",{body:e},t)}function no(e,t){return ie("/auth/verify-otp",{body:e},t)}function ro(e,t){return ie("/auth/sign-in/oauth",{body:e},t)}function so(e,t){return ie("/auth/oauth/exchange",{body:e},t)}function Jt(e,t){return ie("/auth/refresh",{body:e},t)}function oo(e,t){return ie("/auth/password/reset",{body:e},t)}function io(e,t,n){return ie("/auth/password/update",{body:e,bearer:t},n)}function ao(e,t){return ie("/auth/user",{bearer:e},t)}function co(e,t,n){return ie("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function lo(e,t){return ie("/auth/sign-in/sso",{body:e},t)}var uo={enroll:(e,t,n)=>ie("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>ie(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function po(e,t={},n){return ie("/auth/sign-out",{body:t,bearer:e},n)}function go(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,l=0,p=new Set,d=S=>(S.expires_at??0)*1e3,g=S=>d(S)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let S of[...p])try{S(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let S=l,v=(async()=>{let T=await e.storage.get();if(S===l&&T)try{let _=JSON.parse(T);_.session?.access_token&&_.session?.refresh_token&&(r=_.session,s=_.user??null)}catch{r=null}return o=!0,r})();i=v,v.then(()=>{i===v&&(i=null)},()=>{i===v&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let S=r.refresh_token,v=l,T=Jt({refresh_token:S},e.request).then(async _=>(v!==l||(r=_.session,_.user&&(s=_.user),await m()),r)).catch(async _=>{if(v!==l)return r;let b=_&&typeof _=="object"&&"status"in _?_.status:0;if(b>=400&&b<500)return r=null,s=null,await m(),null;throw _}).finally(()=>{a===T&&(a=null)});a=T}return a}return{subscribe(S){return p.add(S),()=>{p.delete(S)}},current:()=>r,user:()=>s,load:f,async set(S,v){await f(),l+=1,a=null,r=S,v!==void 0&&(s=v),S||(s=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){l+=1,a=null,r=null,s=null,o=!0,await m()}}}function nb(){return{list:Ii,get:Mi,create:Ei,secretResources:{list:ec,create:tc,rotate:nc,retry:rc,remove:sc,grant:oc,revoke:ic,setAccess:ac},updateName:Oi,branding:{get:Di,update:ji,uploadAsset:Li,removeAsset:$i,reset:Ui},leave:Ji,members:Fi,invite:Ni,removeMember:zi,updateMemberRole:Yi,invites:Bi,cancelInvite:Ki,resendInvite:qi,tokens:{list:zd,create:Yd,revoke:Jd},connectedApps:{list:Qd,revoke:Xd},audit:{log:rg,export:og,webhooks:{list:ig,create:ag,update:cg,remove:lg}}}}function rb(){return{assignments:{list:yd,create:hd,revoke:_d},permissions:{list:bd,forRole:nd},roles:{list:Zp,create:sd,update:od,setPermissions:id,remove:ad,usage:rd},groups:{list:Wp,get:Hp,create:Vp,update:zp,remove:Yp,members:{list:Jp,add:Qp,remove:Xp}},agentIdentities:ed,oauthClients:{list:ud,get:pd,create:dd,update:gd,rotateSecret:md,remove:fd},can:cd,canBatch:ld}}function sb(){let e={signUp:Zs,signInWithPassword:eo,sendMagicLink:to,verifyOtp:no,signInWithProvider:ro,exchangeCode:so,refresh:Jt,resetPassword:oo,updatePassword:io,updateUserMetadata:co,signInWithSso:lo,mfa:uo,user:ao,signOut:po,session:go},t=nb(),n=rb();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Gi,describe:Wi,accept:us,acceptAndLand:Hi,decline:Vi}}}var pr=new Map,Om=new Map;function Dm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function ob(e){return pr.get(Dm(e))??null}function ib(){return[...pr.values()].filter(e=>typeof e=="string")}function ab(e){return pr.has(Dm(e))}async function it(e){let t=Dm(e),n=pr.get(t);if(n!==void 0)return n;let r=Om.get(t);if(r)return r;let s=(async()=>{try{let o=await c.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let i=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return pr.set(t,i),i}catch{return null}finally{Om.delete(t)}})();return Om.set(t,s),s}function cb(e){let{apiBaseUrl:t}=e;return ab(t)||it(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:ob(t)}}function lb(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 P(`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 s=I().backendUrl??e.backendUrl,o=80,i=t(s);return i&&(o=i.port?Number(i.port):i.protocol==="https:"?443:80),cb({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function ub(e,t){let n=null;async function r(){n||(n=Wn(e,t,{showErrors:!1}).then(s=>{let o=Qn(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,l=s.agent_name?.trim()||void 0;return{model:a,agent:l}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var Qt={url:null,sandboxId:null,dbSandboxId:null,version:0},eE=new Set;function mo(e,t=null,n=null){if(!(Qt.url===e&&Qt.sandboxId===t&&Qt.dbSandboxId===n)){Qt={url:e,sandboxId:t,dbSandboxId:n,version:Qt.version+1};for(let r of eE)r()}}function pb(){return Qt.url}var dr=new Map;function db(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Ct=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function gb(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await nt(e,t,Math.min(3e4,o()));for(;Date.now()<s&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,o()))),i=await nt(e,t,Math.min(3e4,o()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new P(db(i),{code:"RUNTIME_UNAVAILABLE"});let l=i.sandbox.external_id;if(!l)throw new P("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ie(l);return mo(p,l),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:l}}return n}function mb(e,t,n){let r=null;function s(){if(r)return r;let p=c_(e,t);return p&&(r=p),r}let o=gb(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=it(I().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?Ru(p.session):null,h=f?.sandbox?.external_id,S=f?.runtime_session_id;if(h&&S){let b=Ie(h);return mo(b,h),r={runtimeSessionId:S,opencodeSessionId:S,runtimeUrl:b,sandboxId:h},Ts(e,t,r),await m,r}let v=`${e}
|
|
15
|
+
${t}`,T=dr.get(v);if(T)return r=await T,await m,r;let _=o(g);dr.set(v,_);try{return r=await _,await m,r}finally{dr.get(v)===_&&dr.delete(v)}}function a(p){let d=s();if(!d)throw new Ct(p);return d}function l(){r=null,l_(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:l}}var G=["directory","workspace"],fb=["messageID","model","agent","noReply","tools","format","system","variant","parts"],E=(e,t,n=G,r=[],s)=>({method:e,path:t,query:n,body:r,bodyParam:s}),tE={"session.list":E("GET","/session",[...G,"scope","path","roots","start","search","limit"]),"session.get":E("GET","/session/{sessionID}"),"session.create":E("POST","/session",G,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":E("DELETE","/session/{sessionID}"),"session.update":E("PATCH","/session/{sessionID}",G,["title","metadata","permission","time"]),"session.status":E("GET","/session/status"),"session.messages":E("GET","/session/{sessionID}/message",[...G,"limit","before"]),"session.prompt":E("POST","/session/{sessionID}/message",G,fb),"session.promptAsync":E("POST","/session/{sessionID}/prompt_async",G,fb),"session.abort":E("POST","/session/{sessionID}/abort"),"session.revert":E("POST","/session/{sessionID}/revert",G,["messageID","partID"]),"session.unrevert":E("POST","/session/{sessionID}/unrevert"),"session.summarize":E("POST","/session/{sessionID}/summarize",G,["providerID","modelID","auto"]),"session.command":E("POST","/session/{sessionID}/command",G,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":E("POST","/session/{sessionID}/share"),"session.unshare":E("DELETE","/session/{sessionID}/share"),"session.fork":E("POST","/session/{sessionID}/fork",G,["messageID"]),"session.diff":E("GET","/session/{sessionID}/diff",[...G,"messageID"]),"session.todo":E("GET","/session/{sessionID}/todo"),"permission.list":E("GET","/permission"),"permission.reply":E("POST","/permission/{requestID}/reply",G,["reply","message"]),"question.list":E("GET","/question"),"question.reply":E("POST","/question/{requestID}/reply",G,["answers"]),"question.reject":E("POST","/question/{requestID}/reject"),"part.update":E("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",G,[],"part"),"part.delete":E("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":E("GET","/file",[...G,"path"]),"file.read":E("GET","/file/content",[...G,"path"]),"find.files":E("GET","/find/file",[...G,"query","dirs","type","limit"]),"vcs.diff":E("GET","/vcs/diff",[...G,"mode","context"]),"global.health":E("GET","/global/health",[]),"global.dispose":E("POST","/global/dispose",[]),"global.config.get":E("GET","/global/config",[]),"global.config.update":E("PATCH","/global/config",[],[],"config"),"provider.list":E("GET","/provider"),"provider.auth":E("GET","/provider/auth"),"provider.oauth.authorize":E("POST","/provider/{providerID}/oauth/authorize",G,["method","inputs"]),"provider.oauth.callback":E("POST","/provider/{providerID}/oauth/callback",G,["method","code"]),"auth.set":E("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":E("GET","/agent"),"app.skills":E("GET","/skill"),"app.log":E("POST","/log",G,["service","level","message","extra"]),"command.list":E("GET","/command"),"tool.ids":E("GET","/experimental/tool/ids"),"tool.list":E("GET","/experimental/tool",[...G,"provider","model"]),"mcp.status":E("GET","/mcp"),"mcp.add":E("POST","/mcp",G,["name","config"]),"mcp.connect":E("POST","/mcp/{name}/connect"),"mcp.disconnect":E("POST","/mcp/{name}/disconnect"),"mcp.auth.start":E("POST","/mcp/{name}/auth"),"mcp.auth.callback":E("POST","/mcp/{name}/auth/callback",G,["code"]),"mcp.auth.remove":E("DELETE","/mcp/{name}/auth"),"project.list":E("GET","/project"),"project.current":E("GET","/project/current"),"path.get":E("GET","/path")};function nE(e,t){let n=[];for(let r of e.query){let s=t[r];s!=null&&n.push(`${r}=${encodeURIComponent(String(s))}`)}return n.length?`?${n.join("&")}`:""}function rE(e,t,n={},r={}){let s=tE[t],o=s.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(s.bodyParam)i=n[s.bodyParam],a=i!==void 0;else for(let p of s.body)p in n&&(i={...i,[p]:n[p]},a=!0);let l=new Headers(r.headers);return a&&l.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${o}${nE(s,n)}`,{method:s.method,headers:l,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function sE(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 oE(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=sE(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let s=await r.text(),o=s;try{o=JSON.parse(s)}catch{}return{error:o||{},request:t,response:r}}function jm(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let s=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!s.ok)throw Object.assign(new Error(`SSE failed: ${s.status} ${s.statusText}`),{status:s.status});if(!s.body)throw new Error("No body in SSE response");let o=s.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{o.cancel().catch(()=>{})}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:l,value:p}=await o.read();if(l)break;a=(a+p).replace(/\r\n/g,`
|
|
16
16
|
`).replace(/\r/g,`
|
|
17
17
|
`);let d=a.split(`
|
|
18
18
|
|
|
19
19
|
`);a=d.pop()??"";for(let g of d){let m={},f=[];for(let h of g.split(`
|
|
20
20
|
`))if(h.startsWith("data:"))f.push(h.replace(/^data:\s*/,""));else if(h.startsWith("id:"))m.id=h.replace(/^id:\s*/,"");else if(h.startsWith("retry:")){let S=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(S)||(m.retry=S)}f.length&&(m.data=f.join(`
|
|
21
|
-
`)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*sE(e,t,n){let r=e.eventTransport??Om(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let l=new Headers(n.headers);i!==void 0&&l.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:l,signal:s}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(o=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(l){if(n.onSseError?.(l),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(o*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function gr(e){let t=s=>(o,i)=>rE(e,tE(e.baseUrl,s,o,i)),n=s=>o=>t(s)(void 0,o);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(s={})=>({stream:sE(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,s)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var mb=200;async function oE(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function at(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new x(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function fb(e){let t=e.runtimeUrl.replace(/\/$/,""),n=gr({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(l,p)=>{let d=new URLSearchParams;l!==void 0&&d.set("limit",String(l)),p&&d.set("before",p);let g=`/messages/${s}${d.size?`?${d}`:""}`,m=S=>e.fetch(new Request(`${t}${S}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new x(`Reading the session transcript failed: ${await oE(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,mb),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await o(Math.min(r.limit-a.length,mb),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,s,o]=await Promise.all([n.session.status().then(i=>at(i,"Reading the session status failed")),n.permission.list().then(i=>at(i,"Reading permission requests failed")),n.question.list().then(i=>at(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{at(await n.permission.reply({requestID:r,reply:s,...o!==void 0?{message:o}:{}}),"Answering the permission request failed")},answerQuestion:async(r,s)=>{if(s===null){at(await n.question.reject({requestID:r}),"Dismissing the question failed");return}at(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let a=await n.global.config.get().then(d=>d.error===void 0?d.data:null),l=typeof a?.model=="string"?a.model:"",p=l.indexOf("/");p>0&&p<l.length-1&&(s={providerID:l.slice(0,p),modelID:l.slice(p+1)})}if(!s)throw new x("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});let i=at(await n.session.status(),"Reading the session status failed")?.[e.rootId];if(i&&i.type!=="idle")throw new x("This session is busy. Wait for the current turn to finish, then run compact again.",{code:"SESSION_BUSY",status:409});return at(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function yb(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return fb({runtimeUrl:r,rootId:n,fetch:$})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,s)=>(await t()).answerPermission(n,r,s),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function hb(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await pu(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Xt=BigInt(4096),Ve=BigInt(0xffffffffffff),_b=Ve+BigInt(1),iE=_b/BigInt(2),ct=BigInt(3600*1e3)*Xt,mo=120*1e3,bb=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,aE=/^msg_([0-9a-f]{12})/,Sb="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Tt(e){let t=aE.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function Zt(e){return BigInt(Math.trunc(e))*Xt&Ve}function It(e,t){let n=e-t&Ve;return n>=iE&&(n-=_b),n}function Dm(e){let t=null;for(let n of e)n!=null&&(t===null||It(n,t)>BigInt(0))&&(t=n);return t}function Pb(e,t){let n=Tt(e);return n===null?!1:It(n,Zt(t))>ct}function xb(e,t){let n=t===void 0?null:Zt(t);return wb(e,r=>n===null||It(r,n)<=ct)}function wb(e,t){let n=[];for(let r of e){let s=Tt(r);s!==null&&t(s)&&n.push(s)}return Dm(n)}function cE(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Sb[n%62])}return e}function jm(e){let t=e.random,n=Zt(e.nowMs-(e.backdateMs??mo)),r=e.newestKnownTime??null;if(r!==null){let o=It(r,n);o>=BigInt(0)&&o<=ct&&(n=r+BigInt(1)&Ve)}let s="";if(t)for(let o=0;o<14;o++)s+=Sb[Math.min(61,Math.floor(t()*62))];else s=cE();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function fo(e={}){let t=e.nowMs??Date.now(),n=Zt(t-mo),r=wb(e.after??[],s=>{let o=It(s,n);return o>=BigInt(0)&&o<=ct});return jm({nowMs:t,newestKnownTime:r}).id}function kb(e){return{scope:()=>lu(e.projectId,e.sessionId),providerSecretPool:{list:()=>cc(e.projectId,e.sessionId),get:t=>ac(e.projectId,e.sessionId,t),set:(t,n)=>lc(e.projectId,e.sessionId,t,n)},rescope:t=>uu(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,s=n?.agent??e.agent,o=r&&s?{}:await e.persistedPromptDefaults(),i=r??o.model,a=s??o.agent,l=fo(),p=await zn(e.projectId,e.sessionId,{clientMessageId:l,messageId:l,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new x("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var vb=async function*(e){let t=I().eventStreamTransport;if(!t){yield*Om(((s,o)=>$(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await Lt(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function ze(){let e=lb();return e||(I().billingEnabled??!1?"":c_())}async function Lm(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function $m(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function Um(e){let t=$m(e),n=await $(`${t}/env`);if(!n.ok)throw new Error(await Lm(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Fm(e,t,n){let r=$m(e),s=await $(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await Lm(s,"Failed to save secret"))}async function Nm(e,t){let n=$m(e),r=await $(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Lm(r,"Failed to delete secret"))}var Ab={list:Um,set:Fm,delete:Nm};async function Rb(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await $(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}async function yo(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function mr(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return le(e)}async function Km(e){let t=mr(e),n=await $(`${t}/kortix/pty`);if(!n.ok)throw new Error(await yo(n,"Failed to list terminals"));return n.json()}async function qm(e,t){let n=mr(e),r=await $(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await yo(r,"Failed to create terminal"));return r.json()}async function Gm(e,t,n){let r=mr(e),s=await $(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await yo(s,"Failed to update terminal"));return s.json()}async function Wm(e,t){let n=mr(e),r=await $(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await yo(r,"Failed to remove terminal"))}async function Hm(e,t,n){let r=mr(t),o=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),le(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await Ft();a&&i.set("token",a),n?.wake&&i.set("wake","1");let l=i.toString();return l?`${o}${o.includes("?")?"&":"?"}${l}`:o}function Cb(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 lt="\x1B",Tb="\x07",lE="\0",Bm=`(?:${Tb}|${lt}\\\\)`,uE=[new RegExp(`${lt}\\]697;[^${Tb}${lt}]*${Bm}`,"g"),new RegExp(`${lE}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${lt}\\][0-9]+;rgb:[0-9a-fA-F/]+${Bm}`,"g"),new RegExp(`${lt}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Bm}`,"g"),new RegExp(`${lt}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${lt}\\[\\d+;\\d+R`,"g"),new RegExp(`${lt}\\[\\?[0-9;]*c`,"g")];function Ib(e){let t=e;for(let n of uE)t=t.replace(n,"");return t}var Eb={list:Km,create:qm,update:Gm,remove:Wm,webSocketUrl:Hm};async function M(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await $(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await o.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!o.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${o.status}`);return a}async function pE(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return M(e,`/kortix/tasks${r}`)}async function dE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function gE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function mE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function fE(e,t){return M(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function yE(e,t,n){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function hE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function _E(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function bE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function SE(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return M(e,`/kortix/tickets${n}`)}async function PE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function xE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function wE(e,t){return M(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function kE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function vE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function AE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function RE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function CE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function TE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function IE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function EE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function ME(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function OE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function DE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function jE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function LE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function $E(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function UE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function FE(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function NE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function BE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function KE(e,t,n=200){return M(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function qE(e){return M(e,"/kortix/projects")}async function GE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function WE(e,t){return M(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function HE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function VE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function zE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function YE(e,t,n="all"){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function JE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function QE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function XE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function ZE(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function eM(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function tM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function nM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function rM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function sM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function oM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function iM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function aM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var cM=1e4,lM={retryOnAuthError:!1};function en(e,t,n){return M(e,t,{signal:AbortSignal.timeout(cM),...n},lM)}async function uM(e,t=!1){return(await en(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function pM(e){return(await en(e,"/kortix/services/templates")).templates??[]}async function dM(e,t){return(await en(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function gM(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return en(e,s,{method:r?"DELETE":"POST"})}async function mM(e,t){return en(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function fM(e,t){return en(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Ye=new Map,yM=256,tn=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function ut(){let e=ze();if(!e)throw new tn;return Me(e)}function Me(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=Ye.get(e);if(t)return Ye.delete(e),Ye.set(e,t),t;if(!Zr())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=gr({baseUrl:e,fetch:$,eventTransport:vb});return Ye.set(e,n),Ye.size>yM&&Ye.delete(Ye.keys().next().value),n}function hM(e){Ye.delete(e)}function _M(){Ye.clear()}var ho=new Map;function bM(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=ho.get(e);if(t)return t;let n=gr({baseUrl:e,fetch});return ho.set(e,n),n}function SM(e){ho.delete(e)}function PM(){ho.clear()}async function xM(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 wM(e){let t=ze();if(!t)throw new x("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await $(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new x(`System reload failed (${r.status}): ${await xM(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new x(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(l){throw new x(`System reload returned malformed JSON from ${n}: ${l instanceof Error?l.message:String(l)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var Mb="frontend";function _o(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Mb}] ${t}`,...n?[n]:[]);try{ut().app.log({service:Mb,level:e,message:t,extra:n})}catch{}}var Je={debug:(e,t)=>_o("debug",e,t),info:(e,t)=>_o("info",e,t),warn:(e,t)=>_o("warn",e,t),error:(e,t)=>_o("error",e,t)};var kM=16,vM=8,Ob=6e4,AM=250,RM=1e3,CM=3e4,TM=5,IM=.5,EM=3e3,MM=3e4,Db=2e4,OM=2e3,jb=8;function DM(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function jM(e,t){if(!e||e.type!==t.type)return;if(t.type==="message.part.delta"){let o=e.properties,i=t.properties;if(o.partID!==i.partID||o.field!==i.field||o.messageID!==i.messageID||o.sessionID!==i.sessionID)return}else if(t.type==="log.block.delta"){let o=e.properties,i=t.properties;if(typeof o.delta!="string"||typeof i.delta!="string"||o.thread_id!==i.thread_id||o.message_id!==i.message_id||o.block_id!==i.block_id)return}else return;let n=e.properties,r=t.properties,s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function Lb(e,t){let n=[],r,s=0,o=new Map,i=()=>{if(r&&e.clearTimeout(r),r=void 0,n.length===0)return;let l=n;n=[],o.clear(),s=e.now();for(let p of l)p&&t(p.event)},a=()=>{if(r)return;let l=e.now()-s;r=e.setTimeout(i,Math.max(0,kM-l))};return{push(l){let p=jM(n[n.length-1]?.event,l);if(p)n[n.length-1]={type:p.type,event:p};else{let d=DM(l);if(d){let g=o.get(d);g!==void 0&&(n[g]=void 0),o.set(d,n.length)}n.push({type:l.type,event:l})}a()},flush:i,clearTimer:()=>{r&&e.clearTimeout(r)}}}function $b(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)}}function Vm(e,t,...n){for(let r of e){let s=t(r);if(s)try{s(...n)}catch(o){console.warn("[opencode-events] subscriber handler threw, skipping",o)}}}async function LM(e,t,n,r){return new Promise((s,o)=>{let i=!1,a=t.setTimeout(()=>{i||(i=!0,Je.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:n}),r.abort(),o(new Error(`SSE connect timed out after ${n}ms`)))},n);e.global.event({signal:r.signal,sseDefaultRetryDelay:EM,sseMaxRetryDelay:MM,sseMaxRetryAttempts:1}).then(l=>{i||(i=!0,t.clearTimeout(a),s(l))},l=>{i||(i=!0,t.clearTimeout(a),o(l))})})}async function $M(e,t,n,r,s){let o=!1,i=t.now(),a=e[Symbol.asyncIterator]();for(;!n.aborted;){let l=a.next().then(f=>({kind:"next",result:f}),f=>({kind:"error",error:f})),p=$b(n),d=await Promise.race([l,p.promise.then(()=>({kind:"aborted"}))]);if(p.cleanup(),d.kind==="aborted")break;if(d.kind==="error")throw d.error;if(d.result.done)break;s();let g=d.result.value,m=g&&typeof g=="object"&&"payload"in g?g.payload:g;m?.type&&(m.type!=="server.connected"&&(o=!0),r.push(m),!(t.now()-i<vM)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return o}function Ub(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<OM)}function Fb(e,t,n){Je.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),Vm(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function Nb(e,t,n){let r=t?AM:Math.min(RM*2**Math.min(e-1,TM),CM);return Math.round(r*(1+IM*(n.random?.()??0)))}function Bb(e,t,n){return new Promise(r=>{let s=e.setTimeout(r,n),o=()=>{e.clearTimeout(s),r()};t.addEventListener("abort",o,{once:!0})})}async function Kb(e){let{client:t,t:n,connectTimeoutMs:r,heartbeatTimeoutMs:s,outerSignal:o,retryCount:i,setConnectionState:a,onConnected:l,coalescer:p}=e,d=!1,g=!1,m,f=null,h=new AbortController;a("connecting");let S=$b(o);S.promise.then(()=>h.abort());try{let{stream:v}=await LM(t,n,r,h);l();let T=()=>{n.clearTimeout(m),m=n.setTimeout(()=>{Je.warn("SSE heartbeat timeout, forcing reconnect"),h.abort()},s)};T(),d=await $M(v,n,h.signal,p,()=>{a("open"),T()}),g=d}catch(v){if(f=v,o.aborted)return{streamHadWork:d,stableConnection:g,error:f};let T=String(v),_=jt(v)||jt(v?.cause);if(Je.error("SSE event stream error",{error:T,retryCount:i,isAuthError:_}),_)try{gs(),await ds(),Je.info("SSE: refreshed auth token after auth error")}catch(b){Je.error("SSE: failed to refresh auth token",{error:String(b)})}}finally{n.clearTimeout(m),h.abort(),S.cleanup(),p.flush()}return{streamHadWork:d,stableConnection:g,error:f}}function qb(e){return{type:"heartbeat-gap",gapMs:e}}function Gb(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 UM={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},FM=5e3,NM=1e4,BM=4,fr=new WeakMap;function KM(e,t,n){let r=t.timers??UM,s=t.connectTimeoutMs??Db,o=t.heartbeatTimeoutMs??Ob,i=t.maxConsecutiveHardFailures??jb,a=new AbortController,l=(v,...T)=>Vm(n,v,...T),p=null,d=!1,g=v=>{p!==v&&(p=v,v&&l(T=>T.onConnectionChange,v))},m=r.now(),f=null,h=Lb(r,v=>{m=r.now(),l(T=>T.onEvent,v)}),S={client:e,t:r,connectTimeoutMs:s,heartbeatTimeoutMs:o,outerSignal:a.signal,setConnectionState:g,onConnected:()=>{if(f){let v=r.now()-f.lastActivityAt,T=f.eventful;f=null,(T||v>FM)&&l(_=>_.onGapRehydrate,v)}m=r.now()},coalescer:h};return(async()=>{let v=0,T=0,_=0;for(;!a.signal.aborted;){let b=r.now(),O=await Kb({...S,retryCount:v});if(a.signal.aborted)break;let y=O.error,{streamHadWork:w,stableConnection:P}=O,k=r.now()-b;if(T=Ub(w,y,k)?T+1:0,T>=i){Fb(n,T,y),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||w},_=P&&k<NM?_+1:0;let R=P&&_<=BM;R?v=0:(v++,v>1&&Je.warn("SSE event stream reconnecting",{retryCount:v})),await Bb(r,a.signal,Nb(v,R,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),h.clearTimer()}}}function bo(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?Me(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s},l=fr.get(i);if(l?.isParked()&&(fr.delete(i),l=void 0),!l)l=KM(i,e,new Set([a])),fr.set(i,l);else{l.subscribers.add(a);let f=l.connectionState();f&&s?.(f)}let p=l,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),fr.get(i)===p&&fr.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function Wb(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Me(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Me(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Me(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return bo({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Vb(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new x(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Jm(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 ue(e){let t=(e??ze()).trim();if(!t)throw new tn;return t}async function _r(e,t){let n=await $(`${ue(t)}${e}`);if(!n.ok)throw new x(await Jm(n),{status:n.status,response:n});return n.json()}async function Qm(e,t,n,r,s){let o=await $(`${ue(s)}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new x(`${r} failed (${o.status}): ${await Jm(o)}`,{status:o.status,response:o});return o.json()}var Po=["/workspace","/tmp","/home","/opt"],qM=Po.filter(e=>e!=="/workspace");function Xm(e){return Po.some(t=>e===t||e.startsWith(`${t}/`))}function sn(e){return Xm(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function pt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(qM.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Zm=pt;async function on(e,t){let n=ue(t),r=pt(e)||".";return(await _r(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function an(e,t){let n=pt(e);return _r(`/file/content?path=${encodeURIComponent(n)}`,t)}async function GM(e,t,n){let r=ue(n),s=pt(e),o=await $(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new x(await Jm(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new x("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var WM=8,So=0,zb=[];async function HM(){if(So<WM){So++;return}await new Promise(e=>zb.push(e)),So++}function VM(){So--,zb.shift()?.()}function Yb(e,t){let n=ue(t);return Un(`${n}/file/raw?path=${encodeURIComponent(pt(e))}`)}async function cn(e,t){await HM();try{let n=ue(t);try{return await GM(e,void 0,n)}catch{}let r=await an(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{VM()}}async function br(e){return _r("/file/status",ue(e))}async function Sr(e,t,n){let r=ue(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),_r(`/find/file?${s.toString()}`,r)}async function Pr(e,t){let n=ue(t);return(await _r(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var yr=[400,1200],zM=e=>e===408||e===429||e===502||e===503||e===504,Hb=e=>new Promise(t=>setTimeout(t,e));function YM(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var zm=3e4,Jb=15*6e4,JM=256;function nn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return zm;let t=zm+e/JM;return Math.min(Jb,Math.max(zm,Math.round(t)))}async function QM(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function hr(e,t){let n;for(let s=0;s<=yr.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,YM(a)||s===yr.length)break;await Hb(yr[s]);continue}if(o.ok)return o.json();let i=await QM(o);if(n=new x(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!zM(o.status)||s===yr.length)throw n;await Hb(yr[s])}if(n instanceof x)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new x(`Upload failed: ${r}`)}var Ym=8*1024*1024;function XM(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new x(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Qb(e,t){try{e?.onProgress?.(t)}catch{}}function Xb(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function ZM(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function ln(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=ue(o),l=nn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Ym){let d=await hr(()=>Xb(e,t,p),g=>$(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:l}));return XM(d[0],e.size),Qb(i,{loadedBytes:e.size,totalBytes:e.size}),d}return eO(e,t,p,a,i)}async function eO(e,t,n,r,s){let i=(await hr(()=>Xb(new Blob([],{type:e.type}),t,n),l=>$(`${r}/file/upload`,{method:"POST",body:l},{timeoutMs:nn(0)})))[0]?.path;if(!i)throw new x("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=ZM(i);if(!a.name)throw new x(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let l=0;l<e.size;l+=Ym){let p=Math.min(e.size,l+Ym),d=e.slice(l,p,e.type),g=await hr(()=>{let m=new FormData;return a.parent&&m.append("path",a.parent),m.append("filename",a.name),m.append("first",l===0?"true":"false"),m.append("offset",String(l)),m.append("file",d,a.name),m},m=>$(`${r}/file/append`,{method:"POST",body:m},{timeoutMs:nn(d.size)}));if(g.path!==i||g.size!==p)throw new x(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Qb(s,{loadedBytes:p,totalBytes:e.size})}}catch(l){throw await Et(i,r).catch(()=>{}),l}return[{path:i,size:e.size}]}function Zb(e,t,n){let r=ue(n);return hr(()=>{let s=new FormData;return t&&s.append("path",t),s.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),s},s=>$(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:tO}))}var tO=Jb;function nO(e,t,n){let r=ue(n),s=nn(t.size);return hr(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>$(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var rn=class extends x{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function xr(e,t){let n=ue(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",l=sn(`${a}/${i}`),p=[];try{p=await on(eS(l),n)}catch(g){if(!(g instanceof x&&g.status===404))throw g}if(p.some(g=>g.name===tS(l)))throw new rn(l);let d=await nS(l,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function wr(e,t,n){let r=ue(n);return nO(t,await cn(e,r),r)}function rO(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function eS(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function tS(e){return e.slice(e.lastIndexOf("/")+1)}function sO(){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 kr(e,t,n){let r=ue(n),s=sn(rO(e.trim()));return nS(s,t,r,{overwrite:!0})}async function nS(e,t,n,r){let s=tS(e);if(!s)throw new x(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=eS(e);await un(o,n).catch(()=>{});let i=sO(),a=await ln(t,o,`.${s}.kortix-write-${i}`,n),l=a[0]?.path;if(!l)throw new x(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=sn(l);try{await rS(p,e,n,r.overwrite)}catch(g){throw await Et(p,n).catch(()=>{}),!r.overwrite&&g instanceof x&&g.status===409?new rn(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Et(e,t){return Qm("/file","DELETE",{path:e},"Delete",t)}async function un(e,t){return Qm("/file/mkdir","POST",{path:e},"Mkdir",t)}async function vr(e,t,n){return rS(e,t,ue(n),!0)}async function rS(e,t,n,r){return Qm("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function ef(){return Vb(await ut().project.current())}async function xo(){return Vb(await ut().global.health())}async function tf(){try{return(await xo()).healthy===!0}catch{return!1}}var sS={list:on,read:an,readBlob:cn,status:br,findFiles:Sr,findText:Pr,upload:ln,write:kr,create:xr,copy:wr,remove:Et,mkdir:un,rename:vr,currentProject:ef,health:xo,isReachable:tf,toDaemonPath:pt,toSandboxAbsolutePath:sn,toWorkspaceRelative:Zm};function oS(e){return{list:async t=>on(t,(await e()).runtimeUrl),read:async t=>an(t,(await e()).runtimeUrl),readBlob:async t=>cn(t,(await e()).runtimeUrl),status:async()=>br((await e()).runtimeUrl),findFiles:async(t,n)=>Sr(t,n,(await e()).runtimeUrl),findText:async t=>Pr(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>ln(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>kr(t,n,(await e()).runtimeUrl),create:async t=>xr(t,(await e()).runtimeUrl),copy:async(t,n)=>wr(t,n,(await e()).runtimeUrl),remove:async t=>Et(t,(await e()).runtimeUrl),mkdir:async t=>un(t,(await e()).runtimeUrl),rename:async(t,n)=>vr(t,n,(await e()).runtimeUrl)}}function iS(e){return{get:t=>Wn(e.projectId,e.sessionId,t),presence:(t,n)=>c.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>Zn(e.sessionId,{projectId:e.projectId}),update:t=>nu(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),ru(e.projectId,e.sessionId)),restore:()=>ou(e.projectId,e.sessionId),recover:()=>su(e.projectId,e.sessionId),start:(...t)=>nt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Ru(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Yn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Jn(e.projectId,e.sessionId)),configState:()=>iu(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),au(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),cu(e.projectId,e.sessionId,...t)),setSharing:t=>jl(e.projectId,e.sessionId,t),previews:()=>Bl(e.projectId,e.sessionId),participants:()=>Ll(e.projectId,e.sessionId),watch:()=>$l(e.projectId,e.sessionId),setWatch:t=>Ul(e.projectId,e.sessionId,t),setPinned:t=>Fl(e.projectId,e.sessionId,t),setArchived:t=>Nl(e.projectId,e.sessionId,t),commit:t=>Rl(e.projectId,e.sessionId,t),publicShares:{list:()=>Kl(e.projectId,e.sessionId),create:(...t)=>ql(e.projectId,e.sessionId,...t),revoke:(...t)=>Gl(e.projectId,e.sessionId,...t)}}}function aS(e){return{reminders:{list:()=>Cd(e.projectId,e.sessionId),create:t=>Td(e.projectId,e.sessionId,t),update:(t,n)=>js(e.projectId,e.sessionId,t,n),remove:t=>Ls(e.projectId,e.sessionId,t)},audit:(t,n)=>Vl(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Rm(e.projectId,e.sessionId,t,n),read:(t,n)=>Cm(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>zl(e.projectId,e.sessionId,t),messageAuthors:()=>du(e.projectId,e.sessionId),modelUsage:()=>gu(e.projectId,e.sessionId),transcriptSync:t=>Hn(e.projectId,e.sessionId,t),log:t=>Yl(e.projectId,e.sessionId,t),turn:()=>Vn(e.projectId,e.sessionId),prompts:{create:t=>zn(e.projectId,e.sessionId,t),list:()=>Jl(e.projectId,e.sessionId),remove:t=>Ql(e.projectId,e.sessionId,t),retry:t=>eu(e.projectId,e.sessionId,t),edit:(t,n)=>Xl(e.projectId,e.sessionId,t,n),interrupt:t=>Zl(e.projectId,e.sessionId,t),hold:t=>tu(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function cS(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var iO=["control_plane","provider_ingress","daemon","upstream_port"];function nf(e){return typeof e=="string"&&iO.includes(e)?e:null}function rf(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 sf(e,t){let n=(e===void 0?ze():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await $(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let i=o,a=nf(r.headers.get("X-Kortix-Proxy-Hop"))??nf(o?.hop),l=Number(r.headers.get("X-Kortix-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(l)&&l>0?l:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var lS=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,uS=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,pS=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,dS=new Set([22,4096,parseInt(Ke.KORTIX_MASTER,10)]);function aO(e){return uS.test(e)}function wo(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 cO(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var lO=new Set(["'",'"',"`","<","(","["]),uO=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function pO(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&&lO.has(e[t]);)t++;for(;n>t&&uO.has(e[n-1]);)n--;return e.slice(t,n)}function dO(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var gO=/^\/proxy\/(\d{1,5})(\/.*)?$/,mO=/^\/(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 gS(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:mO.test(t.pathname)}catch{return!1}}function Rr(e){if(!e)return null;let t=pO(cO(e.trim())),n=af(t);if(n){let r=wo(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(Ke.KORTIX_MASTER,10);if(s===i){let l=r.pathname.match(gO);if(l){let p=parseInt(l[1],10);if(p>=1&&p<=65535)return s=p,o=wo(`${l[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=wo(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=dO(e);return r&&r!==e?Rr(r):null}}function fO(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,i=o+r[0].length;t.some(([l,p])=>o>=l&&i<=p)||t.push([o,i])}return t}function yO(e,t){return t.some(([n,r])=>e>=n&&e<r)}function mS(e){let t=[],n=new Set,r=fO(e);lS.lastIndex=0;let s;for(;(s=lS.exec(e))!==null;){let o=Rr(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:l}=o;a<1||a>65535||dS.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:l,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:yO(s.index,r)}))}return t}function hO(e){return mS(e).length>0}function _O(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function fS(e){return e.trim().toLowerCase().split("_").join("-")}function yS(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function bO(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let s=r.split("{port}").join(String(e)).split("{sandbox}").join(fS(n.sandboxId));return`${yS(s)}${t}`}function hS(e){return e.sandboxId.trim().length>0}function dt(e,t,n){let r=wo(t);if(!hS(n))return PS(e,r);let s=bO(e,r,n);return s||(_O(n.apiBaseUrl)?`http://p${e}-${fS(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${yS(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function SO(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return dt(3211,`/open?path=/workspace/${r}`,t)}function _S(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function PO(e){return`http://localhost:3211${_S(e)}`}function bS(){return"/health"}function xO(e){return dt(3211,bS(),e)}function wO(e,t){return dt(e,"/",t)}function SS(e){let t=Rr(e);return!(!t||dS.has(t.port)||gS(e))}function of(e,t){if(!e)return e;let n=Rr(e);return n?SS(n.originalUrl)?dt(n.port,n.path,t):n.originalUrl:e}function PS(e,t="/"){return`http://localhost:${e}${t}`}var xS=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function af(e){let t=e.match(uS);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(pS);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(xS);if(r)try{let s=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(s.port,10)||(s.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function kO(e){try{let t=af(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function vO(e){return aO(e)||pS.test(e)||xS.test(e)}function AO(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Ar="/web-proxy/";function RO(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Ar}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(Ke.KORTIX_MASTER,10);return`${dt(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function CO(e){try{let t=new URL(e),n=t.pathname.indexOf(Ar);if(n===-1)return null;let s=t.pathname.slice(n+Ar.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],i=s[2],a=s[3]||"/";return`${o}://${i}${a}${t.search}${t.hash}`}catch{return null}}function TO(e){try{return new URL(e).pathname.includes(Ar)}catch{return e.includes(Ar)}}function IO(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 EO(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 wS(e){return{health:t=>sf(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>dt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>of(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ie(e.requireReady("sandboxPortUrl").sandboxId,t)}}function cf(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=cb(e,t),{ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g}=db(e,t,n),m={projectId:e,sessionId:t,ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return s},set model(f){s=f},get agent(){return o},set agent(f){o=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...iS(m),...aS(m),...wS(m),...hb(m),...kb(m),...Wb(m),files:oS(l),...yb(m),get runtime(){return Me(d("runtime").runtimeUrl)}}}function kS(e){return{apps:{list:()=>_g(e),create:t=>bg(e,t),get:t=>$s(e,t),update:(...t)=>Sg(e,...t),access:{get:(...t)=>kg(e,...t),update:(...t)=>Ag(e,...t),session:(...t)=>Rg(e,...t),agents:t=>vg(e,t)},remove:t=>Pg(e,t),token:t=>xg(e,t),authEnv:t=>wg(e,t),artifacts:{register:t=>Us(e,t),uploadArchive:(...t)=>Cg(e,...t),finalize:(...t)=>Fs(e,...t)},deployments:{create:(...t)=>Tg(e,...t),list:t=>Ig(e,t),get:(...t)=>Eg(e,...t),logs:(...t)=>Mg(e,...t),remove:(...t)=>jg(e,...t)},start:t=>Og(e,t),stop:t=>Dg(e,t),rollback:(...t)=>Lg(e,...t),machines:{list:t=>$g(e,t),start:(t,n)=>Fg(e,t,n),stop:(t,n)=>Ng(e,t,n),restart:(t,n)=>Bg(e,t,n),destroy:(t,n)=>Kg(e,t,n)},scale:(...t)=>qg(e,...t),exec:(...t)=>Gg(e,...t),volumes:{list:t=>Wg(e,t),create:(...t)=>Hg(e,...t),update:(...t)=>Vg(e,...t),destroy:(...t)=>zg(e,...t),snapshots:(...t)=>Yg(e,...t),snapshot:(...t)=>Jg(e,...t),restore:(...t)=>Qg(e,...t),fork:(...t)=>Xg(e,...t)}}}}function vS(e){return{list:()=>Aa(e),invite:(...t)=>Ta(e,...t),update:(...t)=>Ra(e,...t),revoke:t=>Ca(e,t),pendingInvites:()=>Ia(e),resendInvite:(...t)=>Ma(e,...t),revokeInvite:(...t)=>Ea(e,...t),requests:()=>wa(e),approveRequest:(...t)=>ka(e,...t),rejectRequest:(...t)=>va(e,...t),groupGrants:()=>Oa(e),attachGroupGrant:(...t)=>Da(e,...t),updateGroupGrant:(...t)=>ja(e,...t),detachGroupGrant:t=>La(e,t),resourceGrants:{list:()=>$a(e),create:t=>Ua(e,t),remove:t=>Fa(e,t)}}}function AS(e){return{tokens:{list:()=>Qd(e),create:t=>Xd(e,t),revoke:t=>Zd(e,t)},setupLinks:{requestSecret:t=>cg(e,t),requestConnector:t=>lg(e,t)},validateManifest:t=>Zi(e,t),gitToken:()=>ea(e),agentIdentities:()=>ed(e),secrets:{list:()=>qa(e),upsert:t=>Ga(e,t),setStrategy:(...t)=>Wa(e,...t),broker:(...t)=>Ha(e,...t),remove:t=>jn(e,t),setPersonal:(...t)=>Ja(e,...t),removePersonal:t=>Qa(e,t),setGitCredential:t=>Ya(e,t),listProviderOAuth:()=>Va(e),startProviderOAuth:(...t)=>us(e,...t),pollProviderOAuth:(...t)=>ps(e,...t),removeProviderOAuth:t=>za(e,t)},access:vS(e)}}function RS(e){return{list:()=>pc(e),listAll:()=>dc(e),reconcile:(...t)=>gc(e,...t),reconcileMember:(...t)=>mc(e,...t),updateCredential:(...t)=>fc(e,...t),revoke:(...t)=>yc(e,...t),activate:(...t)=>hc(e,...t),setDefault:(...t)=>_c(e,...t),rename:(...t)=>bc(e,...t),share:(...t)=>Pc(e,...t),addComputer:(...t)=>Sc(e,...t),pipedreamConnect:(...t)=>xc(e,...t),pipedreamFinalize:(...t)=>wc(e,...t)}}function ko(e){return{catalog:t=>Nt(e,t),tools:()=>fs(e),search:(...t)=>uc(e,...t),describe:(...t)=>ys(e,...t),call:(...t)=>kt(e,...t),callAction:(t,n,r,s)=>kt(e,`${t}.${n}`,r,s),accounts:(...t)=>hs(e,...t),uploadAttachment:(...t)=>_s(e,...t)}}function lf(e,t){return{slug:t,run:(r,s,o)=>ws(e,t,r,s,o),call:(r,s,o)=>kt(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?ys(e,`${t}.${r}`):(await Nt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>hs(e,t),paginate:(r,s,o)=>Hc(e,t,r,s,o),uploadAttachment:(r,s)=>_s(e,r,{...s,connector:t})}}var MO=100,CS=0,OO=new Set(["attachment_size_mismatch","attachment_failed"]),TS=()=>new x("Attachment expired. Attach the file again.",{code:"attachment_expired"});function uf(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 DO(e,t,n){let r,s=0,o,i=()=>{o=void 0,!(!t()||e.item.status!=="uploading"||r===void 0)&&(e.item={...e.item,receivedBytes:r},r=void 0,s=Date.now(),n())},a=p=>Math.floor(p*100/e.item.size),l=()=>{o&&clearTimeout(o),o=void 0};return{onProgress:p=>{if(!t()||a(p)===a(e.item.receivedBytes)||(r=p,o))return;let d=s+MO-Date.now();if(d<=0)return i();o=setTimeout(i,d),typeof o=="object"&&"unref"in o&&o.unref()},onProcessing:()=>{l(),r=void 0,t()&&(e.item={...e.item,status:"processing",receivedBytes:e.item.size},n())},clear:l}}function pf(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,i=0,a=!1,l,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,w){y.removalDeleted||(y.removalDeleted=!0,Bt(e,w).catch(()=>{}))}function m(){l&&clearTimeout(l);let y=d().map(({item:P})=>P);(y.length!==p.attachments.length||y.some((P,k)=>P!==p.attachments[k]))&&(p={attachments:y});let w=Math.min(...y.filter(P=>P.status==="ready").map(P=>Date.parse(P.attachment.expires_at)));Number.isFinite(w)&&!a&&(l=setTimeout(()=>{for(let P of d())P.item.status==="ready"&&Date.parse(P.item.attachment.expires_at)<=Date.now()&&(P.item={...P.item,status:"error",error:TS()});m()},Math.min(2147483647,Math.max(0,w-Date.now()))),typeof l=="object"&&"unref"in l&&l.unref());for(let P of s)P();for(let P of[...o])P()}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 w=d();if(w.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(k=>!Number.isSafeInteger(k)||k<=0||k>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(w.reduce((k,C)=>k+C.item.size,0)+y.reduce((k,C)=>k+C,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function S(y,w,P){let k=++y.generation,C=new AbortController;y.abort=C,y.item={...y.item,status:"uploading",error:void 0};let j=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===k,R=DO(y,j,m);Bn(e,w,{resume:y.upload,signal:C.signal,onUpload:L=>{y.upload=L,y.removed&&(C.abort(),g(y,L.attachment_id))},...R}).then(L=>{j()&&(y.item={...y.item,status:"ready",attachment:uf(L),receivedBytes:L.size})}).catch(L=>{L instanceof x&&OO.has(L.code??"")&&(y.upload=void 0),j()&&(y.item={...y.item,status:L instanceof x&&L.code==="ABORTED"?"aborted":"error",error:L instanceof Error?L:new Error(String(L))})}).finally(()=>{R.clear(),y.abort===C&&(y.abort=void 0),P()})}function v(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let w=y.item.file;i++,S(y,w,()=>{i--,m(),v()})}m()}function T(y){h(y.map(P=>P.size));let w=y.map(P=>{let k=`attachment-${++CS}`;return r.set(k,{generation:0,item:{id:k,file:P,filename:P.name,mime:P.type||"application/octet-stream",size:P.size,status:"pending",receivedBytes:0}}),k});return m(),v(),w}function _(y){let w=y.map(({attachment:k,file:C})=>{try{return{attachment:uf(k),file:C}}catch{return}});h(w.flatMap(k=>k?[k.attachment.size]:[]));let P=w.map(k=>{if(!k)return;let C=`attachment-${++CS}`,{attachment:j,file:R}=k;return r.set(C,{generation:0,item:{id:C,...R?{file:R}:{},filename:j.filename,mime:j.mime,size:j.size,status:"ready",receivedBytes:j.size,attachment:j}}),C});return m(),P}function b(y){let w=r.get(y);!w||w.item.status==="ready"||(w.generation++,w.abort?.abort(),w.item={...w.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function O(y,{signal:w}={}){let P=[...y];return new Promise((k,C)=>{let j=()=>{o.delete(pe),w?.removeEventListener("abort",L)},R=D=>{j(),C(D)},L=()=>R(Ae()),pe=()=>{let D=!1;for(let W of P){let K=r.get(W);if(!K)return R(new Error("Attachment was removed before it was sent"));if(a&&!K.handedOff)return R(new Error("Attachment controller is disposed"));if(K.item.status==="error"||K.item.status==="aborted")return R(K.item.error??new Error("Attachment upload failed"));K.item.status!=="ready"&&(D=!0)}if(D)return;let q;try{q=P.map(W=>{let K=uf(r.get(W).item.attachment);return{type:"file",attachment_id:K.attachment_id,filename:K.filename,mime:K.mime}})}catch(W){return R(W instanceof Error?W:new Error(String(W)))}j(),k(q)};if(w?.aborted)return L();o.add(pe),w?.addEventListener("abort",L,{once:!0}),pe()})}return{add:y=>T([y])[0],addMany:T,restore:_,retry(y){let w=r.get(y);if(w?.handedOff||f(),!(!w||w.item.status==="ready"||w.item.status==="uploading"||w.item.status==="processing"||w.item.status==="pending")){if(!w.item.file||w.upload&&Date.parse(w.upload.expires_at)<=Date.now())throw TS();w.item={...w.item,status:"pending",error:void 0},v()}},async remove(y){let w=r.get(y);if(!w)return;w.removed=!0,w.generation++,r.delete(y);let P=w.upload?.attachment_id??w.item.attachment?.attachment_id;P&&w.abort?.abort(),m(),v(),P&&g(w,P)},abort:b,submit(y){if(!a){for(let w of y){let P=r.get(w);P&&(P.handedOff=!0)}m()}},reclaim(y){if(!a){for(let w of y){let P=r.get(w);P&&(P.handedOff=!1)}m()}},whenReady:O,forget(y=d().map(w=>w.item.id)){for(let w of y){let P=r.get(w);P&&(P.generation++,P.abort?.abort(),r.delete(w))}m(),v()},dispose(){if(!a){a=!0,l&&clearTimeout(l);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let w=y.upload?.attachment_id??y.item.attachment?.attachment_id;w&&e&&Bt(e,w).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(y){return s.add(y),()=>{s.delete(y)}}}}function IS(e){return{attachments:{upload:(...t)=>Bn(e,...t),delete:(...t)=>Bt(e,...t),createController:t=>pf(e,t)},get:t=>wt(e,t),detail:()=>In(e),skills:{remove:(...t)=>la(e,...t),create:(...t)=>ca(e,...t)},audit:t=>ng(e,t),update:t=>On(e,t),archive:()=>Dn(e),llmCatalog:()=>En(e),modelPicker:()=>Mn(e),modelAccess:()=>nr(e),setModelAccess:t=>rr(e,t),customLlmProviders:()=>sr(e),setCustomLlmProvider:(t,n)=>or(e,t,n),deleteCustomLlmProvider:t=>ir(e,t),sandboxHealth:()=>$n(e),onboardingComplete:(...t)=>aa(e,...t)}}function ES(e){return{sessions:{list:t=>At(e,t),listPage:t=>Dl(e,t),create:t=>Rt(e,t),ensureWarm:()=>Wl(e),claimWarm:t=>Hl(e,t)},review:{list:t=>bd(e,t),summary:()=>Sd(e),get:t=>Pd(e,t),submit:t=>xd(e,t),act:(...t)=>wd(e,...t),bulkAct:t=>kd(e,t)},approvals:{list:t=>Na(e,t),resolve:(...t)=>Ka(e,...t),sessionsNeedingInput:t=>Ba(e,t)}}}function MS(e){return{files:{list:t=>sl(e,t),listDirectory:t=>ol(e,t),read:(t,n)=>al(e,t,n),search:(...t)=>il(e,...t),archive:(...t)=>cl(e,...t),archiveRequest:(...t)=>ll(e,...t),history:(...t)=>yl(e,...t)},git:{commits:()=>gl(e),commit:t=>ml(e,t),commitDiff:t=>fl(e,t),branches:()=>dl(e),versionDiff:(...t)=>hl(e,...t),inviteCollaborator:(...t)=>Xi(e,...t)},changeRequests:{list:(...t)=>_l(e,...t),get:t=>bl(e,t),update:(...t)=>Cl(e,...t),diff:t=>Sl(e,t),mergePreview:t=>Pl(e,t),open:(...t)=>xl(e,...t),merge:(...t)=>wl(e,...t),close:(...t)=>kl(e,...t),reopen:(...t)=>vl(e,...t),requestChanges:(...t)=>Al(e,...t)},...ES(e)}}function OS(e){return{policies:{list:()=>Vc(e),set:(...t)=>zc(e,...t)},reminders:{list:()=>Md(e),updateMany:(...t)=>Id(e,...t),removeMany:(...t)=>Ed(e,...t)},rooms:{list:(...t)=>Dd(e,...t),create:(...t)=>jd(e,...t),get:(...t)=>Ld(e,...t),update:(...t)=>$d(e,...t),messages:(...t)=>Ud(e,...t),post:(...t)=>Fd(e,...t),markRead:(...t)=>Nd(e,...t),addSession:(...t)=>Bd(e,...t),removeSession:(...t)=>Kd(e,...t),addPerson:(...t)=>qd(e,...t),removePerson:(...t)=>Gd(e,...t),people:(...t)=>Wd(e,...t)},triggers:{list:()=>mu(e),eventApps:()=>ku(e),eventTypes:(...t)=>wu(e,...t),create:(...t)=>fu(e,...t),update:(...t)=>yu(e,...t),remove:(...t)=>hu(e,...t),fire:((t,n)=>bu(e,t,n)),runs:(...t)=>Su(e,...t),projectRuns:(...t)=>Pu(e,...t),replay:(...t)=>xu(e,...t),setActivation:(...t)=>_u(e,...t)},...MS(e)}}function DS(e,t){return{connectors:{...ko(e),list:()=>kc(e),config:(...n)=>Ec(e,...n),create:(...n)=>Dc(e,...n),remove:(...n)=>Uc(e,...n),sync:()=>vc(e),auth:{discover:(...n)=>jc(e,...n)},setName:(...n)=>Mc(e,...n),setCredentialMode:(...n)=>Ac(e,...n),setAuthorizationStrategy:(...n)=>Rc(e,...n),setCredential:(...n)=>qc(e,...n),deleteCredential:(...n)=>Gc(e,...n),setSensitive:(...n)=>Cc(e,...n),connections:t,policies:{get:(...n)=>Tc(e,...n),set:(...n)=>Ic(e,...n)},listMoves:()=>Lc(e),move:(...n)=>$c(e,...n),pipedream:{listApps:(...n)=>Fc(e,...n),listSections:(...n)=>Nc(e,...n),connect:(...n)=>Oc(e,...n),finalize:(...n)=>Wc(e,...n)},discover:{list:(...n)=>bs(e,...n),sections:(...n)=>Bc(e,...n),detail:(...n)=>Ss(e,...n)}},...OS(e)}}function jS(e){return{gateway:{logs:t=>Ap(e,t),log:t=>Rp(e,t),overview:t=>Cp(e,t),series:t=>Tp(e,t),breakdown:t=>Ip(e,t),sessions:t=>Ep(e,t),errors:t=>Mp(e,t),budgets:()=>Op(e),setBudget:t=>Dp(e,t),deleteBudget:t=>jp(e,t),keys:()=>Lp(e),createKey:t=>$p(e,t),revokeKey:t=>Up(e,t),routing:{get:()=>xp(e),set:t=>wp(e,t),reset:()=>kp(e),preview:t=>vp(e,t)},playground:(t,n,r)=>Fp(e,t,n,r)}}}function LS(e){return{modelDefaults:{get:()=>Cu(e),set:t=>Tu(e,t),clear:t=>Iu(e,t)},setDefaultAgent:t=>Ou(e,t),sandbox:{list:()=>rl(e),snapshots:()=>Jc(e),rebuildSnapshot:t=>Qc(e,t),fixWithAgent:()=>Xc(e),createTemplate:t=>Zc(e,t),updateTemplate:(...t)=>el(e,...t),removeTemplate:t=>tl(e,t),buildTemplate:t=>nl(e,t),setProvider:t=>ia(e,t)},setAgentScope:(...t)=>Eu(e,...t)}}function $S(e){return{channels:{slack:{installation:()=>ap(e),connect:t=>cp(e,t),mode:()=>lp(e),completeInstall:t=>up(e,t),manifest:()=>dp(e),disconnect:()=>gp(e),getFile:t=>mp(e,t),uploadFile:t=>fp(e,t)},teams:{completeInstall:t=>pp(e,t)},email:{installation:t=>hp(e,t),mode:()=>_p(e),connect:t=>bp(e,t),disconnect:t=>Sp(e,t),updatePolicy:(...t)=>Pp(e,...t)}},updateFeatureFlag:(...t)=>sa(e,...t),updateExperimentalFeature:(...t)=>oa(e,...t),...LS(e)}}var jO=["screen","actions","audio"],LO=["password_managers","messaging","banking"],$O={localHours:8760,remoteDays:3650},UO=[500,1e3,2e3,5e3,1e4],FO=[720,1080,1440,2160],NO={intervalMs:2e3,maxHeight:1440},BO=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function KO(e){let t=e.trim().toLowerCase();if(!t)return null;let n;try{n=new URL(t.includes("://")?t:`https://${t}`).hostname}catch{return null}return n=n.replace(/^www\./,"").replace(/\.$/,""),BO.test(n)?n:null}function qO(e){let t=e.trim();return!t||t.length>255||t.startsWith("-")||/[\u0000-\u001f\u007f]/.test(t)||t.endsWith("*")&&t.slice(0,-1).trim().length<3?null:t}function GO(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var Y=e=>`/accounts/${e}/capture`;function Qe(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}var US=e=>Qe({q:e.q,kinds:e.kinds?.join(","),app:e.app,limit:e.limit,day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,scope:e.scope}),df=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function gf(e,t={}){return u(await c.get(`${Y(e)}/devices${Qe({user_id:t.userId,scope:t.scope})}`))}async function mf(e,t){return u(await c.delete(`${Y(e)}/devices/${t}`))}async function ff(e,t,n){return u(await c.put(`${Y(e)}/devices/${t}/link`,{user_id:n}))}async function yf(e){return u(await c.get(`${Y(e)}/enrollment-tokens`))}async function hf(e,t){return u(await c.post(`${Y(e)}/enrollment-tokens`,t))}async function _f(e,t){return u(await c.delete(`${Y(e)}/enrollment-tokens/${t}`))}async function bf(e,t={}){return u(await c.get(`${Y(e)}/enrollments${Qe({status:t.status})}`))}async function Sf(e,t,n){return u(await c.post(`${Y(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function Pf(e,t){return u(await c.post(`${Y(e)}/enrollments/${t}/deny`,{}))}async function xf(e){return u(await c.get(`${Y(e)}/policy`))}async function wf(e,t){return u(await c.put(`${Y(e)}/policy`,{policy:t}))}async function kf(e){return u(await c.get(`${Y(e)}/storage`))}async function vf(e,t){return u(await c.put(`${Y(e)}/storage`,t))}async function Af(e,t={}){return u(await c.get(`${Y(e)}/timeline${Qe(df(t))}`))}async function Rf(e,t={}){return u(await c.get(`${Y(e)}/timeline/items${Qe(df(t))}`))}async function Cf(e,t={}){return u(await c.get(`${Y(e)}/days${Qe({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function Tf(e,t){return u(await c.get(`${Y(e)}/search${US(t)}`))}async function If(e,t,n={}){return u(await c.get(`${Y(e)}/frames/${t}${Qe({user_id:n.userId,device_id:n.deviceId})}`))}async function Ef(e,t,n={}){return u(await c.get(`${Y(e)}/chunks/${t}/media${Qe({user_id:n.userId,device_id:n.deviceId})}`))}async function Mf(e,t,n){return u(await c.get(`${Y(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function Of(e){return u(await c.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function Df(e,t){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function jf(e){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function Lf(e){return u(await c.get(Y(e)))}async function $f(e,t){return u(await c.patch(Y(e),{enabled:t}))}async function Uf(e){return u(await c.get(`/capture/me/search${US(e)}`))}async function Ff(e={}){return u(await c.get(`/capture/me/timeline${Qe(df(e))}`))}async function Nf(e){return u(await c.get(`/capture/me/frames/${e}`))}function HO(e){return{workspace:{get:()=>Lf(e),setEnabled:t=>$f(e,t)},devices:{list:t=>gf(e,t),revoke:t=>mf(e,t),link:(t,n)=>ff(e,t,n),assetUrl:(t,n)=>Mf(e,t,n)},enrollment:{tokens:{list:()=>yf(e),create:t=>hf(e,t),revoke:t=>_f(e,t)},list:t=>bf(e,t),approve:(t,n)=>Sf(e,t,n),deny:t=>Pf(e,t)},policy:{get:()=>xf(e),set:t=>wf(e,t)},storage:{get:()=>kf(e),set:t=>vf(e,t)},timeline:{get:t=>Af(e,t),items:t=>Rf(e,t),days:t=>Cf(e,t)},search:t=>Tf(e,t),frame:(t,n)=>If(e,t,n),media:(t,n)=>Ef(e,t,n)}}var FS={account:e=>HO(e),deviceGrant:Of,approveDevice:Df,denyDevice:jf,me:{search:Uf,timeline:Ff,frame:Nf}};async function Bf(e){let t=e?.fetch??I().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??I().backendUrl,r=await t(`${qe(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new x(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var VO=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function zO(e,t){let n=o=>{let i=VO.exec(o.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),s=n(t);if(!r||!s)return null;for(let o=0;o<3;o++)if(r[o]!==s[o])return r[o]<s[o]?-1:1;return 0}function YO(){return ut()}var NS=null,BS=!1;function JO(e){let t=NS;NS=e,!(BS||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(BS=!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 KS(e,t){t?.global!==!1&&JO(e),Xr(e,t);let n=ab(e),{auth:r,accounts:s,iam:o,accountInvites:i}=nb(),{billing:a,sandboxShares:l}=Z_(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=X_();function h(S){let v=RS(S);return{...IS(S),...kS(S),...AS(S),...DS(S,v),...jS(S),...$S(S),connector:T=>lf(S,T),session:T=>cf(S,T,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:ko(),connector:S=>lf(void 0,S),project:h,session:(S,v)=>cf(S,v,e,n),github:d,gitBackend:g,billing:a,sandboxShares:l,connectStatus:m,marketplace:f,capture:FS,notifications:{registerDeviceToken:nm,unregisterDeviceToken:rm,releaseDeviceToken:sm,list:om,markRead:im,preferences:am,updatePreferences:cm,webPushPublicKey:lm,registerWebPushSubscription:um,unregisterWebPushSubscription:pm},mobileClientPolicy:Bf,validateToken:Ji,runtime:YO}}function qS(){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 GS(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function pn(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function WS(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function HS(e){if(pn(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 VS(e){let t=pn(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function zS(e,t){let n=pn(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function YS(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function JS(e,t){return pn(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 QS(e,t,n){return pn(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 XS(e,t,n){let r=pn(e);if(r.includes(t))return e;let s=e.pending.findIndex(p=>p.id===t);if(s===-1)return e;let o=r.length,i=Math.min(Math.max(n,o),e.pending.length-1);if(i===s)return e;let a=[...e.pending],[l]=a.splice(s,1);return a.splice(i,0,l),{...e,pending:a}}var Kf={thinking:!1,toolDetails:!0,assistantMetadata:!0};function QO(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function XO(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 ZO(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
21
|
+
`)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*iE(e,t,n){let r=e.eventTransport??jm(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let l=new Headers(n.headers);i!==void 0&&l.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:l,signal:s}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(o=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(l){if(n.onSseError?.(l),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(o*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function gr(e){let t=s=>(o,i)=>oE(e,rE(e.baseUrl,s,o,i)),n=s=>o=>t(s)(void 0,o);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(s={})=>({stream:iE(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,s)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var yb=200;async function aE(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function at(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new P(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function hb(e){let t=e.runtimeUrl.replace(/\/$/,""),n=gr({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(l,p)=>{let d=new URLSearchParams;l!==void 0&&d.set("limit",String(l)),p&&d.set("before",p);let g=`/messages/${s}${d.size?`?${d}`:""}`,m=S=>e.fetch(new Request(`${t}${S}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new P(`Reading the session transcript failed: ${await aE(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,yb),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await o(Math.min(r.limit-a.length,yb),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,s,o]=await Promise.all([n.session.status().then(i=>at(i,"Reading the session status failed")),n.permission.list().then(i=>at(i,"Reading permission requests failed")),n.question.list().then(i=>at(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{at(await n.permission.reply({requestID:r,reply:s,...o!==void 0?{message:o}:{}}),"Answering the permission request failed")},answerQuestion:async(r,s)=>{if(s===null){at(await n.question.reject({requestID:r}),"Dismissing the question failed");return}at(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let a=await n.global.config.get().then(d=>d.error===void 0?d.data:null),l=typeof a?.model=="string"?a.model:"",p=l.indexOf("/");p>0&&p<l.length-1&&(s={providerID:l.slice(0,p),modelID:l.slice(p+1)})}if(!s)throw new P("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});let i=at(await n.session.status(),"Reading the session status failed")?.[e.rootId];if(i&&i.type!=="idle")throw new P("This session is busy. Wait for the current turn to finish, then run compact again.",{code:"SESSION_BUSY",status:409});return at(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function _b(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return hb({runtimeUrl:r,rootId:n,fetch:$})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,s)=>(await t()).answerPermission(n,r,s),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function bb(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await du(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Xt=BigInt(4096),Ve=BigInt(0xffffffffffff),Sb=Ve+BigInt(1),cE=Sb/BigInt(2),ct=BigInt(3600*1e3)*Xt,fo=120*1e3,xb=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,lE=/^msg_([0-9a-f]{12})/,Pb="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Tt(e){let t=lE.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function Zt(e){return BigInt(Math.trunc(e))*Xt&Ve}function It(e,t){let n=e-t&Ve;return n>=cE&&(n-=Sb),n}function Lm(e){let t=null;for(let n of e)n!=null&&(t===null||It(n,t)>BigInt(0))&&(t=n);return t}function wb(e,t){let n=Tt(e);return n===null?!1:It(n,Zt(t))>ct}function kb(e,t){let n=t===void 0?null:Zt(t);return vb(e,r=>n===null||It(r,n)<=ct)}function vb(e,t){let n=[];for(let r of e){let s=Tt(r);s!==null&&t(s)&&n.push(s)}return Lm(n)}function uE(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Pb[n%62])}return e}function $m(e){let t=e.random,n=Zt(e.nowMs-(e.backdateMs??fo)),r=e.newestKnownTime??null;if(r!==null){let o=It(r,n);o>=BigInt(0)&&o<=ct&&(n=r+BigInt(1)&Ve)}let s="";if(t)for(let o=0;o<14;o++)s+=Pb[Math.min(61,Math.floor(t()*62))];else s=uE();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function yo(e={}){let t=e.nowMs??Date.now(),n=Zt(t-fo),r=vb(e.after??[],s=>{let o=It(s,n);return o>=BigInt(0)&&o<=ct});return $m({nowMs:t,newestKnownTime:r}).id}function Ab(e){return{scope:()=>uu(e.projectId,e.sessionId),providerSecretPool:{list:()=>lc(e.projectId,e.sessionId),get:t=>cc(e.projectId,e.sessionId,t),set:(t,n)=>uc(e.projectId,e.sessionId,t,n)},rescope:t=>pu(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,s=n?.agent??e.agent,o=r&&s?{}:await e.persistedPromptDefaults(),i=r??o.model,a=s??o.agent,l=yo(),p=await zn(e.projectId,e.sessionId,{clientMessageId:l,messageId:l,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new P("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var Rb=async function*(e){let t=I().eventStreamTransport;if(!t){yield*jm(((s,o)=>$(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await Lt(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function ze(){let e=pb();return e||(I().billingEnabled??!1?"":u_())}async function Um(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Fm(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function Nm(e){let t=Fm(e),n=await $(`${t}/env`);if(!n.ok)throw new Error(await Um(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Bm(e,t,n){let r=Fm(e),s=await $(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await Um(s,"Failed to save secret"))}async function Km(e,t){let n=Fm(e),r=await $(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Um(r,"Failed to delete secret"))}var Cb={list:Nm,set:Bm,delete:Km};async function Tb(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await $(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}async function ho(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function mr(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return le(e)}async function Gm(e){let t=mr(e),n=await $(`${t}/kortix/pty`);if(!n.ok)throw new Error(await ho(n,"Failed to list terminals"));return n.json()}async function Wm(e,t){let n=mr(e),r=await $(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await ho(r,"Failed to create terminal"));return r.json()}async function Hm(e,t,n){let r=mr(e),s=await $(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await ho(s,"Failed to update terminal"));return s.json()}async function Vm(e,t){let n=mr(e),r=await $(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await ho(r,"Failed to remove terminal"))}async function zm(e,t,n){let r=mr(t),o=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),le(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await Ft();a&&i.set("token",a),n?.wake&&i.set("wake","1");let l=i.toString();return l?`${o}${o.includes("?")?"&":"?"}${l}`:o}function Ib(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 lt="\x1B",Eb="\x07",pE="\0",qm=`(?:${Eb}|${lt}\\\\)`,dE=[new RegExp(`${lt}\\]697;[^${Eb}${lt}]*${qm}`,"g"),new RegExp(`${pE}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${lt}\\][0-9]+;rgb:[0-9a-fA-F/]+${qm}`,"g"),new RegExp(`${lt}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${qm}`,"g"),new RegExp(`${lt}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${lt}\\[\\d+;\\d+R`,"g"),new RegExp(`${lt}\\[\\?[0-9;]*c`,"g")];function Mb(e){let t=e;for(let n of dE)t=t.replace(n,"");return t}var Ob={list:Gm,create:Wm,update:Hm,remove:Vm,webSocketUrl:zm};async function M(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await $(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await o.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!o.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${o.status}`);return a}async function gE(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return M(e,`/kortix/tasks${r}`)}async function mE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function fE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function yE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function hE(e,t){return M(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function _E(e,t,n){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function bE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function SE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function xE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function PE(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return M(e,`/kortix/tickets${n}`)}async function wE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function kE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function vE(e,t){return M(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function AE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function RE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function CE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function TE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function IE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function EE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function ME(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function OE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function DE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function jE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function LE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function $E(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function UE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function FE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function NE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function BE(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function KE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function qE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function GE(e,t,n=200){return M(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function WE(e){return M(e,"/kortix/projects")}async function HE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function VE(e,t){return M(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function zE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function YE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function JE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function QE(e,t,n="all"){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function XE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function ZE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function eM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function tM(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function nM(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function rM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function sM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function oM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function iM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function aM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function cM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function lM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var uM=1e4,pM={retryOnAuthError:!1};function en(e,t,n){return M(e,t,{signal:AbortSignal.timeout(uM),...n},pM)}async function dM(e,t=!1){return(await en(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function gM(e){return(await en(e,"/kortix/services/templates")).templates??[]}async function mM(e,t){return(await en(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function fM(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return en(e,s,{method:r?"DELETE":"POST"})}async function yM(e,t){return en(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function hM(e,t){return en(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Ye=new Map,_M=256,tn=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function ut(){let e=ze();if(!e)throw new tn;return Me(e)}function Me(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=Ye.get(e);if(t)return Ye.delete(e),Ye.set(e,t),t;if(!es())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=gr({baseUrl:e,fetch:$,eventTransport:Rb});return Ye.set(e,n),Ye.size>_M&&Ye.delete(Ye.keys().next().value),n}function bM(e){Ye.delete(e)}function SM(){Ye.clear()}var _o=new Map;function xM(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=_o.get(e);if(t)return t;let n=gr({baseUrl:e,fetch});return _o.set(e,n),n}function PM(e){_o.delete(e)}function wM(){_o.clear()}async function kM(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 vM(e){let t=ze();if(!t)throw new P("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await $(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new P(`System reload failed (${r.status}): ${await kM(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new P(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(l){throw new P(`System reload returned malformed JSON from ${n}: ${l instanceof Error?l.message:String(l)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var Db="frontend";function bo(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Db}] ${t}`,...n?[n]:[]);try{ut().app.log({service:Db,level:e,message:t,extra:n})}catch{}}var Je={debug:(e,t)=>bo("debug",e,t),info:(e,t)=>bo("info",e,t),warn:(e,t)=>bo("warn",e,t),error:(e,t)=>bo("error",e,t)};var AM=16,RM=8,jb=6e4,CM=250,TM=1e3,IM=3e4,EM=5,MM=.5,OM=3e3,DM=3e4,Lb=2e4,jM=2e3,$b=8;function LM(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function $M(e,t){if(!e||e.type!==t.type)return;if(t.type==="message.part.delta"){let o=e.properties,i=t.properties;if(o.partID!==i.partID||o.field!==i.field||o.messageID!==i.messageID||o.sessionID!==i.sessionID)return}else if(t.type==="log.block.delta"){let o=e.properties,i=t.properties;if(typeof o.delta!="string"||typeof i.delta!="string"||o.thread_id!==i.thread_id||o.message_id!==i.message_id||o.block_id!==i.block_id)return}else return;let n=e.properties,r=t.properties,s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function Ub(e,t){let n=[],r,s=0,o=new Map,i=()=>{if(r&&e.clearTimeout(r),r=void 0,n.length===0)return;let l=n;n=[],o.clear(),s=e.now();for(let p of l)p&&t(p.event)},a=()=>{if(r)return;let l=e.now()-s;r=e.setTimeout(i,Math.max(0,AM-l))};return{push(l){let p=$M(n[n.length-1]?.event,l);if(p)n[n.length-1]={type:p.type,event:p};else{let d=LM(l);if(d){let g=o.get(d);g!==void 0&&(n[g]=void 0),o.set(d,n.length)}n.push({type:l.type,event:l})}a()},flush:i,clearTimer:()=>{r&&e.clearTimeout(r)}}}function Fb(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)}}function Ym(e,t,...n){for(let r of e){let s=t(r);if(s)try{s(...n)}catch(o){console.warn("[opencode-events] subscriber handler threw, skipping",o)}}}async function UM(e,t,n,r){return new Promise((s,o)=>{let i=!1,a=t.setTimeout(()=>{i||(i=!0,Je.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:n}),r.abort(),o(new Error(`SSE connect timed out after ${n}ms`)))},n);e.global.event({signal:r.signal,sseDefaultRetryDelay:OM,sseMaxRetryDelay:DM,sseMaxRetryAttempts:1}).then(l=>{i||(i=!0,t.clearTimeout(a),s(l))},l=>{i||(i=!0,t.clearTimeout(a),o(l))})})}async function FM(e,t,n,r,s){let o=!1,i=t.now(),a=e[Symbol.asyncIterator]();for(;!n.aborted;){let l=a.next().then(f=>({kind:"next",result:f}),f=>({kind:"error",error:f})),p=Fb(n),d=await Promise.race([l,p.promise.then(()=>({kind:"aborted"}))]);if(p.cleanup(),d.kind==="aborted")break;if(d.kind==="error")throw d.error;if(d.result.done)break;s();let g=d.result.value,m=g&&typeof g=="object"&&"payload"in g?g.payload:g;m?.type&&(m.type!=="server.connected"&&(o=!0),r.push(m),!(t.now()-i<RM)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return o}function Nb(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<jM)}function Bb(e,t,n){Je.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),Ym(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function Kb(e,t,n){let r=t?CM:Math.min(TM*2**Math.min(e-1,EM),IM);return Math.round(r*(1+MM*(n.random?.()??0)))}function qb(e,t,n){return new Promise(r=>{let s=e.setTimeout(r,n),o=()=>{e.clearTimeout(s),r()};t.addEventListener("abort",o,{once:!0})})}async function Gb(e){let{client:t,t:n,connectTimeoutMs:r,heartbeatTimeoutMs:s,outerSignal:o,retryCount:i,setConnectionState:a,onConnected:l,coalescer:p}=e,d=!1,g=!1,m,f=null,h=new AbortController;a("connecting");let S=Fb(o);S.promise.then(()=>h.abort());try{let{stream:v}=await UM(t,n,r,h);l();let T=()=>{n.clearTimeout(m),m=n.setTimeout(()=>{Je.warn("SSE heartbeat timeout, forcing reconnect"),h.abort()},s)};T(),d=await FM(v,n,h.signal,p,()=>{a("open"),T()}),g=d}catch(v){if(f=v,o.aborted)return{streamHadWork:d,stableConnection:g,error:f};let T=String(v),_=jt(v)||jt(v?.cause);if(Je.error("SSE event stream error",{error:T,retryCount:i,isAuthError:_}),_)try{ms(),await gs(),Je.info("SSE: refreshed auth token after auth error")}catch(b){Je.error("SSE: failed to refresh auth token",{error:String(b)})}}finally{n.clearTimeout(m),h.abort(),S.cleanup(),p.flush()}return{streamHadWork:d,stableConnection:g,error:f}}function Wb(e){return{type:"heartbeat-gap",gapMs:e}}function Hb(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 NM={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},BM=5e3,KM=1e4,qM=4,fr=new WeakMap;function GM(e,t,n){let r=t.timers??NM,s=t.connectTimeoutMs??Lb,o=t.heartbeatTimeoutMs??jb,i=t.maxConsecutiveHardFailures??$b,a=new AbortController,l=(v,...T)=>Ym(n,v,...T),p=null,d=!1,g=v=>{p!==v&&(p=v,v&&l(T=>T.onConnectionChange,v))},m=r.now(),f=null,h=Ub(r,v=>{m=r.now(),l(T=>T.onEvent,v)}),S={client:e,t:r,connectTimeoutMs:s,heartbeatTimeoutMs:o,outerSignal:a.signal,setConnectionState:g,onConnected:()=>{if(f){let v=r.now()-f.lastActivityAt,T=f.eventful;f=null,(T||v>BM)&&l(_=>_.onGapRehydrate,v)}m=r.now()},coalescer:h};return(async()=>{let v=0,T=0,_=0;for(;!a.signal.aborted;){let b=r.now(),O=await Gb({...S,retryCount:v});if(a.signal.aborted)break;let y=O.error,{streamHadWork:w,stableConnection:x}=O,k=r.now()-b;if(T=Nb(w,y,k)?T+1:0,T>=i){Bb(n,T,y),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||w},_=x&&k<KM?_+1:0;let R=x&&_<=qM;R?v=0:(v++,v>1&&Je.warn("SSE event stream reconnecting",{retryCount:v})),await qb(r,a.signal,Kb(v,R,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),h.clearTimer()}}}function So(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?Me(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s},l=fr.get(i);if(l?.isParked()&&(fr.delete(i),l=void 0),!l)l=GM(i,e,new Set([a])),fr.set(i,l);else{l.subscribers.add(a);let f=l.connectionState();f&&s?.(f)}let p=l,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),fr.get(i)===p&&fr.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function Vb(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Me(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return Me(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return Me(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return So({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Yb(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 P(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Xm(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 ue(e){let t=(e??ze()).trim();if(!t)throw new tn;return t}async function _r(e,t){let n=await $(`${ue(t)}${e}`);if(!n.ok)throw new P(await Xm(n),{status:n.status,response:n});return n.json()}async function Zm(e,t,n,r,s){let o=await $(`${ue(s)}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new P(`${r} failed (${o.status}): ${await Xm(o)}`,{status:o.status,response:o});return o.json()}var Po=["/workspace","/tmp","/home","/opt"],WM=Po.filter(e=>e!=="/workspace");function ef(e){return Po.some(t=>e===t||e.startsWith(`${t}/`))}function sn(e){return ef(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function pt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(WM.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var tf=pt;async function on(e,t){let n=ue(t),r=pt(e)||".";return(await _r(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function an(e,t){let n=pt(e);return _r(`/file/content?path=${encodeURIComponent(n)}`,t)}async function HM(e,t,n){let r=ue(n),s=pt(e),o=await $(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new P(await Xm(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new P("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var VM=8,xo=0,Jb=[];async function zM(){if(xo<VM){xo++;return}await new Promise(e=>Jb.push(e)),xo++}function YM(){xo--,Jb.shift()?.()}function Qb(e,t){let n=ue(t);return Un(`${n}/file/raw?path=${encodeURIComponent(pt(e))}`)}async function cn(e,t){await zM();try{let n=ue(t);try{return await HM(e,void 0,n)}catch{}let r=await an(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{YM()}}async function br(e){return _r("/file/status",ue(e))}async function Sr(e,t,n){let r=ue(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),_r(`/find/file?${s.toString()}`,r)}async function xr(e,t){let n=ue(t);return(await _r(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var yr=[400,1200],JM=e=>e===408||e===429||e===502||e===503||e===504,zb=e=>new Promise(t=>setTimeout(t,e));function QM(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Jm=3e4,Xb=15*6e4,XM=256;function nn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Jm;let t=Jm+e/XM;return Math.min(Xb,Math.max(Jm,Math.round(t)))}async function ZM(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function hr(e,t){let n;for(let s=0;s<=yr.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,QM(a)||s===yr.length)break;await zb(yr[s]);continue}if(o.ok)return o.json();let i=await ZM(o);if(n=new P(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!JM(o.status)||s===yr.length)throw n;await zb(yr[s])}if(n instanceof P)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new P(`Upload failed: ${r}`)}var Qm=8*1024*1024;function eO(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new P(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Zb(e,t){try{e?.onProgress?.(t)}catch{}}function eS(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function tO(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function ln(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=ue(o),l=nn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Qm){let d=await hr(()=>eS(e,t,p),g=>$(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:l}));return eO(d[0],e.size),Zb(i,{loadedBytes:e.size,totalBytes:e.size}),d}return nO(e,t,p,a,i)}async function nO(e,t,n,r,s){let i=(await hr(()=>eS(new Blob([],{type:e.type}),t,n),l=>$(`${r}/file/upload`,{method:"POST",body:l},{timeoutMs:nn(0)})))[0]?.path;if(!i)throw new P("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=tO(i);if(!a.name)throw new P(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let l=0;l<e.size;l+=Qm){let p=Math.min(e.size,l+Qm),d=e.slice(l,p,e.type),g=await hr(()=>{let m=new FormData;return a.parent&&m.append("path",a.parent),m.append("filename",a.name),m.append("first",l===0?"true":"false"),m.append("offset",String(l)),m.append("file",d,a.name),m},m=>$(`${r}/file/append`,{method:"POST",body:m},{timeoutMs:nn(d.size)}));if(g.path!==i||g.size!==p)throw new P(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Zb(s,{loadedBytes:p,totalBytes:e.size})}}catch(l){throw await Et(i,r).catch(()=>{}),l}return[{path:i,size:e.size}]}function tS(e,t,n){let r=ue(n);return hr(()=>{let s=new FormData;return t&&s.append("path",t),s.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),s},s=>$(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:rO}))}var rO=Xb;function sO(e,t,n){let r=ue(n),s=nn(t.size);return hr(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>$(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var rn=class extends P{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function Pr(e,t){let n=ue(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",l=sn(`${a}/${i}`),p=[];try{p=await on(nS(l),n)}catch(g){if(!(g instanceof P&&g.status===404))throw g}if(p.some(g=>g.name===rS(l)))throw new rn(l);let d=await sS(l,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function wr(e,t,n){let r=ue(n);return sO(t,await cn(e,r),r)}function oO(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function nS(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function rS(e){return e.slice(e.lastIndexOf("/")+1)}function iO(){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 kr(e,t,n){let r=ue(n),s=sn(oO(e.trim()));return sS(s,t,r,{overwrite:!0})}async function sS(e,t,n,r){let s=rS(e);if(!s)throw new P(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=nS(e);await un(o,n).catch(()=>{});let i=iO(),a=await ln(t,o,`.${s}.kortix-write-${i}`,n),l=a[0]?.path;if(!l)throw new P(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=sn(l);try{await oS(p,e,n,r.overwrite)}catch(g){throw await Et(p,n).catch(()=>{}),!r.overwrite&&g instanceof P&&g.status===409?new rn(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Et(e,t){return Zm("/file","DELETE",{path:e},"Delete",t)}async function un(e,t){return Zm("/file/mkdir","POST",{path:e},"Mkdir",t)}async function vr(e,t,n){return oS(e,t,ue(n),!0)}async function oS(e,t,n,r){return Zm("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function nf(){return Yb(await ut().project.current())}async function wo(){return Yb(await ut().global.health())}async function rf(){try{return(await wo()).healthy===!0}catch{return!1}}var iS={list:on,read:an,readBlob:cn,status:br,findFiles:Sr,findText:xr,upload:ln,write:kr,create:Pr,copy:wr,remove:Et,mkdir:un,rename:vr,currentProject:nf,health:wo,isReachable:rf,toDaemonPath:pt,toSandboxAbsolutePath:sn,toWorkspaceRelative:tf};function aS(e){return{list:async t=>on(t,(await e()).runtimeUrl),read:async t=>an(t,(await e()).runtimeUrl),readBlob:async t=>cn(t,(await e()).runtimeUrl),status:async()=>br((await e()).runtimeUrl),findFiles:async(t,n)=>Sr(t,n,(await e()).runtimeUrl),findText:async t=>xr(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>ln(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>kr(t,n,(await e()).runtimeUrl),create:async t=>Pr(t,(await e()).runtimeUrl),copy:async(t,n)=>wr(t,n,(await e()).runtimeUrl),remove:async t=>Et(t,(await e()).runtimeUrl),mkdir:async t=>un(t,(await e()).runtimeUrl),rename:async(t,n)=>vr(t,n,(await e()).runtimeUrl)}}function cS(e){return{get:t=>Wn(e.projectId,e.sessionId,t),presence:(t,n)=>c.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>Zn(e.sessionId,{projectId:e.projectId}),update:t=>ru(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),su(e.projectId,e.sessionId)),restore:()=>iu(e.projectId,e.sessionId),recover:()=>ou(e.projectId,e.sessionId),start:(...t)=>nt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Cu(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Yn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Jn(e.projectId,e.sessionId)),configState:()=>au(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),cu(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),lu(e.projectId,e.sessionId,...t)),setSharing:t=>Ll(e.projectId,e.sessionId,t),previews:()=>Kl(e.projectId,e.sessionId),participants:()=>$l(e.projectId,e.sessionId),watch:()=>Ul(e.projectId,e.sessionId),setWatch:t=>Fl(e.projectId,e.sessionId,t),setPinned:t=>Nl(e.projectId,e.sessionId,t),setArchived:t=>Bl(e.projectId,e.sessionId,t),commit:t=>Cl(e.projectId,e.sessionId,t),publicShares:{list:()=>ql(e.projectId,e.sessionId),create:(...t)=>Gl(e.projectId,e.sessionId,...t),revoke:(...t)=>Wl(e.projectId,e.sessionId,...t)}}}function lS(e){return{reminders:{list:()=>Td(e.projectId,e.sessionId),create:t=>Id(e.projectId,e.sessionId,t),update:(t,n)=>Ls(e.projectId,e.sessionId,t,n),remove:t=>$s(e.projectId,e.sessionId,t),run:t=>Ed(e.projectId,e.sessionId,t)},audit:(t,n)=>zl(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Tm(e.projectId,e.sessionId,t,n),read:(t,n)=>Im(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Yl(e.projectId,e.sessionId,t),messageAuthors:()=>gu(e.projectId,e.sessionId),modelUsage:()=>mu(e.projectId,e.sessionId),transcriptSync:t=>Hn(e.projectId,e.sessionId,t),log:t=>Jl(e.projectId,e.sessionId,t),turn:()=>Vn(e.projectId,e.sessionId),prompts:{create:t=>zn(e.projectId,e.sessionId,t),list:()=>Ql(e.projectId,e.sessionId),remove:t=>Xl(e.projectId,e.sessionId,t),retry:t=>tu(e.projectId,e.sessionId,t),edit:(t,n)=>Zl(e.projectId,e.sessionId,t,n),interrupt:t=>eu(e.projectId,e.sessionId,t),hold:t=>nu(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function uS(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var cO=["control_plane","provider_ingress","daemon","upstream_port"];function sf(e){return typeof e=="string"&&cO.includes(e)?e:null}function of(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 af(e,t){let n=(e===void 0?ze():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await $(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let i=o,a=sf(r.headers.get("X-Kortix-Proxy-Hop"))??sf(o?.hop),l=Number(r.headers.get("X-Kortix-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(l)&&l>0?l:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var pS=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,dS=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,gS=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,mS=new Set([22,4096,parseInt(Ke.KORTIX_MASTER,10)]);function lO(e){return dS.test(e)}function ko(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 uO(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var pO=new Set(["'",'"',"`","<","(","["]),dO=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function gO(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&&pO.has(e[t]);)t++;for(;n>t&&dO.has(e[n-1]);)n--;return e.slice(t,n)}function mO(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var fO=/^\/proxy\/(\d{1,5})(\/.*)?$/,yO=/^\/(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 fS(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:yO.test(t.pathname)}catch{return!1}}function Rr(e){if(!e)return null;let t=gO(uO(e.trim())),n=lf(t);if(n){let r=ko(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(Ke.KORTIX_MASTER,10);if(s===i){let l=r.pathname.match(fO);if(l){let p=parseInt(l[1],10);if(p>=1&&p<=65535)return s=p,o=ko(`${l[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=ko(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=mO(e);return r&&r!==e?Rr(r):null}}function hO(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,i=o+r[0].length;t.some(([l,p])=>o>=l&&i<=p)||t.push([o,i])}return t}function _O(e,t){return t.some(([n,r])=>e>=n&&e<r)}function yS(e){let t=[],n=new Set,r=hO(e);pS.lastIndex=0;let s;for(;(s=pS.exec(e))!==null;){let o=Rr(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:l}=o;a<1||a>65535||mS.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:l,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:_O(s.index,r)}))}return t}function bO(e){return yS(e).length>0}function SO(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function hS(e){return e.trim().toLowerCase().split("_").join("-")}function _S(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function xO(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let s=r.split("{port}").join(String(e)).split("{sandbox}").join(hS(n.sandboxId));return`${_S(s)}${t}`}function bS(e){return e.sandboxId.trim().length>0}function dt(e,t,n){let r=ko(t);if(!bS(n))return wS(e,r);let s=xO(e,r,n);return s||(SO(n.apiBaseUrl)?`http://p${e}-${hS(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${_S(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function PO(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return dt(3211,`/open?path=/workspace/${r}`,t)}function SS(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function wO(e){return`http://localhost:3211${SS(e)}`}function xS(){return"/health"}function kO(e){return dt(3211,xS(),e)}function vO(e,t){return dt(e,"/",t)}function PS(e){let t=Rr(e);return!(!t||mS.has(t.port)||fS(e))}function cf(e,t){if(!e)return e;let n=Rr(e);return n?PS(n.originalUrl)?dt(n.port,n.path,t):n.originalUrl:e}function wS(e,t="/"){return`http://localhost:${e}${t}`}var kS=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function lf(e){let t=e.match(dS);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(gS);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(kS);if(r)try{let s=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(s.port,10)||(s.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function AO(e){try{let t=lf(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function RO(e){return lO(e)||gS.test(e)||kS.test(e)}function CO(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Ar="/web-proxy/";function TO(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Ar}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(Ke.KORTIX_MASTER,10);return`${dt(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function IO(e){try{let t=new URL(e),n=t.pathname.indexOf(Ar);if(n===-1)return null;let s=t.pathname.slice(n+Ar.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],i=s[2],a=s[3]||"/";return`${o}://${i}${a}${t.search}${t.hash}`}catch{return null}}function EO(e){try{return new URL(e).pathname.includes(Ar)}catch{return e.includes(Ar)}}function MO(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 OO(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 vS(e){return{health:t=>af(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>dt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>cf(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ie(e.requireReady("sandboxPortUrl").sandboxId,t)}}function uf(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=ub(e,t),{ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g}=mb(e,t,n),m={projectId:e,sessionId:t,ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return s},set model(f){s=f},get agent(){return o},set agent(f){o=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...cS(m),...lS(m),...vS(m),...bb(m),...Ab(m),...Vb(m),files:aS(l),..._b(m),get runtime(){return Me(d("runtime").runtimeUrl)}}}function AS(e){return{apps:{list:()=>Sg(e),create:t=>xg(e,t),get:t=>Us(e,t),update:(...t)=>Pg(e,...t),access:{get:(...t)=>Ag(e,...t),update:(...t)=>Cg(e,...t),session:(...t)=>Tg(e,...t),agents:t=>Rg(e,t)},remove:t=>wg(e,t),token:t=>kg(e,t),authEnv:t=>vg(e,t),artifacts:{register:t=>Fs(e,t),uploadArchive:(...t)=>Ig(e,...t),finalize:(...t)=>Ns(e,...t)},deployments:{create:(...t)=>Eg(e,...t),list:t=>Mg(e,t),get:(...t)=>Og(e,...t),logs:(...t)=>Dg(e,...t),remove:(...t)=>$g(e,...t)},start:t=>jg(e,t),stop:t=>Lg(e,t),rollback:(...t)=>Ug(e,...t),machines:{list:t=>Fg(e,t),start:(t,n)=>Bg(e,t,n),stop:(t,n)=>Kg(e,t,n),restart:(t,n)=>qg(e,t,n),destroy:(t,n)=>Gg(e,t,n)},scale:(...t)=>Wg(e,...t),exec:(...t)=>Hg(e,...t),volumes:{list:t=>Vg(e,t),create:(...t)=>zg(e,...t),update:(...t)=>Yg(e,...t),destroy:(...t)=>Jg(e,...t),snapshots:(...t)=>Qg(e,...t),snapshot:(...t)=>Xg(e,...t),restore:(...t)=>Zg(e,...t),fork:(...t)=>em(e,...t)}}}}function RS(e){return{list:()=>Ra(e),invite:(...t)=>Ia(e,...t),update:(...t)=>Ca(e,...t),revoke:t=>Ta(e,t),pendingInvites:()=>Ea(e),resendInvite:(...t)=>Oa(e,...t),revokeInvite:(...t)=>Ma(e,...t),requests:()=>ka(e),approveRequest:(...t)=>va(e,...t),rejectRequest:(...t)=>Aa(e,...t),groupGrants:()=>Da(e),attachGroupGrant:(...t)=>ja(e,...t),updateGroupGrant:(...t)=>La(e,...t),detachGroupGrant:t=>$a(e,t),resourceGrants:{list:()=>Ua(e),create:t=>Fa(e,t),remove:t=>Na(e,t)}}}function CS(e){return{tokens:{list:()=>Zd(e),create:t=>eg(e,t),revoke:t=>tg(e,t)},setupLinks:{requestSecret:t=>ug(e,t),requestConnector:t=>pg(e,t)},validateManifest:t=>ea(e,t),gitToken:()=>ta(e),agentIdentities:()=>td(e),secrets:{list:()=>Ga(e),upsert:t=>Wa(e,t),setStrategy:(...t)=>Ha(e,...t),broker:(...t)=>Va(e,...t),remove:t=>jn(e,t),setPersonal:(...t)=>Qa(e,...t),removePersonal:t=>Xa(e,t),setGitCredential:t=>Ja(e,t),listProviderOAuth:()=>za(e),startProviderOAuth:(...t)=>ps(e,...t),pollProviderOAuth:(...t)=>ds(e,...t),removeProviderOAuth:t=>Ya(e,t)},access:RS(e)}}function TS(e){return{list:()=>dc(e),listAll:()=>gc(e),reconcile:(...t)=>mc(e,...t),reconcileMember:(...t)=>fc(e,...t),updateCredential:(...t)=>yc(e,...t),revoke:(...t)=>hc(e,...t),activate:(...t)=>_c(e,...t),setDefault:(...t)=>bc(e,...t),rename:(...t)=>Sc(e,...t),share:(...t)=>Pc(e,...t),addComputer:(...t)=>xc(e,...t),pipedreamConnect:(...t)=>wc(e,...t),pipedreamFinalize:(...t)=>kc(e,...t)}}function vo(e){return{catalog:t=>Nt(e,t),tools:()=>ys(e),search:(...t)=>pc(e,...t),describe:(...t)=>hs(e,...t),call:(...t)=>kt(e,...t),callAction:(t,n,r,s)=>kt(e,`${t}.${n}`,r,s),accounts:(...t)=>_s(e,...t),uploadAttachment:(...t)=>bs(e,...t)}}function pf(e,t){return{slug:t,run:(r,s,o)=>ks(e,t,r,s,o),call:(r,s,o)=>kt(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?hs(e,`${t}.${r}`):(await Nt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>_s(e,t),paginate:(r,s,o)=>Vc(e,t,r,s,o),uploadAttachment:(r,s)=>bs(e,r,{...s,connector:t})}}var DO=100,IS=0,jO=new Set(["attachment_size_mismatch","attachment_failed"]),ES=()=>new P("Attachment expired. Attach the file again.",{code:"attachment_expired"});function df(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 LO(e,t,n){let r,s=0,o,i=()=>{o=void 0,!(!t()||e.item.status!=="uploading"||r===void 0)&&(e.item={...e.item,receivedBytes:r},r=void 0,s=Date.now(),n())},a=p=>Math.floor(p*100/e.item.size),l=()=>{o&&clearTimeout(o),o=void 0};return{onProgress:p=>{if(!t()||a(p)===a(e.item.receivedBytes)||(r=p,o))return;let d=s+DO-Date.now();if(d<=0)return i();o=setTimeout(i,d),typeof o=="object"&&"unref"in o&&o.unref()},onProcessing:()=>{l(),r=void 0,t()&&(e.item={...e.item,status:"processing",receivedBytes:e.item.size},n())},clear:l}}function gf(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,i=0,a=!1,l,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,w){y.removalDeleted||(y.removalDeleted=!0,Bt(e,w).catch(()=>{}))}function m(){l&&clearTimeout(l);let y=d().map(({item:x})=>x);(y.length!==p.attachments.length||y.some((x,k)=>x!==p.attachments[k]))&&(p={attachments:y});let w=Math.min(...y.filter(x=>x.status==="ready").map(x=>Date.parse(x.attachment.expires_at)));Number.isFinite(w)&&!a&&(l=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:ES()});m()},Math.min(2147483647,Math.max(0,w-Date.now()))),typeof l=="object"&&"unref"in l&&l.unref());for(let x of s)x();for(let x of[...o])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 w=d();if(w.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(k=>!Number.isSafeInteger(k)||k<=0||k>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(w.reduce((k,C)=>k+C.item.size,0)+y.reduce((k,C)=>k+C,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function S(y,w,x){let k=++y.generation,C=new AbortController;y.abort=C,y.item={...y.item,status:"uploading",error:void 0};let j=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===k,R=LO(y,j,m);Bn(e,w,{resume:y.upload,signal:C.signal,onUpload:L=>{y.upload=L,y.removed&&(C.abort(),g(y,L.attachment_id))},...R}).then(L=>{j()&&(y.item={...y.item,status:"ready",attachment:df(L),receivedBytes:L.size})}).catch(L=>{L instanceof P&&jO.has(L.code??"")&&(y.upload=void 0),j()&&(y.item={...y.item,status:L instanceof P&&L.code==="ABORTED"?"aborted":"error",error:L instanceof Error?L:new Error(String(L))})}).finally(()=>{R.clear(),y.abort===C&&(y.abort=void 0),x()})}function v(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let w=y.item.file;i++,S(y,w,()=>{i--,m(),v()})}m()}function T(y){h(y.map(x=>x.size));let w=y.map(x=>{let k=`attachment-${++IS}`;return r.set(k,{generation:0,item:{id:k,file:x,filename:x.name,mime:x.type||"application/octet-stream",size:x.size,status:"pending",receivedBytes:0}}),k});return m(),v(),w}function _(y){let w=y.map(({attachment:k,file:C})=>{try{return{attachment:df(k),file:C}}catch{return}});h(w.flatMap(k=>k?[k.attachment.size]:[]));let x=w.map(k=>{if(!k)return;let C=`attachment-${++IS}`,{attachment:j,file:R}=k;return r.set(C,{generation:0,item:{id:C,...R?{file:R}:{},filename:j.filename,mime:j.mime,size:j.size,status:"ready",receivedBytes:j.size,attachment:j}}),C});return m(),x}function b(y){let w=r.get(y);!w||w.item.status==="ready"||(w.generation++,w.abort?.abort(),w.item={...w.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function O(y,{signal:w}={}){let x=[...y];return new Promise((k,C)=>{let j=()=>{o.delete(pe),w?.removeEventListener("abort",L)},R=D=>{j(),C(D)},L=()=>R(Ae()),pe=()=>{let D=!1;for(let W of x){let K=r.get(W);if(!K)return R(new Error("Attachment was removed before it was sent"));if(a&&!K.handedOff)return R(new Error("Attachment controller is disposed"));if(K.item.status==="error"||K.item.status==="aborted")return R(K.item.error??new Error("Attachment upload failed"));K.item.status!=="ready"&&(D=!0)}if(D)return;let q;try{q=x.map(W=>{let K=df(r.get(W).item.attachment);return{type:"file",attachment_id:K.attachment_id,filename:K.filename,mime:K.mime}})}catch(W){return R(W instanceof Error?W:new Error(String(W)))}j(),k(q)};if(w?.aborted)return L();o.add(pe),w?.addEventListener("abort",L,{once:!0}),pe()})}return{add:y=>T([y])[0],addMany:T,restore:_,retry(y){let w=r.get(y);if(w?.handedOff||f(),!(!w||w.item.status==="ready"||w.item.status==="uploading"||w.item.status==="processing"||w.item.status==="pending")){if(!w.item.file||w.upload&&Date.parse(w.upload.expires_at)<=Date.now())throw ES();w.item={...w.item,status:"pending",error:void 0},v()}},async remove(y){let w=r.get(y);if(!w)return;w.removed=!0,w.generation++,r.delete(y);let x=w.upload?.attachment_id??w.item.attachment?.attachment_id;x&&w.abort?.abort(),m(),v(),x&&g(w,x)},abort:b,submit(y){if(!a){for(let w of y){let x=r.get(w);x&&(x.handedOff=!0)}m()}},reclaim(y){if(!a){for(let w of y){let x=r.get(w);x&&(x.handedOff=!1)}m()}},whenReady:O,forget(y=d().map(w=>w.item.id)){for(let w of y){let x=r.get(w);x&&(x.generation++,x.abort?.abort(),r.delete(w))}m(),v()},dispose(){if(!a){a=!0,l&&clearTimeout(l);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let w=y.upload?.attachment_id??y.item.attachment?.attachment_id;w&&e&&Bt(e,w).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(y){return s.add(y),()=>{s.delete(y)}}}}function MS(e){return{attachments:{upload:(...t)=>Bn(e,...t),delete:(...t)=>Bt(e,...t),createController:t=>gf(e,t)},get:t=>wt(e,t),detail:()=>In(e),skills:{remove:(...t)=>ua(e,...t),create:(...t)=>la(e,...t)},audit:t=>sg(e,t),update:t=>On(e,t),archive:()=>Dn(e),llmCatalog:()=>En(e),modelPicker:()=>Mn(e),modelAccess:()=>nr(e),setModelAccess:t=>rr(e,t),customLlmProviders:()=>sr(e),setCustomLlmProvider:(t,n)=>or(e,t,n),deleteCustomLlmProvider:t=>ir(e,t),sandboxHealth:()=>$n(e),onboardingComplete:(...t)=>ca(e,...t)}}function OS(e){return{sessions:{list:t=>At(e,t),listPage:t=>jl(e,t),create:t=>Rt(e,t),ensureWarm:()=>Hl(e),claimWarm:t=>Vl(e,t)},review:{list:t=>Sd(e,t),summary:()=>xd(e),get:t=>Pd(e,t),submit:t=>wd(e,t),act:(...t)=>kd(e,...t),bulkAct:t=>vd(e,t)},approvals:{list:t=>Ba(e,t),resolve:(...t)=>qa(e,...t),sessionsNeedingInput:t=>Ka(e,t)}}}function DS(e){return{files:{list:t=>ol(e,t),listDirectory:t=>il(e,t),read:(t,n)=>cl(e,t,n),search:(...t)=>al(e,...t),archive:(...t)=>ll(e,...t),archiveRequest:(...t)=>ul(e,...t),history:(...t)=>hl(e,...t)},git:{commits:()=>ml(e),commit:t=>fl(e,t),commitDiff:t=>yl(e,t),branches:()=>gl(e),versionDiff:(...t)=>_l(e,...t),inviteCollaborator:(...t)=>Zi(e,...t)},changeRequests:{list:(...t)=>bl(e,...t),get:t=>Sl(e,t),update:(...t)=>Tl(e,...t),diff:t=>xl(e,t),mergePreview:t=>Pl(e,t),open:(...t)=>wl(e,...t),merge:(...t)=>kl(e,...t),close:(...t)=>vl(e,...t),reopen:(...t)=>Al(e,...t),requestChanges:(...t)=>Rl(e,...t)},...OS(e)}}function jS(e){return{policies:{list:()=>zc(e),set:(...t)=>Yc(e,...t)},reminders:{list:()=>Dd(e),updateMany:(...t)=>Md(e,...t),removeMany:(...t)=>Od(e,...t)},rooms:{list:(...t)=>Ld(e,...t),create:(...t)=>$d(e,...t),get:(...t)=>Ud(e,...t),update:(...t)=>Fd(e,...t),messages:(...t)=>Nd(e,...t),post:(...t)=>Bd(e,...t),markRead:(...t)=>Kd(e,...t),addSession:(...t)=>qd(e,...t),removeSession:(...t)=>Gd(e,...t),addPerson:(...t)=>Wd(e,...t),removePerson:(...t)=>Hd(e,...t),people:(...t)=>Vd(e,...t)},triggers:{list:()=>fu(e),eventApps:()=>vu(e),eventTypes:(...t)=>ku(e,...t),create:(...t)=>yu(e,...t),update:(...t)=>hu(e,...t),remove:(...t)=>_u(e,...t),fire:((t,n)=>Su(e,t,n)),runs:(...t)=>xu(e,...t),projectRuns:(...t)=>Pu(e,...t),replay:(...t)=>wu(e,...t),setActivation:(...t)=>bu(e,...t)},...DS(e)}}function LS(e,t){return{connectors:{...vo(e),list:()=>vc(e),config:(...n)=>Mc(e,...n),create:(...n)=>jc(e,...n),remove:(...n)=>Fc(e,...n),sync:()=>Ac(e),auth:{discover:(...n)=>Lc(e,...n)},setName:(...n)=>Oc(e,...n),setCredentialMode:(...n)=>Rc(e,...n),setAuthorizationStrategy:(...n)=>Cc(e,...n),setCredential:(...n)=>Gc(e,...n),deleteCredential:(...n)=>Wc(e,...n),setSensitive:(...n)=>Tc(e,...n),connections:t,policies:{get:(...n)=>Ic(e,...n),set:(...n)=>Ec(e,...n)},listMoves:()=>$c(e),move:(...n)=>Uc(e,...n),pipedream:{listApps:(...n)=>Nc(e,...n),listSections:(...n)=>Bc(e,...n),connect:(...n)=>Dc(e,...n),finalize:(...n)=>Hc(e,...n)},discover:{list:(...n)=>Ss(e,...n),sections:(...n)=>Kc(e,...n),detail:(...n)=>xs(e,...n)}},...jS(e)}}function $S(e){return{gateway:{logs:t=>Rp(e,t),log:t=>Cp(e,t),overview:t=>Tp(e,t),series:t=>Ip(e,t),breakdown:t=>Ep(e,t),sessions:t=>Mp(e,t),errors:t=>Op(e,t),budgets:()=>Dp(e),setBudget:t=>jp(e,t),deleteBudget:t=>Lp(e,t),keys:()=>$p(e),createKey:t=>Up(e,t),revokeKey:t=>Fp(e,t),routing:{get:()=>wp(e),set:t=>kp(e,t),reset:()=>vp(e),preview:t=>Ap(e,t)},playground:(t,n,r)=>Np(e,t,n,r)}}}function US(e){return{modelDefaults:{get:()=>Tu(e),set:t=>Iu(e,t),clear:t=>Eu(e,t)},setDefaultAgent:t=>Du(e,t),sandbox:{list:()=>sl(e),snapshots:()=>Qc(e),rebuildSnapshot:t=>Xc(e,t),fixWithAgent:()=>Zc(e),createTemplate:t=>el(e,t),updateTemplate:(...t)=>tl(e,...t),removeTemplate:t=>nl(e,t),buildTemplate:t=>rl(e,t),setProvider:t=>aa(e,t)},setAgentScope:(...t)=>Mu(e,...t)}}function FS(e){return{channels:{slack:{installation:()=>cp(e),connect:t=>lp(e,t),mode:()=>up(e),completeInstall:t=>pp(e,t),manifest:()=>gp(e),disconnect:()=>mp(e),getFile:t=>fp(e,t),uploadFile:t=>yp(e,t)},teams:{completeInstall:t=>dp(e,t)},email:{installation:t=>_p(e,t),mode:()=>bp(e),connect:t=>Sp(e,t),disconnect:t=>xp(e,t),updatePolicy:(...t)=>Pp(e,...t)}},updateFeatureFlag:(...t)=>oa(e,...t),updateExperimentalFeature:(...t)=>ia(e,...t),...US(e)}}var $O=["screen","actions","audio"],UO=["password_managers","messaging","banking"],FO={localHours:8760,remoteDays:3650},NO=[500,1e3,2e3,5e3,1e4],BO=[720,1080,1440,2160],KO={intervalMs:2e3,maxHeight:1440},qO=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function GO(e){let t=e.trim().toLowerCase();if(!t)return null;let n;try{n=new URL(t.includes("://")?t:`https://${t}`).hostname}catch{return null}return n=n.replace(/^www\./,"").replace(/\.$/,""),qO.test(n)?n:null}function WO(e){let t=e.trim();return!t||t.length>255||t.startsWith("-")||/[\u0000-\u001f\u007f]/.test(t)||t.endsWith("*")&&t.slice(0,-1).trim().length<3?null:t}function HO(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var Y=e=>`/accounts/${e}/capture`;function Qe(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}var NS=e=>Qe({q:e.q,kinds:e.kinds?.join(","),app:e.app,limit:e.limit,day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,scope:e.scope}),mf=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function ff(e,t={}){return u(await c.get(`${Y(e)}/devices${Qe({user_id:t.userId,scope:t.scope})}`))}async function yf(e,t){return u(await c.delete(`${Y(e)}/devices/${t}`))}async function hf(e,t,n){return u(await c.put(`${Y(e)}/devices/${t}/link`,{user_id:n}))}async function _f(e){return u(await c.get(`${Y(e)}/enrollment-tokens`))}async function bf(e,t){return u(await c.post(`${Y(e)}/enrollment-tokens`,t))}async function Sf(e,t){return u(await c.delete(`${Y(e)}/enrollment-tokens/${t}`))}async function xf(e,t={}){return u(await c.get(`${Y(e)}/enrollments${Qe({status:t.status})}`))}async function Pf(e,t,n){return u(await c.post(`${Y(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function wf(e,t){return u(await c.post(`${Y(e)}/enrollments/${t}/deny`,{}))}async function kf(e){return u(await c.get(`${Y(e)}/policy`))}async function vf(e,t){return u(await c.put(`${Y(e)}/policy`,{policy:t}))}async function Af(e){return u(await c.get(`${Y(e)}/storage`))}async function Rf(e,t){return u(await c.put(`${Y(e)}/storage`,t))}async function Cf(e,t={}){return u(await c.get(`${Y(e)}/timeline${Qe(mf(t))}`))}async function Tf(e,t={}){return u(await c.get(`${Y(e)}/timeline/items${Qe(mf(t))}`))}async function If(e,t={}){return u(await c.get(`${Y(e)}/days${Qe({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function Ef(e,t){return u(await c.get(`${Y(e)}/search${NS(t)}`))}async function Mf(e,t,n={}){return u(await c.get(`${Y(e)}/frames/${t}${Qe({user_id:n.userId,device_id:n.deviceId})}`))}async function Of(e,t,n={}){return u(await c.get(`${Y(e)}/chunks/${t}/media${Qe({user_id:n.userId,device_id:n.deviceId})}`))}async function Df(e,t,n){return u(await c.get(`${Y(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function jf(e){return u(await c.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function Lf(e,t){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function $f(e){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function Uf(e){return u(await c.get(Y(e)))}async function Ff(e,t){return u(await c.patch(Y(e),{enabled:t}))}async function Nf(e){return u(await c.get(`/capture/me/search${NS(e)}`))}async function Bf(e={}){return u(await c.get(`/capture/me/timeline${Qe(mf(e))}`))}async function Kf(e){return u(await c.get(`/capture/me/frames/${e}`))}function zO(e){return{workspace:{get:()=>Uf(e),setEnabled:t=>Ff(e,t)},devices:{list:t=>ff(e,t),revoke:t=>yf(e,t),link:(t,n)=>hf(e,t,n),assetUrl:(t,n)=>Df(e,t,n)},enrollment:{tokens:{list:()=>_f(e),create:t=>bf(e,t),revoke:t=>Sf(e,t)},list:t=>xf(e,t),approve:(t,n)=>Pf(e,t,n),deny:t=>wf(e,t)},policy:{get:()=>kf(e),set:t=>vf(e,t)},storage:{get:()=>Af(e),set:t=>Rf(e,t)},timeline:{get:t=>Cf(e,t),items:t=>Tf(e,t),days:t=>If(e,t)},search:t=>Ef(e,t),frame:(t,n)=>Mf(e,t,n),media:(t,n)=>Of(e,t,n)}}var BS={account:e=>zO(e),deviceGrant:jf,approveDevice:Lf,denyDevice:$f,me:{search:Nf,timeline:Bf,frame:Kf}};async function qf(e){let t=e?.fetch??I().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??I().backendUrl,r=await t(`${qe(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new P(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var YO=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function JO(e,t){let n=o=>{let i=YO.exec(o.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),s=n(t);if(!r||!s)return null;for(let o=0;o<3;o++)if(r[o]!==s[o])return r[o]<s[o]?-1:1;return 0}function QO(){return ut()}var KS=null,qS=!1;function XO(e){let t=KS;KS=e,!(qS||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(qS=!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 GS(e,t){t?.global!==!1&&XO(e),Zr(e,t);let n=lb(e),{auth:r,accounts:s,iam:o,accountInvites:i}=sb(),{billing:a,sandboxShares:l}=tb(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=eb();function h(S){let v=TS(S);return{...MS(S),...AS(S),...CS(S),...LS(S,v),...$S(S),...FS(S),connector:T=>pf(S,T),session:T=>uf(S,T,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:vo(),connector:S=>pf(void 0,S),project:h,session:(S,v)=>uf(S,v,e,n),github:d,gitBackend:g,billing:a,sandboxShares:l,connectStatus:m,marketplace:f,capture:BS,notifications:{registerDeviceToken:sm,unregisterDeviceToken:om,releaseDeviceToken:im,list:am,markRead:cm,preferences:lm,updatePreferences:um,webPushPublicKey:pm,registerWebPushSubscription:dm,unregisterWebPushSubscription:gm},mobileClientPolicy:qf,validateToken:Qi,runtime:QO}}function WS(){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 HS(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function pn(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function VS(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function zS(e){if(pn(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 YS(e){let t=pn(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function JS(e,t){let n=pn(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function QS(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function XS(e,t){return pn(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 ZS(e,t,n){return pn(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 ex(e,t,n){let r=pn(e);if(r.includes(t))return e;let s=e.pending.findIndex(p=>p.id===t);if(s===-1)return e;let o=r.length,i=Math.min(Math.max(n,o),e.pending.length-1);if(i===s)return e;let a=[...e.pending],[l]=a.splice(s,1);return a.splice(i,0,l),{...e,pending:a}}var Gf={thinking:!1,toolDetails:!0,assistantMetadata:!0};function ZO(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function eD(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 tD(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
22
22
|
|
|
23
23
|
`;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
|
|
24
24
|
>
|
|
@@ -51,15 +51,15 @@ ${s}
|
|
|
51
51
|
${e.state.error}
|
|
52
52
|
\`\`\`
|
|
53
53
|
`),n+=`
|
|
54
|
-
`,n}return""}function
|
|
54
|
+
`,n}return""}function nD(e,t){if(!t)return`## Assistant
|
|
55
55
|
|
|
56
|
-
`;let n=e.agent?
|
|
56
|
+
`;let n=e.agent?ZO(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=eD(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
|
|
57
57
|
|
|
58
58
|
`:`## ${n}
|
|
59
59
|
|
|
60
|
-
`}function
|
|
60
|
+
`}function rD(e,t,n){let r="";e.role==="user"?r+=`## User
|
|
61
61
|
|
|
62
|
-
`:r+=
|
|
62
|
+
`:r+=nD(e,n.assistantMetadata);for(let s of t)r+=tD(s,n);return r}function tx(e,t,n=Gf){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,32 +67,32 @@ ${e.state.error}
|
|
|
67
67
|
|
|
68
68
|
`,r+=`---
|
|
69
69
|
|
|
70
|
-
`;for(let s of t)r+=
|
|
70
|
+
`;for(let s of t)r+=rD(s.info,s.parts,n),r+=`---
|
|
71
71
|
|
|
72
|
-
`;return r}function
|
|
72
|
+
`;return r}function nx(e,t){return`session-${e}.md`}var Wf="An error occurred";var sD=["message","error","detail","error_description","msg","errors","data"];function Hf(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 dn(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function oD(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=dn(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function iD(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=aD(e,t);if(n)return n;let r=lD(e,t);return r?r.slice(0,200):void 0}function ix(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function rx(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function aD(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!ix(t.charCodeAt(s))){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return;let i=e.indexOf("<",o+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(o+1,i).trim();if(a)return a}n=o+1}}var cD=["script","style"];function lD(e,t){let n=[],r=0;for(;r<e.length;){let s=e.indexOf("<",r);if(s===-1){n.push(e.slice(r));break}n.push(e.slice(r,s));let o=cD.find(i=>t.startsWith(`<${i}`,s)&&ix(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:rx(e,i);continue}r=rx(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function uD(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 pD(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function sx(e,t,n){if(typeof e=="string")return Ao(e,t,n);if(e&&typeof e=="object")return Ro(e,t,n)}function Ao(e,t,n=new WeakSet){let r=Hf(e);if(!r)return;if(t>=4)return r;let s=uD(r);if(s)return s;let o=dn(r);if(o!==void 0)return typeof o=="string"?Ao(o,t+1,n):o&&typeof o=="object"?Ro(o,t+1,n):String(o);let i=ax(r);if(i){let a=dn(i);if(a&&typeof a=="object"){let l=Ro(a,t+1,n);if(l)return l}}if(r.includes("{")){let a=oD(r);if(a)return Ao(a,t+1,n)??a}return iD(r)??r}function Ro(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=sx(i,t,n);if(a)return a}return}let r=e;for(let i of sD){let a=sx(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return pD(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function ye(e){return e?typeof e=="string"?Ao(e,0)??Wf:typeof e=="object"?Ro(e,0)??Wf:String(e):Wf}function Cr(e){let t=dD(e)?.trim();if(!t)return;let n=ye(e);if(!(t===n||Hf(t)===n))return t}function dD(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:s}=n,o=[r,s].filter((i,a,l)=>typeof i=="string"&&i.trim()!==""&&l.indexOf(i)===a);if(o.length>0)return o.join(`
|
|
73
73
|
|
|
74
|
-
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function
|
|
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 ax(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function gD(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 mD(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 ox(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,s=typeof e.upstream_status=="number"?e.upstream_status:void 0,o=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=mD(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,l=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&s===void 0&&!o&&!i?void 0:{message:typeof e.message=="string"&&e.message||gD(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:i,...a?{requestedModel:a}:{},...l?{resolvedModel:l}:{}}}function Se(e){if(e==null)return;if(typeof e=="string"){let a=Hf(e),l=dn(a)??dn(ax(a));return l!==void 0?Se(l):void 0}if(typeof e!="object")return;let t=e,n=ox(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let s=t.error;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=ox(s);if(a)return a}let o=t.data;if(o&&typeof o.responseBody=="string"){let a=dn(o.responseBody);if(a!==void 0){let l=Se(a);if(l)return l}}if(o&&typeof o.message=="string"){let a=Se(o.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let l=Se(a);if(l)return l}}return n}var cx={};function V(e,t){for(let n of t)cx[n]=e}V("read",["read"]);V("list",["list","ls"]);V("glob",["glob"]);V("grep",["grep"]);V("write",["write"]);V("edit",["edit","multiedit","morph_edit","MultiEdit","NotebookEdit"]);V("apply_patch",["apply_patch","patch"]);V("bash",["bash"]);V("script",["codemode"]);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 fD=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ae(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=cx[t];if(n)return n;for(let[r,s]of fD)if(t.startsWith(r))return s;return"other"}function ve(e){for(let t of[e?.filePath,e?.file_path,e?.path,e?.notebook_path])if(typeof t=="string"&&t)return t}var yD=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function hD(){return new RegExp(`(^|\\s)([-+]?)(${yD.join("|")}):("[^"]*"|\\S+)`,"gi")}function _D(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function bD(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function SD(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function xD(e){return SD(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function lx(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(hD(),(s,o,i,a,l)=>{if(!i&&a.toLowerCase()==="site"){let p=xD(l);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(_D(),"$1").replace(bD(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${lx(n)}`:r:n.length>0?lx(n):t}var PD=/\s/,wD=/\w/;function he(e){return e!==void 0&&PD.test(e)}function Ir(e){return e===`
|
|
75
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function Vf(e){return e!==void 0&&wD.test(e)}function Mt(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(kD(n.charCodeAt(0))):n;return t}function kD(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 Xe(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function ux(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Xe(e.slice(t))}function Er(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let s=e.indexOf(n,r+t.length);return s===-1?null:e.slice(r+t.length,s)}function zf(e,t){let n=Er(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
|
|
76
76
|
`)&&(n=n.slice(1)),n.endsWith(`
|
|
77
|
-
`)&&(n=n.slice(0,-1)),n)}function Vf(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let s=e.indexOf(">",r+1+t.length);return s===-1?null:{open:r,end:s}}function lP(e,t){let n=Vf(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function uP(e,t){let n=Vf(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 pP(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=Vf(e,t,s);if(!o)break;let i=e.indexOf(n,o.end+1);if(i===-1)break;r+=e.slice(s,o.open),s=i+n.length}return r+e.slice(s)}function dP(e,t,n){let r=[];for(let s of e.split(/[\n\r\u2028\u2029]/)){let o=0;for(;;){let i=s.indexOf(t,o);if(i===-1)break;let a=s.indexOf(n,i+t.length);if(a===-1)break;r.push(s.slice(i+t.length,a)),o=a+n.length}}return r}function Ro(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&&he(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function gP(e,t,n){let r=Mt(t),s=Mt(n);for(let o of Mt(e).split(/[\n\r\u2028\u2029]/)){let i=o.indexOf(r);if(i!==-1&&o.lastIndexOf(s)>=i+r.length)return!0}return!1}function mP(e,t){let n=Mt(e),r=t.map(Mt),s=e.length,o=l=>{let p=l;for(;p<s&&he(e[p]);)p++;return p},i=l=>{for(let p=l;p<s;p++)if(Ir(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let l=o(a);if(l>=s)return null;let p=r.find(d=>n.startsWith(d,l));if(p!==void 0){let d=o(l+p.length);if(e[d]===":"){let g=o(d+1);if(g<s){let m=g;for(;m<s&&!Ir(e[m]);)m++;for(;m>g+1&&he(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!Ir(e[m]))return e[m];return null}}a=i(l)}return null}function fP(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=he(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"||!he(e[a-1]))continue;let l=a+1;if(he(e[l])){for(;l<t&&he(e[l]);)l++;Wf(e[l])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(Ir(e[a])?1:0);let o=(a,l)=>s[l]===s[a],i=a=>{let l=a+1;for(;he(e[l]);)l++;let p=l;for(;p<t&&Wf(e[p]);)p++;return e.slice(l,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let l=a+7;for(;l<t&&/[a-z0-9]/.test(e[l]);)l++;if(l===a+7||e[l]!=="*"||e[l+1]!=="*")continue;let p=l+2,d=p;for(;d<t&&he(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(o(d,m))return{id:e.slice(a+2,l),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Ir(e[g]))return{id:e.slice(a+2,l),title:e[g],status:i(d)}}}}return null}function yP(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&he(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&he(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!Wf(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&he(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function hP(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let l=a+n.length;if(o<l&&(o=e.indexOf("]",l)),o===-1)break;let p=o;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(s,a)+(t?" ":e.slice(l,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function _P(e){return hP(e,!0)}function bP(e){return hP(e,!1)}function wD(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function SP(e,t){let n=Mt(e),r=Mt(t),s=e.length,o=i=>{let a=i;for(;a<s&&he(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=o(i+r.length);if(e[a]!==":")continue;let l=o(a+1);for(let p=l;p<s;){if(!he(e[p])){p++;continue}let d=o(p);if(wD(e,d))return e.slice(l,p);p=d}return e.slice(l)}return null}var PP=new Set(["read","glob","grep","list"]);function Z(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function kD(e){return PP.has(ae(e))}function vD(e){let t=0,n=0,r=0;for(let s of e){let o=ae(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function zf(e){if(!e)return"";let t=Xe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Co(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function To(e){let t=We(e),r=(t.state??{}).input??{};switch(Z(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=ve(r);return i?zf(i):""}case"glob":return r.pattern?String(r.pattern):"";case"grep":{let i=r.pattern??r.query,a=r.path??r.include;return i&&a?`"${Co(String(i),40)}" in ${zf(String(a))}`:i?`"${Co(String(i),60)}"`:""}case"list":return r.path?zf(String(r.path)):"";case"bash":return Co(String(r.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let i of o){let a=r[i];if(typeof a=="string"&&a.length>0)return Co(i==="query"&&Tr(a)||a,60)}return""}var xP={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 AD(e,t={}){let n=me(e)?oe(e):e,r={...xP,...t},s=Z(n.tool),o=To(n);switch(s){case"read":return{title:r.read,subtitle:o};case"glob":case"grep":return{title:r.search,subtitle:o};case"list":return{title:r.list,subtitle:o};case"bash":return{title:r.shell,subtitle:o};case"edit":case"morph_edit":return{title:r.edit,subtitle:o};case"write":return{title:r.write,subtitle:o};case"webfetch":case"web_fetch":return{title:r.fetch,subtitle:o};case"websearch":case"web_search":return{title:r.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:r.scrape,subtitle:o};case"apply_patch":return{title:r.applyPatch,subtitle:o};case"task":return{title:r.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:r.worker,subtitle:o};case"project_select":case"project_list":return{title:r.workspace,subtitle:o};default:return{title:s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase()),subtitle:o}}}function Oe(e){return e.type==="text"}function we(e){return e.type==="reasoning"}function ee(e){return e.type==="tool"}function Jf(e){return e.type==="file"}function RD(e){return e.type==="agent"}function CD(e){return e.type==="compaction"}function TD(e){return e.type==="snapshot"}function ID(e){return e.type==="patch"}function ED(e){return e.type==="step-start"||e.type==="step-finish"}function MD(e){if(Oe(e)||we(e))return e.text}function OD(e){if(!Jf(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function DD(e){let t=[],n=[];for(let r of e)Jf(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function jD(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function LD(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var $D=new Set(["todoread","context_info"]);function gn(e){return!$D.has(me(e)?e.name:e.tool)}var UD=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function Or(e){let t=me(e)?oe(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=ae(n);if(r==="task"||r==="delegate"){let s=t.state?.metadata?.sessionId;if(typeof s=="string"&&s)return s;if(r==="task"&&t.state?.status==="error")return t.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return FD(n,t.state)}function FD(e,t){let n=Z(e);if(UD.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 ND(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return ye(n.error)}}function BD(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)ee(r)&&gn(r)&&t.push(r);return t}var KD={webfetch:{icon:"globe",title:"Web Fetch",subtitle:e=>e.url},websearch:{icon:"search",title:"Web Search",subtitle:e=>e.query},web_search:{icon:"search",title:"Web Search",subtitle:e=>e.query},scrape_webpage:{icon:"globe",title:"Scrape",subtitle:e=>e.urls?.split?.(",")[0]},image_search:{icon:"image",title:"Image Search",subtitle:e=>e.query},image_gen:{icon:"image",title:"Image Gen",subtitle:e=>e.prompt?.slice?.(0,40)},video_gen:{icon:"cpu",title:"Video Gen",subtitle:e=>e.prompt?.slice?.(0,40)},presentation_gen:{icon:"presentation",title:e=>{let t=e.action||"";return{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[t]||"Presentation"},subtitle:e=>e.slide_title||e.presentation_name},show:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},show_user:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},task:{icon:"square-kanban",title:e=>`Agent (${e.subagent_type||"task"})`,subtitle:e=>vP(e)},session_spawn:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},session_start_background:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},apply_patch:{icon:"file-pen",title:"Patch",subtitle:e=>e.files?.length?`${e.files.length} file${e.files.length>1?"s":""}`:void 0},todoread:{icon:"check-square",title:"Todos (read)"},prune:{icon:"scissors",title:"DCP Prune",subtitle:e=>e.reason},distill:{icon:"scissors",title:"DCP Distill"},compress:{icon:"scissors",title:"DCP Compress",subtitle:e=>e.topic},context_info:{icon:"scissors",title:"Context Info"},session_read:{icon:"glasses",title:e=>`Session Read (${e.mode||"summary"})`,subtitle:e=>e.session_id?.slice(-12)},session_search:{icon:"search",title:"Session Search",subtitle:e=>e.query},session_message:{icon:"message-circle",title:"Message \u2192 Session",subtitle:e=>e.session_id?.slice(-12)},session_lineage:{icon:"list-tree",title:"Session Lineage",subtitle:e=>e.session_id?.slice(-12)},session_list_background:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_list_spawned:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_stats:{icon:"layers",title:"Session Stats",subtitle:e=>e.session_id?.slice(-12)||"current"},session_list:{icon:"list",title:"Session List",subtitle:e=>e.search},session_get:{icon:"book-open",title:"Session Get",subtitle:e=>e.session_id?.slice(-12)},session_context:{icon:"book-open",title:"Session Context",subtitle:e=>e.session_id?.slice(-12)},project_delete:{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:e=>e.project},project_list:{icon:"folder",title:"Projects"},project_get:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_update:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_select:{icon:"folder",title:"Project Select",subtitle:e=>e.project},project_create:{icon:"folder-plus",title:"Project Create",subtitle:e=>e.name},triggers:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_create:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_list:{icon:"clock",title:"List Triggers"},trigger_get:{icon:"clock",title:"Trigger Details",subtitle:e=>e.name||e.id},trigger_delete:{icon:"clock",title:"Delete Trigger",subtitle:e=>e.name||e.id},trigger_update:{icon:"clock",title:"Update Trigger",subtitle:e=>e.name||e.id},trigger_test:{icon:"clock",title:"Test Trigger",subtitle:e=>e.name||e.id},trigger_pause:{icon:"clock",title:"Pause Trigger",subtitle:e=>e.name||e.id},trigger_resume:{icon:"clock",title:"Resume Trigger",subtitle:e=>e.name||e.id},agent_spawn:{icon:"cpu",title:e=>`Agent (${e.agent_type||"worker"})`,subtitle:e=>e.description},agent_message:{icon:"message-circle",title:"Agent Message",subtitle:e=>e.agent_id},agent_stop:{icon:"ban",title:"Agent Stop",subtitle:e=>e.agent_id},agent_status:{icon:"layers",title:"Agent Status"},agent_task:{icon:"check-square",title:"Create Task",subtitle:e=>e.title},agent_task_update:{icon:"check-square",title:"Update Task",subtitle:e=>e.task_id},agent_task_list:{icon:"check-square",title:"List Tasks"},agent_task_get:{icon:"check-square",title:"Task Details",subtitle:e=>e.task_id},task_create:{icon:"plus",title:"Create Task",subtitle:e=>e.title},task_list:{icon:"list",title:"Tasks",subtitle:e=>e.status||"all"},task_update:{icon:"refresh-cw",title:"Update Task",subtitle:e=>e.id},task_done:{icon:"check-circle",title:"Task Done",subtitle:e=>e.id},task_delete:{icon:"trash-2",title:"Delete Task",subtitle:e=>e.id},pty_spawn:{icon:"terminal",title:"Spawn",subtitle:e=>e.title||e.command},pty_read:{icon:"terminal",title:"Terminal Output",subtitle:e=>e.id},pty_write:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_input:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_kill:{icon:"terminal",title:"Kill Process",subtitle:e=>e.id}};function qD(e,t={}){let n=KD[Z(e)];if(!n)return GD(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function GD(e,t){switch(ae(e)){case"read":return{icon:"glasses",title:"Read",subtitle:wP(ve(t))};case"list":return{icon:"list",title:"List",subtitle:kP(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:Yf(ve(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Yf(ve(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function wP(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Yf(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 kP(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function WD(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function Mr(e,t=120){if(typeof e!="string")return"";let n=e.split(`
|
|
78
|
-
`).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function
|
|
77
|
+
`)&&(n=n.slice(0,-1)),n)}function Yf(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let s=e.indexOf(">",r+1+t.length);return s===-1?null:{open:r,end:s}}function px(e,t){let n=Yf(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function dx(e,t){let n=Yf(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 gx(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=Yf(e,t,s);if(!o)break;let i=e.indexOf(n,o.end+1);if(i===-1)break;r+=e.slice(s,o.open),s=i+n.length}return r+e.slice(s)}function mx(e,t,n){let r=[];for(let s of e.split(/[\n\r\u2028\u2029]/)){let o=0;for(;;){let i=s.indexOf(t,o);if(i===-1)break;let a=s.indexOf(n,i+t.length);if(a===-1)break;r.push(s.slice(i+t.length,a)),o=a+n.length}}return r}function Co(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&&he(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function fx(e,t,n){let r=Mt(t),s=Mt(n);for(let o of Mt(e).split(/[\n\r\u2028\u2029]/)){let i=o.indexOf(r);if(i!==-1&&o.lastIndexOf(s)>=i+r.length)return!0}return!1}function yx(e,t){let n=Mt(e),r=t.map(Mt),s=e.length,o=l=>{let p=l;for(;p<s&&he(e[p]);)p++;return p},i=l=>{for(let p=l;p<s;p++)if(Ir(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let l=o(a);if(l>=s)return null;let p=r.find(d=>n.startsWith(d,l));if(p!==void 0){let d=o(l+p.length);if(e[d]===":"){let g=o(d+1);if(g<s){let m=g;for(;m<s&&!Ir(e[m]);)m++;for(;m>g+1&&he(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!Ir(e[m]))return e[m];return null}}a=i(l)}return null}function hx(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=he(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"||!he(e[a-1]))continue;let l=a+1;if(he(e[l])){for(;l<t&&he(e[l]);)l++;Vf(e[l])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(Ir(e[a])?1:0);let o=(a,l)=>s[l]===s[a],i=a=>{let l=a+1;for(;he(e[l]);)l++;let p=l;for(;p<t&&Vf(e[p]);)p++;return e.slice(l,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let l=a+7;for(;l<t&&/[a-z0-9]/.test(e[l]);)l++;if(l===a+7||e[l]!=="*"||e[l+1]!=="*")continue;let p=l+2,d=p;for(;d<t&&he(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(o(d,m))return{id:e.slice(a+2,l),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Ir(e[g]))return{id:e.slice(a+2,l),title:e[g],status:i(d)}}}}return null}function Jf(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&he(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&he(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!Vf(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&he(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function _x(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let l=a+n.length;if(o<l&&(o=e.indexOf("]",l)),o===-1)break;let p=o;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(s,a)+(t?" ":e.slice(l,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function bx(e){return _x(e,!0)}function Sx(e){return _x(e,!1)}function vD(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function xx(e,t){let n=Mt(e),r=Mt(t),s=e.length,o=i=>{let a=i;for(;a<s&&he(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=o(i+r.length);if(e[a]!==":")continue;let l=o(a+1);for(let p=l;p<s;){if(!he(e[p])){p++;continue}let d=o(p);if(vD(e,d))return e.slice(l,p);p=d}return e.slice(l)}return null}var Px=new Set(["read","glob","grep","list"]);function Z(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function AD(e){return Px.has(ae(e))}function RD(e){let t=0,n=0,r=0;for(let s of e){let o=ae(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function Qf(e){if(!e)return"";let t=Xe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function To(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Io(e){let t=We(e),r=(t.state??{}).input??{};switch(Z(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=ve(r);return i?Qf(i):""}case"glob":return r.pattern?String(r.pattern):"";case"grep":{let i=r.pattern??r.query,a=r.path??r.include;return i&&a?`"${To(String(i),40)}" in ${Qf(String(a))}`:i?`"${To(String(i),60)}"`:""}case"list":return r.path?Qf(String(r.path)):"";case"bash":return To(String(r.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let i of o){let a=r[i];if(typeof a=="string"&&a.length>0)return To(i==="query"&&Tr(a)||a,60)}return""}var wx={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 CD(e,t={}){let n=me(e)?oe(e):e,r={...wx,...t},s=Z(n.tool),o=Io(n);switch(s){case"read":return{title:r.read,subtitle:o};case"glob":case"grep":return{title:r.search,subtitle:o};case"list":return{title:r.list,subtitle:o};case"bash":return{title:r.shell,subtitle:o};case"edit":case"morph_edit":return{title:r.edit,subtitle:o};case"write":return{title:r.write,subtitle:o};case"webfetch":case"web_fetch":return{title:r.fetch,subtitle:o};case"websearch":case"web_search":return{title:r.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:r.scrape,subtitle:o};case"apply_patch":return{title:r.applyPatch,subtitle:o};case"task":return{title:r.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:r.worker,subtitle:o};case"project_select":case"project_list":return{title:r.workspace,subtitle:o};default:return{title:s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase()),subtitle:o}}}function Oe(e){return e.type==="text"}function we(e){return e.type==="reasoning"}function ee(e){return e.type==="tool"}function Zf(e){return e.type==="file"}function TD(e){return e.type==="agent"}function ID(e){return e.type==="compaction"}function ED(e){return e.type==="snapshot"}function MD(e){return e.type==="patch"}function OD(e){return e.type==="step-start"||e.type==="step-finish"}function DD(e){if(Oe(e)||we(e))return e.text}function jD(e){if(!Zf(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function LD(e){let t=[],n=[];for(let r of e)Zf(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function $D(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function UD(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var FD=new Set(["todoread","context_info"]);function gn(e){return!FD.has(me(e)?e.name:e.tool)}var ND=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function Or(e){let t=me(e)?oe(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=ae(n);if(r==="task"||r==="delegate"){let s=t.state?.metadata?.sessionId;if(typeof s=="string"&&s)return s;if(r==="task"&&t.state?.status==="error")return t.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return BD(n,t.state)}function BD(e,t){let n=Z(e);if(ND.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 KD(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return ye(n.error)}}function qD(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)ee(r)&&gn(r)&&t.push(r);return t}var GD={webfetch:{icon:"globe",title:"Web Fetch",subtitle:e=>e.url},websearch:{icon:"search",title:"Web Search",subtitle:e=>e.query},web_search:{icon:"search",title:"Web Search",subtitle:e=>e.query},scrape_webpage:{icon:"globe",title:"Scrape",subtitle:e=>e.urls?.split?.(",")[0]},image_search:{icon:"image",title:"Image Search",subtitle:e=>e.query},image_gen:{icon:"image",title:"Image Gen",subtitle:e=>e.prompt?.slice?.(0,40)},video_gen:{icon:"cpu",title:"Video Gen",subtitle:e=>e.prompt?.slice?.(0,40)},presentation_gen:{icon:"presentation",title:e=>{let t=e.action||"";return{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[t]||"Presentation"},subtitle:e=>e.slide_title||e.presentation_name},show:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},show_user:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},task:{icon:"square-kanban",title:e=>`Agent (${e.subagent_type||"task"})`,subtitle:e=>Ax(e)},session_spawn:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},session_start_background:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},apply_patch:{icon:"file-pen",title:"Patch",subtitle:e=>e.files?.length?`${e.files.length} file${e.files.length>1?"s":""}`:void 0},todoread:{icon:"check-square",title:"Todos (read)"},prune:{icon:"scissors",title:"DCP Prune",subtitle:e=>e.reason},distill:{icon:"scissors",title:"DCP Distill"},compress:{icon:"scissors",title:"DCP Compress",subtitle:e=>e.topic},context_info:{icon:"scissors",title:"Context Info"},session_read:{icon:"glasses",title:e=>`Session Read (${e.mode||"summary"})`,subtitle:e=>e.session_id?.slice(-12)},session_search:{icon:"search",title:"Session Search",subtitle:e=>e.query},session_message:{icon:"message-circle",title:"Message \u2192 Session",subtitle:e=>e.session_id?.slice(-12)},session_lineage:{icon:"list-tree",title:"Session Lineage",subtitle:e=>e.session_id?.slice(-12)},session_list_background:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_list_spawned:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_stats:{icon:"layers",title:"Session Stats",subtitle:e=>e.session_id?.slice(-12)||"current"},session_list:{icon:"list",title:"Session List",subtitle:e=>e.search},session_get:{icon:"book-open",title:"Session Get",subtitle:e=>e.session_id?.slice(-12)},session_context:{icon:"book-open",title:"Session Context",subtitle:e=>e.session_id?.slice(-12)},project_delete:{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:e=>e.project},project_list:{icon:"folder",title:"Projects"},project_get:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_update:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_select:{icon:"folder",title:"Project Select",subtitle:e=>e.project},project_create:{icon:"folder-plus",title:"Project Create",subtitle:e=>e.name},triggers:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_create:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_list:{icon:"clock",title:"List Triggers"},trigger_get:{icon:"clock",title:"Trigger Details",subtitle:e=>e.name||e.id},trigger_delete:{icon:"clock",title:"Delete Trigger",subtitle:e=>e.name||e.id},trigger_update:{icon:"clock",title:"Update Trigger",subtitle:e=>e.name||e.id},trigger_test:{icon:"clock",title:"Test Trigger",subtitle:e=>e.name||e.id},trigger_pause:{icon:"clock",title:"Pause Trigger",subtitle:e=>e.name||e.id},trigger_resume:{icon:"clock",title:"Resume Trigger",subtitle:e=>e.name||e.id},agent_spawn:{icon:"cpu",title:e=>`Agent (${e.agent_type||"worker"})`,subtitle:e=>e.description},agent_message:{icon:"message-circle",title:"Agent Message",subtitle:e=>e.agent_id},agent_stop:{icon:"ban",title:"Agent Stop",subtitle:e=>e.agent_id},agent_status:{icon:"layers",title:"Agent Status"},agent_task:{icon:"check-square",title:"Create Task",subtitle:e=>e.title},agent_task_update:{icon:"check-square",title:"Update Task",subtitle:e=>e.task_id},agent_task_list:{icon:"check-square",title:"List Tasks"},agent_task_get:{icon:"check-square",title:"Task Details",subtitle:e=>e.task_id},task_create:{icon:"plus",title:"Create Task",subtitle:e=>e.title},task_list:{icon:"list",title:"Tasks",subtitle:e=>e.status||"all"},task_update:{icon:"refresh-cw",title:"Update Task",subtitle:e=>e.id},task_done:{icon:"check-circle",title:"Task Done",subtitle:e=>e.id},task_delete:{icon:"trash-2",title:"Delete Task",subtitle:e=>e.id},pty_spawn:{icon:"terminal",title:"Spawn",subtitle:e=>e.title||e.command},pty_read:{icon:"terminal",title:"Terminal Output",subtitle:e=>e.id},pty_write:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_input:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_kill:{icon:"terminal",title:"Kill Process",subtitle:e=>e.id}};function WD(e,t={}){let n=GD[Z(e)];if(!n)return HD(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function HD(e,t){switch(ae(e)){case"read":return{icon:"glasses",title:"Read",subtitle:kx(ve(t))};case"list":return{icon:"list",title:"List",subtitle:vx(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:Xf(ve(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Xf(ve(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function kx(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Xf(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 vx(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function VD(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function Mr(e,t=120){if(typeof e!="string")return"";let n=e.split(`
|
|
78
|
+
`).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function Ax(e){let t=Mr(e.description);if(t)return t;let n=Mr(e.title,80);if(n)return n;let r=Mr(e.message);if(r)return r;let s=Mr(e.prompt);if(s)return s;let o=Mr(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function zD(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function YD(e,t){return e.find(n=>n.tool?.callID===t)}function JD(e,t){return e.find(n=>n.tool?.callID===t)}var QD=/\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 ey(e){return e?e.replace(QD,""):""}function Eo(e){let t=Rx(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let s=r&&typeof r=="object"?Rx(r):void 0;return s?[s]:[]})}function Rx(e){let t=e?.oldString??e?.old_string??e?.oldText,n=e?.newString??e?.new_string??e?.newText;return typeof t=="string"&&typeof n=="string"?[t,n]:void 0}var XD={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"},ZD={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",script:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function ej(e){return e.replace(/^oc[-_]/,"")}function ty(e){return ej(e).replace(/-/g,"_")}function ny(e){return ty(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Mo(e){return{label:XD[ty(e)]??ny(e),category:ZD[ae(e)]}}var tj=256*1024;function nj(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function rj(e){if(e===void 0)return{};if(e.length>tj)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function sj(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,s=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!s))return s?ye(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var de=e=>typeof e=="string"?e:void 0,Oo=e=>typeof e=="number"?e:void 0,Do=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function ry(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var oj=new Set(["add","update","delete","move"]);function ij(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=Do(d),m=g&&(de(g.relativePath)||de(g.filePath));if(!g||!m)return[];let f=de(g.type);return[ry({path:m,type:f&&oj.has(f)?f:void 0,before:de(g.before),after:de(g.after),patch:de(g.patch)??de(g.diff),additions:Oo(g.additions),deletions:Oo(g.deletions),movePath:de(g.movePath)})]});return p.length?p:void 0}let r=ve(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[ry({path:r,after:de(t.content)})];if(e!=="edit")return;let s=Do(n.filediff),o=s?void 0:de(n.patch),i=o?aj(o):void 0,a=s||o?[]:Eo(t);return[ry({path:r,before:de(s?.before)??(a.length?a.map(([l])=>l).join(`
|
|
79
79
|
`):void 0),after:de(s?.after)??(a.length?a.map(([,l])=>l).join(`
|
|
80
|
-
`):de(t.new_source)),patch:o,additions:
|
|
81
|
-
`))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function
|
|
82
|
-
|
|
83
|
-
`)}function Uj(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function Fj(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 Nj(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=_P(n),n=bP(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 Bj(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let s=r.error.trim(),o;for(let i=0;i<3;i++){let a=Ro(s);if(a===null)break;let l;try{l=JSON.parse(a)}catch{break}if(typeof l.status=="number"&&(o=l.status),typeof l.message=="string"&&l.message.trim())s=l.message.trim();else if(typeof l.error=="string"&&l.error.trim())s=l.error.trim();else break}return{message:s,status:o}}function jr(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Uo(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,l,p)=>{!/^https?:\/\//i.test(l)||r.has(l)||n.length>=t||(r.add(l),n.push({title:a.trim()||l,url:l,snippet:p?.trim()||void 0}))},o=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=o.exec(e))!==null;)if(s(jr(i[1]),jr(i[2]),i[3]?jr(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(s(jr(i[2]),jr(i[1])),n.length>=t)return n}return n}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jP(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{let r=JSON.parse(n);return typeof r=="object"&&r!==null?r:null}catch{}return null}}function Fo(e){return e.filter(t=>gt(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 uy(e){if(!e)return[];let t=jP(e,!0),n=t&&!Array.isArray(t)?t:void 0;if(n?.success===!1)return[];let r=n&&Array.isArray(n.results)?n.results:void 0;if(r&&r.length>0){let s=r[0];if(gt(s)&&typeof s.query=="string"){let o=[];for(let i of r)!gt(i)||typeof i.query!="string"||o.push({query:i.query,answer:i.answer||void 0,sources:Array.isArray(i.results)?Fo(i.results):[]});if(o.length>0)return o}else if(gt(s)&&(s.title||s.url)){let o=Fo(r);if(o.length>0)return[{query:n?.query||"",answer:n?.answer||void 0,sources:o}]}}if(n?.query&&typeof n.query=="string")return[{query:n.query,answer:n.answer||void 0,sources:r?Fo(r):[]}];if(Array.isArray(t)&&t.length>0){let s=t[0];if(gt(s)&&(s.title||s.url)){let o=Fo(t);if(o.length>0)return[{query:"",sources:o}]}}if(typeof e=="string"){let s=e.split(/(?=^Title: )/m).filter(Boolean),o=[];for(let i of s){let a=i.match(/^Title:\s*(.+)/m),l=i.match(/^URL:\s*(.+)/m),p=i.match(/^Author:\s*(.+)/m),d=i.match(/^Published Date:\s*(.+)/m),g=i.match(/^Text:\s*([\s\S]*?)$/m);a&&l&&o.push({title:a[1].trim(),url:l[1].trim(),snippet:g?.[1]?.trim()||void 0,author:p?.[1]?.trim()||void 0,publishedDate:d?.[1]?.trim()||void 0})}if(o.length>0)return[{query:"",sources:o}]}if(typeof e=="string"){let s=Uo(e);if(s.length>0)return[{query:"",sources:s.map(o=>({title:o.title,url:o.url,snippet:o.snippet}))}]}return[]}function No(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function Kj(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return No(e)}}function qj(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function Gj(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 LP(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let s=r.trim();/^https?:\/\//i.test(s)&&n.push(s)}return n}return[]}function $P(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=SP(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function Wj(e,t){let n=UP(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?$P(r,LP(t)):[]}function UP(e){if(!e)return null;let t=jP(e),n=t&&!Array.isArray(t)?t:void 0;if(!n)return null;if(n.results&&Array.isArray(n.results)){let r=n.results;return{total:n.total||r.length,successful:n.successful??r.filter(s=>gt(s)&&s.success!==!1).length,failed:n.failed??r.filter(s=>gt(s)&&s.success===!1).length,results:r.map(s=>{let o=gt(s)?s:{};return{url:o.url||"",success:o.success!==!1,title:o.title||void 0,content:o.content||o.text||o.snippet||void 0,error:o.error||void 0}})}}if(typeof e=="string"){let r=Uo(e);if(r.length>0)return{total:r.length,successful:r.length,failed:0,results:r.map(s=>({url:s.url,success:!0,title:s.title||void 0,content:s.snippet||void 0}))}}return null}function Hj(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 Vj={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",script:"script",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function fn(e){return Vj[ae(e)]}function $r(e){let t=Z(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var zj={run:"Terminal",memory:"Memory"};function Yj(e){let t=fn(e);return(t==="hidden"?void 0:zj[t])??$r(e)}function Lr(e,t,n){return e===1?t:n}function py(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 BP(e){return e.length?To(e[0]):""}function De(e){return(e.state??{}).input??{}}var Jj={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 Qj(e){let t=Z(e.tool);if(t==="agent_task_update"||t==="task_update")switch(De(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return Jj[t]??"message"}function FP(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 Xj(e){let t=Z(e.tool);if(t==="triggers"){let r=De(e).action||"list";return FP(r)}let n=t.match(/^trigger_(.+)$/);return FP(n?n[1]:"list")}var Zj={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 eL(e){return Zj[Z(e.tool)]??"read"}var tL={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function nL(e){return tL[Z(e.tool)]??"open"}function mn(e){return e.every(t=>t===e[0])}var rL={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function sL(e){if(Z(e.tool)!=="memory")return"read";let n=De(e).command;return n&&rL[n]||"unknown"}var oL={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},iL={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 aL(e){let t=Xe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function cL(e){let t=De(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 lL(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return aL(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=Hj(o);return i?No(i):"a link"}return""}function lL(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function uL(e){let t=De(e).action;return t&&oL[t]||"Worked on an image"}function pL(e){let t=De(e).action;return t&&iL[t]||"Worked on a presentation"}function dL(e){return e.slice(0,e.indexOf(":"))}var gL={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},mL={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 fL(e){let t=Z(e.tool);if(t==="image_gen"){let n=De(e).action;return n&&gL[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=De(e).action;return n&&mL[n]||"presentation:unknown"}return"shown:result"}var yL=new Set(["create_slide","export_pdf","export_pptx"]);function hL(e){let t=We(e),n=Z(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=De(t).action;return r?yL.has(r)?"presentation":null:"presentation"}return null}var _L={"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`},NP={image:"image",video:"video",presentation:"presentation",shown:"result"};function bL(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[dL(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Lr(s,NP[r],`${NP[r]}s`)}`)}),`Worked on ${py(n)}`}function Ur(e,t){let n=t.map(We),r=n.length,s=BP(n);switch(e){case"explore":{let o=n.filter(i=>Z(i.tool)==="read").length;return o===r?`Read ${r} ${Lr(r,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(n.map(a=>ve(De(a))).filter(Boolean)).size||r,i=n.every(a=>Z(a.tool)==="write")?"Wrote":"Updated";return o===1?s?`${i} ${s}`:`${i} a file`:`${i} ${o} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"script":return r===1?"Ran a script":`Ran ${r} scripts`;case"web":{let o=p=>{let d=Z(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(o).length;if(i===r)return`Searched the web \xB7 ${r} ${Lr(r,"query","queries")}`;if(i===0)return`Read ${r} ${Lr(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of uy(d).flatMap(m=>m.sources))g.url&&a.add(g.url)}else{let d=p.state?.input?.url;typeof d=="string"&&d&&a.add(d)}let l=a.size||r;return`Searched and read ${l} ${Lr(l,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=Z(i.tool);if(a==="image_gen")return uL(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return pL(i);let l=cL(i);return l?`Showed you ${l}`:"Showed you the result"}let o=n.map(fL);return mn(o)?_L[o[0]](r):bL(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(Qj);if(mn(o))switch(o[0]){case"spawn":return r===1?"Asked a helper agent":`Worked with ${r} helper agents`;case"message":return r===1?"Sent instructions to a helper agent":`Sent instructions to ${r} helper agents`;case"status":return"Checked on a helper agent";case"stop":return r===1?"Stopped a helper agent":`Stopped ${r} helper agents`;case"done":return r===1?"A helper agent finished a task":`Helper agents finished ${r} tasks`;case"delete":return r===1?"Removed a task":`Removed ${r} tasks`}return r===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${r} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=n.map(sL);if(mn(o))switch(o[0]){case"write":return r===1?"Wrote to its memory":`Wrote to its memory \xB7 ${r} updates`;case"delete":return r===1?"Deleted from its memory":`Deleted ${r} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=n.map(eL);if(mn(o))switch(o[0]){case"connect":return r===1?s?`Connected to ${s}`:"Connected a connector":`Connected ${r} connectors`;case"call":return r===1?"Used a connector":`Made ${r} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=n.map(Xj);if(mn(o))switch(o[0]){case"create":return r===1?"Set up an automation":`Set up ${r} automations`;case"update":return r===1?"Updated an automation":`Updated ${r} automations`;case"delete":return r===1?"Deleted an automation":`Deleted ${r} automations`;case"control":return r===1?"Adjusted an automation":`Adjusted ${r} automations`;case"test":return r===1?"Tested an automation":`Tested ${r} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=n.map(nL);if(mn(o))switch(o[0]){case"delete":return r===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${r} projects \u2014 deletion isn't allowed`;case"create":return r===1?s?`Created ${s}`:"Created a project":`Created ${r} projects`;case"update":return r===1?s?`Updated ${s}`:"Updated your project":`Updated ${r} projects`;case"open":return r===1?s?`Opened ${s}`:"Opened your project":`Opened ${r} projects`}return s?`Worked in ${s}`:"Worked in your project"}case"skills":return r===1?s?`Used the ${s} skill`:"Used a skill":`Used ${r} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(r===1)return`Used ${$r(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>$r(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${py(o)}`}}}function dy(e,t){let n=t.map(We),r=BP(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let s=Z(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${s} ${r}`:`Couldn't ${s} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let s=n.filter(a=>a.state?.status==="error"),o=s.length?s:n,i=Array.from(new Set(o.map(a=>$r(a.tool))));return`Couldn't finish using ${py(i)}`}}}var KP=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),SL={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 PL(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 xL(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let s=n[r];if(typeof s=="string"&&s.trim())return PL(r,s.trim())}}function yn(e){let t=me(e)?oe(e):e;if(we(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!ee(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=fe(t.tool),r=SL[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:xL(s,r.objectKeys),tier:KP.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function Bo(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(yn(o).tier==="plumbing"){r=!0;continue}if(we(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,ee(o)&&$o(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function gy(e){return`${e} ${e===1?"step":"steps"}`}function qP(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${gy(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${gy(n)}`:s===0?`${gy(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function my(e){let t=new Map,n=0;for(let s of e){if(!ee(s)||yn(s).tier==="plumbing")continue;let o=fn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),$o(s)!=="ok"&&(n+=1))}if(t.size===0)return qP(Bo(e),!1);let r=[...t].map(([s,o],i)=>{let a=Ur(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function wL(e){let t=!1,n=!1,r=!1,s=null,o=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),s==null&&d.error!=null&&(s=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},l=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");l&&(t=!0),e.userMessage&&o(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)o(p.info),i(p.parts);return l&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function kL(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function vL(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let s=r.state.time;typeof s?.start=="number"&&(t=Math.min(t,s.start)),typeof s?.end=="number"&&(n=Math.max(n,s.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function GP(e,t){let n=t.map(We),r=kL(n);return{id:n[0].callID,family:e,label:r==="error"?dy(e,n):Ur(e,n),parts:t,status:r,durationMs:r==="running"?void 0:vL(n)}}function fy(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(GP(n,r)),n=null,r=[]};for(let o of e){let i=We(o),a=fn(i.tool);if(a!=="hidden"&&!Ys(i)){if(Pm(i.tool)){s(),t.push(GP(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function Ko(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function yy(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:l}=r,p=typeof a=="number"&&typeof l=="number"&&l>a?l-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of fy(s))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});s=[]}};for(let a of e)if(t(a)!=="plumbing"){if(we(a)){let l=a.text?.trim();if(!l)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(l);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=Ko(a);continue}if(o(),ee(a)){s.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}o(),i();for(let a=0;a<n.length-1;a++){let l=n[a];l.kind==="thought"&&(l.running=!1)}return n}var AL=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function RL(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 CL(e){let t=e.flatMap(s=>{let o=RL(s);return o?[o]:[]}).join(" ").trim();return t?AL.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function YP(e){return e?.info?.time??{}}function TL(e){let t=YP(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var qo=6e4,IL=10080*qo,WP=1440;function HP(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 EL(e,t){let n=t.getTime()-e.getTime(),r=n/qo,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<WP)return s(Math.round(r/60),"hour");let o=(n-(HP(t)-HP(e)))/qo;return s(Math.round(o/WP),"day")}function JP(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 VP=new Map;function ML(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=VP.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),VP.set(r,s)),s}function Go(e,t,n){return ML(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?OL(r.value,n):r.value).join("")}function OL(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function zP(e,t){return Go(e,{year:"numeric"},t)}function DL(e,t,n={}){let r=JP(e);if(!r)return"";let s=i=>Go(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return s(!0);let o=Math.max(0,t-r.getTime());return o<qo?"just now":o<IL?EL(r,new Date(t)):s(zP(r,n)!==zP(new Date(t),n))}function jL(e,t={}){let n=JP(e);if(!n)return"";let r=Go(n,{month:"long",day:"numeric",year:"numeric"},t),s=Go(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function hy(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!xm(o)){if(Oe(o)){s(),n.push({kind:"text",part:o});continue}if(ee(o)&&(wm(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function LL(e){let t=fe(e);return t==="show"||t==="show_user"}function _y(e,t={}){let n=[],r=[],s=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(o=>o.part)}),r=[]};for(let o of e){if(o.kind==="standalone"&&LL(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var $L=["title","description","path","url","content","language","aspect_ratio","attachment"];function QP(e,t){if(!t||typeof t!="object")return null;let n=t;if(ar(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of $L){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function UL(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 by(e){let t=[];for(let n of e){let r=n.state,s=r.input??{};if(r.status==="error"){let a=typeof s.title=="string"&&s.title?s.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let o=UL(s.items),i=o?o.map(a=>QP(n.callID,a)).filter(a=>!!a):[QP(n.callID,s)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function Sy(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Fr=e=>"id"in e?e.id:e.userMessage.info.id,XP=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,FL=e=>e.time?.completed;function NL(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function BL(e,t){let n=Fr(e);return t.pendingTurnIds.has(n)||XP(e)===0&&t.pendingPromptIds.has(n)}function KL(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Fr(r)));if(t)return Fr(t);let n=e.turns.findIndex(r=>BL(r,e));return n<=0?null:Fr(e.turns[n-1])}function qL(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function GL(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 WL(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Sy({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function HL(e,t){for(let n=e.length-1;n>=0;n--){let r=Fr(e[n]);if(t(r))return XP(e[n])===0?r:null}return null}function Py(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),s=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(l=>l.userMessage.info.id)}),o=e.hintMessageId??null;if(o){if(n>=0&&t[n].userMessage.info.id===o)return s(n);let a=r.indexOf(o);if(a>=0)return s(n+1+a)}if(n>=0){let a=t[n],l=a.assistantMessages[a.assistantMessages.length-1];if(!FL(l.info)&&!l.info.error)return s(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return s(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:s(n)}function VL(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 zL(e,t){return!t||!e?!1:e.type!=="idle"}function YL(e,t){return!e&&!!t}function JL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Se(n.error)?.message||ye(n.error)}}function QL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Cr(n.error)}}function XL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Se(n.error)}}function xy(e){if(e){if(ee(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(we(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(Oe(e))return"Gathering thoughts..."}}var ZL=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function e$(e){if(!(!e||e.length===0))for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.info.role==="assistant")for(let r=n.parts.length-1;r>=0;r--){let s=xy(n.parts[r]);if(s)return s}}}function t$(e,t){let n=ee(e)?e:void 0;if(n&&ZL.has(n.tool)&&n.state.status==="running"){let r=e$(t);return r||(t?.length?"Handing off to an agent...":void 0)}return xy(e)}function wy(e,t){for(let n=e.length-1;n>=0;n--){let r=t$(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function ky(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 vy=1.055;function ZP(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),s=e.cache?.read??0,o=e.cache?.write??0,i=Math.max(0,n-s-o),l=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*l.inputPer1M;return p+=r/1e6*l.outputPer1M,s>0&&(p+=s/1e6*(l.cacheReadPer1M??l.inputPer1M)),o>0&&(p+=o/1e6*(l.cacheWritePer1M??l.inputPer1M)),p}function Ay(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function ex(e,t,n,r){if(Ay(t,n))return 0;let s=e.cost||0;if(s>0)return s;if(!r||!t||!n)return 0;let o=r(t,n);return o?ZP(e.tokens,o):0}function tx(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function Wo(e,t){let n=0,r=0,s=0,o=0,i=0,a=0,l=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){l=!0;let g=p,{providerID:m,modelID:f}=tx(d.info);n+=ex(g,m,f,t),r+=g.tokens?.input||0,s+=g.tokens?.output||0,o+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!l){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=nx(g,t),f=g.tokens&&Ay(g.providerID,g.modelID);if(m<=0&&!f)continue;l=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,s+=h.output??0,o+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(l)return{cost:n*vy,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function nx(e,t){if(Ay(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?ZP({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function n$(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=tx(s),a=0,l=!1;for(let p of r.parts)p.type==="step-finish"&&(l=!0,a+=ex(p,o,i,t));l||(a+=nx(s,t)),n+=a}return n*vy}function r$(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function s$(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function o$(e){if(!e||e.type!=="retry")return;let t=e,n=ye(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:Se(t.message)}}function i$(e){if(!(!e||e.type!=="retry"))return ye(e.message)}function a$(e){return(e.info.summary?.diffs?.length??0)>0}function rx(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=fe(e.part.tool);return t==="show"||t==="show_user"}function c$(e){return e.kind==="text"&&!e.part.text?.trim()}function Ry(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(rx(o)||c$(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):rx(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function l$(e){let t=e==null?"":ky(e);return t?`Worked for ${t}`:"Worked"}function sx(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>Oe(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return ee(s)&&s.tool==="bash"}function u$(e){if(sx(e))return e.assistantMessages[0].parts[0]}function p$(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=pP(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 d$(e){return e?e.split(`
|
|
84
|
-
`).filter(n=>n.trim()).length<=3:!1}function
|
|
85
|
-
`).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function
|
|
86
|
-
`).filter(r=>r.trim());for(let r of n){let s=
|
|
87
|
-
`),r=n===-1?e:e.slice(0,n),s=n===-1?"":e.slice(n+1);if(
|
|
80
|
+
`):de(t.new_source)),patch:o,additions:Oo(s?.additions)??i?.additions,deletions:Oo(s?.deletions)??i?.deletions})]}function aj(e){let t=0,n=0;for(let r of e.split(`
|
|
81
|
+
`))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function cj(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function Cx(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=rj(r),i=nj(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=sj(s);m&&(i="error",a=m)}let l=ae(e),p=t.input??{},d="metadata"in t&&Do(t.metadata)||{},g=Do(d.diagnostics);return{name:e,kind:l,title:n||Mo(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:ij(l,p,d),diff:de(d.patch)??de(d.diff),diagnostics:g,answers:l==="question"?cj(d):void 0,childSessionId:Or({tool:e,state:t})}}function sy(e){let t=me(e)?oe(e):e;return Cx(t.tool,t.state)}function lj(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function uj(e){return{kind:"reasoning",id:e.id,text:e.text}}function pj(e){return{kind:"tool",id:e.id,tool:Cx(e.tool,e.state)}}function dj(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 gj(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function mj(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function fj(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function yj(e){return{kind:"agent",id:e.id,name:e.name}}function hj(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:ye(e.error),createdAt:e.time.created}}function _j(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function bj(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function Sj(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function oy(e){switch(e.type){case"text":return lj(e);case"reasoning":return uj(e);case"tool":return pj(e);case"file":return dj(e);case"subtask":return gj(e);case"patch":return mj(e);case"snapshot":return fj(e);case"agent":return yj(e);case"retry":return hj(e);case"compaction":return _j(e);case"step-start":return bj(e);case"step-finish":return Sj(e);default:return{kind:"unknown",raw:e}}}function xj(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=Se(e);return{name:t,message:n?.message||ye(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function Pj(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function jo(e){let t=e.parts.map(oy),n=e.info.role==="assistant"?e.info.error:void 0,r=xj(n),s=!r&&!t.some(Pj);return{parts:t,error:r,isEmpty:s}}var iy=Ve+BigInt(1),Tx=iy/BigInt(2);function Lo(e){return BigInt(Math.trunc(e))*Xt}function ay(e,t){let r=t-(t&Ve)+e;return r-t>Tx?r-=iy:t-r>Tx&&(r+=iy),r}function Ix(e,t){let n=Tt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return ay(n,t);let s=Lo(r),o=ay(n,s);return(o>s?o-s:s-o)<=ct?o:s}function Ex(e){return Tt(e)===null?1:0}function Mx(e,t){return e<t?-1:e>t?1:0}function wj(e,t){return $o(e,t,Lo(Date.now()))}function cy(e){let t=null;for(let n of e){let r=n.info.time?.created;typeof r=="number"&&(t===null||r>t)&&(t=r)}return Lo(t??Date.now())}function $o(e,t,n){let r=Ex(e.info.id),s=Ex(t.info.id);if(r!==s)return r-s;if(r===0){let a=Ix(e,n),l=Ix(t,n);return a!==l?a<l?-1:1:Mx(e.info.id,t.info.id)}let o=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return o===null&&i===null?0:o===null?1:i===null?-1:o!==i?o<i?-1:1:Mx(e.info.id,t.info.id)}function kj(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 vj(e){let t=e-6e4;return(n,r)=>{let s=n.time.updated??n.time.created,o=r.time.updated??r.time.created,i=s>t,a=o>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:o-s}}function Ox(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let s of n)r.push(s),r.push(...Ox(e,s));return r}function Aj(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=cy(e),s=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:$o(d,g,r)}),o=[],i=new Map;for(let d of s)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};o.push(g),i.set(d.info.id,g)}let a=null,l=[],p=[];for(let d of s){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=l[l.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):l.push({userMessage:Cj(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=o[0]??l[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;o.push({userMessage:g,assistantMessages:m})}}return l.length>0?[...l,...o]:o}var Dr=new Map,Rj=256;function Cj(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=Dr.get(s);if(o)return o;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(Dr.size>=Rj){let a=Dr.keys().next().value;a!==void 0&&Dr.delete(a)}return Dr.set(s,i),i}function Tj(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function Ij(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(Oe(n)&&n.text?.trim())return n}}function Ej(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function Mj(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!ee(o))continue;let i=o,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:o,message:s})}return r}function Dx(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function ly(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&&Dx(n.error)}return!1}function jr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function uy(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 Oj(e){return!!e&&(uy(e)||py(e)!==null)}function Uo(e){let t=me(e)?oe(e):e,n=jx.get(t);if(n&&n.state===t.state)return n.outcome;let r=Dj(t);return jx.set(t,{state:t.state,outcome:r}),r}var jx=new WeakMap;function Dj(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(uy(n))return"failed";let r=jj(n);return r===void 0?"ok":Lj(r)?"failed":$j(r)}function jj(e){try{return JSON.parse(e)}catch{return}}function Lj(e){return jr(e)&&e.success===!1&&typeof e.error=="string"}function $j(e){let t=jr(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 py(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!jr(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},s=Uj.exec(Jf(r.errorSummary));s&&(r.status=Number(s[1]));let o=Co(r.errorSummary);if(o===null)return r;try{let i=JSON.parse(o),a=Fj(i);a&&(r.nestedMessage=a),typeof i.status=="number"&&(r.status=i.status),typeof i.error=="boolean"&&(r.nestedError=i.error)}catch{}return r}var Uj=/^([1-5]\d{2}) Error\b/;function Fj(e){let{message:t,error:n,detail:r}=e,s=[t,jr(n)?n.message:void 0,jr(r)?r.error:void 0,r];for(let o of s)if(typeof o=="string"&&o.trim())return o.trim()}function Nj(e){return Jf(e).replace(/\s+/g," ").trim()||e.trim()}function Bj(e){let t=py(e);if(!t)return null;let n=[];return n.push(t.errorSummary),t.nestedMessage!==void 0&&n.push(`Details: ${t.nestedMessage}`),t.hint&&n.push(`Hint: ${t.hint}`),n.join(`
|
|
82
|
+
|
|
83
|
+
`)}function Kj(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function qj(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 Gj(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=bx(n),n=Sx(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 Wj(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let s=r.error.trim(),o;for(let i=0;i<3;i++){let a=Co(s);if(a===null)break;let l;try{l=JSON.parse(a)}catch{break}if(typeof l.status=="number"&&(o=l.status),typeof l.message=="string"&&l.message.trim())s=l.message.trim();else if(typeof l.error=="string"&&l.error.trim())s=l.error.trim();else break}return{message:s,status:o}}function Lr(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Fo(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,l,p)=>{!/^https?:\/\//i.test(l)||r.has(l)||n.length>=t||(r.add(l),n.push({title:a.trim()||l,url:l,snippet:p?.trim()||void 0}))},o=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=o.exec(e))!==null;)if(s(Lr(i[1]),Lr(i[2]),i[3]?Lr(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(s(Lr(i[2]),Lr(i[1])),n.length>=t)return n}return n}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lx(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{let r=JSON.parse(n);return typeof r=="object"&&r!==null?r:null}catch{}return null}}function No(e){return e.filter(t=>gt(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 dy(e){if(!e)return[];let t=Lx(e,!0),n=t&&!Array.isArray(t)?t:void 0;if(n?.success===!1)return[];let r=n&&Array.isArray(n.results)?n.results:void 0;if(r&&r.length>0){let s=r[0];if(gt(s)&&typeof s.query=="string"){let o=[];for(let i of r)!gt(i)||typeof i.query!="string"||o.push({query:i.query,answer:i.answer||void 0,sources:Array.isArray(i.results)?No(i.results):[],...i.success===!1?{error:typeof i.error=="string"&&i.error.trim()||"Search failed"}:{}});if(o.length>0)return o}else if(gt(s)&&(s.title||s.url)){let o=No(r);if(o.length>0)return[{query:n?.query||"",answer:n?.answer||void 0,sources:o}]}}if(n?.query&&typeof n.query=="string")return[{query:n.query,answer:n.answer||void 0,sources:r?No(r):[]}];if(Array.isArray(t)&&t.length>0){let s=t[0];if(gt(s)&&(s.title||s.url)){let o=No(t);if(o.length>0)return[{query:"",sources:o}]}}if(typeof e=="string"){let s=e.split(/(?=^Title: )/m).filter(Boolean),o=[];for(let i of s){let a=i.match(/^Title:\s*(.+)/m),l=i.match(/^URL:\s*(.+)/m),p=i.match(/^Author:\s*(.+)/m),d=i.match(/^Published Date:\s*(.+)/m),g=i.match(/^Text:\s*([\s\S]*?)$/m);a&&l&&o.push({title:a[1].trim(),url:l[1].trim(),snippet:g?.[1]?.trim()||void 0,author:p?.[1]?.trim()||void 0,publishedDate:d?.[1]?.trim()||void 0})}if(o.length>0)return[{query:"",sources:o}]}if(typeof e=="string"){let s=Fo(e);if(s.length>0)return[{query:"",sources:s.map(o=>({title:o.title,url:o.url,snippet:o.snippet}))}]}return[]}function Bo(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function Hj(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Bo(e)}}function Vj(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function zj(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 $x(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let s=r.trim();/^https?:\/\//i.test(s)&&n.push(s)}return n}return[]}function Ux(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=xx(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function Yj(e,t){let n=Fx(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?Ux(r,$x(t)):[]}function Fx(e){if(!e)return null;let t=Lx(e),n=t&&!Array.isArray(t)?t:void 0;if(!n)return null;if(n.results&&Array.isArray(n.results)){let r=n.results;return{total:n.total||r.length,successful:n.successful??r.filter(s=>gt(s)&&s.success!==!1).length,failed:n.failed??r.filter(s=>gt(s)&&s.success===!1).length,results:r.map(s=>{let o=gt(s)?s:{};return{url:o.url||"",success:o.success!==!1,title:o.title||void 0,content:o.content||o.text||o.snippet||void 0,error:o.error||void 0}})}}if(typeof e=="string"){let r=Fo(e);if(r.length>0)return{total:r.length,successful:r.length,failed:0,results:r.map(s=>({url:s.url,success:!0,title:s.title||void 0,content:s.snippet||void 0}))}}return null}function Jj(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 Qj={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",script:"script",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function fn(e){return Qj[ae(e)]}function Ur(e){let t=Z(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var Xj={run:"Terminal",memory:"Memory"};function Zj(e){let t=fn(e);return(t==="hidden"?void 0:Xj[t])??Ur(e)}function $r(e,t,n){return e===1?t:n}function gy(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 Kx(e){return e.length?Io(e[0]):""}function De(e){return(e.state??{}).input??{}}var eL={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 tL(e){let t=Z(e.tool);if(t==="agent_task_update"||t==="task_update")switch(De(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return eL[t]??"message"}function Nx(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 nL(e){let t=Z(e.tool);if(t==="triggers"){let r=De(e).action||"list";return Nx(r)}let n=t.match(/^trigger_(.+)$/);return Nx(n?n[1]:"list")}var rL={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 sL(e){return rL[Z(e.tool)]??"read"}var oL={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function iL(e){return oL[Z(e.tool)]??"open"}function mn(e){return e.every(t=>t===e[0])}var aL={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function cL(e){if(Z(e.tool)!=="memory")return"read";let n=De(e).command;return n&&aL[n]||"unknown"}var lL={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},uL={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 pL(e){let t=Xe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function dL(e){let t=De(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 gL(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return pL(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=Jj(o);return i?Bo(i):"a link"}return""}function gL(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function mL(e){let t=De(e).action;return t&&lL[t]||"Worked on an image"}function fL(e){let t=De(e).action;return t&&uL[t]||"Worked on a presentation"}function yL(e){return e.slice(0,e.indexOf(":"))}var hL={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},_L={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 bL(e){let t=Z(e.tool);if(t==="image_gen"){let n=De(e).action;return n&&hL[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=De(e).action;return n&&_L[n]||"presentation:unknown"}return"shown:result"}var SL=new Set(["create_slide","export_pdf","export_pptx"]);function xL(e){let t=We(e),n=Z(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=De(t).action;return r?SL.has(r)?"presentation":null:"presentation"}return null}var PL={"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`},Bx={image:"image",video:"video",presentation:"presentation",shown:"result"};function wL(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[yL(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${$r(s,Bx[r],`${Bx[r]}s`)}`)}),`Worked on ${gy(n)}`}function Fr(e,t){let n=t.map(We),r=n.length,s=Kx(n);switch(e){case"explore":{let o=n.filter(i=>Z(i.tool)==="read").length;return o===r?`Read ${r} ${$r(r,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(n.map(a=>ve(De(a))).filter(Boolean)).size||r,i=n.every(a=>Z(a.tool)==="write")?"Wrote":"Updated";return o===1?s?`${i} ${s}`:`${i} a file`:`${i} ${o} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"script":return r===1?"Ran a script":`Ran ${r} scripts`;case"web":{let o=p=>{let d=Z(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(o).length;if(i===r)return`Searched the web \xB7 ${r} ${$r(r,"query","queries")}`;if(i===0)return`Read ${r} ${$r(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of dy(d).flatMap(m=>m.sources))g.url&&a.add(g.url)}else{let d=p.state?.input?.url;typeof d=="string"&&d&&a.add(d)}let l=a.size||r;return`Searched and read ${l} ${$r(l,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=Z(i.tool);if(a==="image_gen")return mL(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return fL(i);let l=dL(i);return l?`Showed you ${l}`:"Showed you the result"}let o=n.map(bL);return mn(o)?PL[o[0]](r):wL(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(tL);if(mn(o))switch(o[0]){case"spawn":return r===1?"Asked a helper agent":`Worked with ${r} helper agents`;case"message":return r===1?"Sent instructions to a helper agent":`Sent instructions to ${r} helper agents`;case"status":return"Checked on a helper agent";case"stop":return r===1?"Stopped a helper agent":`Stopped ${r} helper agents`;case"done":return r===1?"A helper agent finished a task":`Helper agents finished ${r} tasks`;case"delete":return r===1?"Removed a task":`Removed ${r} tasks`}return r===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${r} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=n.map(cL);if(mn(o))switch(o[0]){case"write":return r===1?"Wrote to its memory":`Wrote to its memory \xB7 ${r} updates`;case"delete":return r===1?"Deleted from its memory":`Deleted ${r} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=n.map(sL);if(mn(o))switch(o[0]){case"connect":return r===1?s?`Connected to ${s}`:"Connected a connector":`Connected ${r} connectors`;case"call":return r===1?"Used a connector":`Made ${r} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=n.map(nL);if(mn(o))switch(o[0]){case"create":return r===1?"Set up an automation":`Set up ${r} automations`;case"update":return r===1?"Updated an automation":`Updated ${r} automations`;case"delete":return r===1?"Deleted an automation":`Deleted ${r} automations`;case"control":return r===1?"Adjusted an automation":`Adjusted ${r} automations`;case"test":return r===1?"Tested an automation":`Tested ${r} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=n.map(iL);if(mn(o))switch(o[0]){case"delete":return r===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${r} projects \u2014 deletion isn't allowed`;case"create":return r===1?s?`Created ${s}`:"Created a project":`Created ${r} projects`;case"update":return r===1?s?`Updated ${s}`:"Updated your project":`Updated ${r} projects`;case"open":return r===1?s?`Opened ${s}`:"Opened your project":`Opened ${r} projects`}return s?`Worked in ${s}`:"Worked in your project"}case"skills":return r===1?s?`Used the ${s} skill`:"Used a skill":`Used ${r} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(r===1)return`Used ${Ur(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>Ur(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${gy(o)}`}}}function my(e,t){let n=t.map(We),r=Kx(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let s=Z(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${s} ${r}`:`Couldn't ${s} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let s=n.filter(a=>a.state?.status==="error"),o=s.length?s:n,i=Array.from(new Set(o.map(a=>Ur(a.tool))));return`Couldn't finish using ${gy(i)}`}}}var qx=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),kL={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 vL(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 AL(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let s=n[r];if(typeof s=="string"&&s.trim())return vL(r,s.trim())}}function yn(e){let t=me(e)?oe(e):e;if(we(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!ee(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=fe(t.tool),r=kL[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:AL(s,r.objectKeys),tier:qx.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function Ko(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(yn(o).tier==="plumbing"){r=!0;continue}if(we(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,ee(o)&&Uo(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function fy(e){return`${e} ${e===1?"step":"steps"}`}function Gx(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${fy(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${fy(n)}`:s===0?`${fy(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function yy(e){let t=new Map,n=0;for(let s of e){if(!ee(s)||yn(s).tier==="plumbing")continue;let o=fn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),Uo(s)!=="ok"&&(n+=1))}if(t.size===0)return Gx(Ko(e),!1);let r=[...t].map(([s,o],i)=>{let a=Fr(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function RL(e){let t=!1,n=!1,r=!1,s=null,o=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),s==null&&d.error!=null&&(s=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},l=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");l&&(t=!0),e.userMessage&&o(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)o(p.info),i(p.parts);return l&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function CL(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function TL(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let s=r.state.time;typeof s?.start=="number"&&(t=Math.min(t,s.start)),typeof s?.end=="number"&&(n=Math.max(n,s.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function Wx(e,t){let n=t.map(We),r=CL(n);return{id:n[0].callID,family:e,label:r==="error"?my(e,n):Fr(e,n),parts:t,status:r,durationMs:r==="running"?void 0:TL(n)}}function hy(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(Wx(n,r)),n=null,r=[]};for(let o of e){let i=We(o),a=fn(i.tool);if(a!=="hidden"&&!Js(i)){if(wm(i.tool)){s(),t.push(Wx(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function qo(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function _y(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:l}=r,p=typeof a=="number"&&typeof l=="number"&&l>a?l-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of hy(s))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});s=[]}};for(let a of e)if(t(a)!=="plumbing"){if(we(a)){let l=a.text?.trim();if(!l)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(l);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=qo(a);continue}if(o(),ee(a)){s.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}o(),i();for(let a=0;a<n.length-1;a++){let l=n[a];l.kind==="thought"&&(l.running=!1)}return n}var IL=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function EL(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 ML(e){let t=e.flatMap(s=>{let o=EL(s);return o?[o]:[]}).join(" ").trim();return t?IL.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function Jx(e){return e?.info?.time??{}}function OL(e){let t=Jx(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Go=6e4,DL=10080*Go,Hx=1440;function Vx(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 jL(e,t){let n=t.getTime()-e.getTime(),r=n/Go,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<Hx)return s(Math.round(r/60),"hour");let o=(n-(Vx(t)-Vx(e)))/Go;return s(Math.round(o/Hx),"day")}function Qx(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 zx=new Map;function LL(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=zx.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),zx.set(r,s)),s}function Wo(e,t,n){return LL(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?$L(r.value,n):r.value).join("")}function $L(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function Yx(e,t){return Wo(e,{year:"numeric"},t)}function UL(e,t,n={}){let r=Qx(e);if(!r)return"";let s=i=>Wo(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return s(!0);let o=Math.max(0,t-r.getTime());return o<Go?"just now":o<DL?jL(r,new Date(t)):s(Yx(r,n)!==Yx(new Date(t),n))}function FL(e,t={}){let n=Qx(e);if(!n)return"";let r=Wo(n,{month:"long",day:"numeric",year:"numeric"},t),s=Wo(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function by(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!km(o)){if(Oe(o)){s(),n.push({kind:"text",part:o});continue}if(ee(o)&&(vm(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function NL(e){let t=fe(e);return t==="show"||t==="show_user"}function Sy(e,t={}){let n=[],r=[],s=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(o=>o.part)}),r=[]};for(let o of e){if(o.kind==="standalone"&&NL(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var BL=["title","description","path","url","content","language","aspect_ratio","attachment"];function Xx(e,t){if(!t||typeof t!="object")return null;let n=t;if(ar(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of BL){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function KL(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 xy(e){let t=[];for(let n of e){let r=n.state,s=r.input??{};if(r.status==="error"){let a=typeof s.title=="string"&&s.title?s.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let o=KL(s.items),i=o?o.map(a=>Xx(n.callID,a)).filter(a=>!!a):[Xx(n.callID,s)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function Py(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Nr=e=>"id"in e?e.id:e.userMessage.info.id,Zx=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,qL=e=>e.time?.completed;function GL(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function WL(e,t){let n=Nr(e);return t.pendingTurnIds.has(n)||Zx(e)===0&&t.pendingPromptIds.has(n)}function HL(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Nr(r)));if(t)return Nr(t);let n=e.turns.findIndex(r=>WL(r,e));return n<=0?null:Nr(e.turns[n-1])}function VL(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function zL(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 YL(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Py({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function JL(e,t){for(let n=e.length-1;n>=0;n--){let r=Nr(e[n]);if(t(r))return Zx(e[n])===0?r:null}return null}function wy(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),s=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(l=>l.userMessage.info.id)}),o=e.hintMessageId??null;if(o){if(n>=0&&t[n].userMessage.info.id===o)return s(n);let a=r.indexOf(o);if(a>=0)return s(n+1+a)}if(n>=0){let a=t[n],l=a.assistantMessages[a.assistantMessages.length-1];if(!qL(l.info)&&!l.info.error)return s(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return s(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:s(n)}function QL(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 XL(e,t){return!t||!e?!1:e.type!=="idle"}function ZL(e,t){return!e&&!!t}function e$(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Se(n.error)?.message||ye(n.error)}}function t$(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Cr(n.error)}}function n$(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Se(n.error)}}function ky(e){if(e){if(ee(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(we(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(Oe(e))return"Gathering thoughts..."}}var r$=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function s$(e){if(!(!e||e.length===0))for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.info.role==="assistant")for(let r=n.parts.length-1;r>=0;r--){let s=ky(n.parts[r]);if(s)return s}}}function o$(e,t){let n=ee(e)?e:void 0;if(n&&r$.has(n.tool)&&n.state.status==="running"){let r=s$(t);return r||(t?.length?"Handing off to an agent...":void 0)}return ky(e)}function vy(e,t){for(let n=e.length-1;n>=0;n--){let r=o$(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function Ay(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 Ry=1.055;function eP(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),s=e.cache?.read??0,o=e.cache?.write??0,i=Math.max(0,n-s-o),l=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*l.inputPer1M;return p+=r/1e6*l.outputPer1M,s>0&&(p+=s/1e6*(l.cacheReadPer1M??l.inputPer1M)),o>0&&(p+=o/1e6*(l.cacheWritePer1M??l.inputPer1M)),p}function Cy(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function tP(e,t,n,r){if(Cy(t,n))return 0;let s=e.cost||0;if(s>0)return s;if(!r||!t||!n)return 0;let o=r(t,n);return o?eP(e.tokens,o):0}function nP(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function Ho(e,t){let n=0,r=0,s=0,o=0,i=0,a=0,l=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){l=!0;let g=p,{providerID:m,modelID:f}=nP(d.info);n+=tP(g,m,f,t),r+=g.tokens?.input||0,s+=g.tokens?.output||0,o+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!l){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=rP(g,t),f=g.tokens&&Cy(g.providerID,g.modelID);if(m<=0&&!f)continue;l=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,s+=h.output??0,o+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(l)return{cost:n*Ry,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function rP(e,t){if(Cy(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?eP({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function i$(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=nP(s),a=0,l=!1;for(let p of r.parts)p.type==="step-finish"&&(l=!0,a+=tP(p,o,i,t));l||(a+=rP(s,t)),n+=a}return n*Ry}function a$(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function c$(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function l$(e){if(!e||e.type!=="retry")return;let t=e,n=ye(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:Se(t.message)}}function u$(e){if(!(!e||e.type!=="retry"))return ye(e.message)}function p$(e){return(e.info.summary?.diffs?.length??0)>0}function sP(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=fe(e.part.tool);return t==="show"||t==="show_user"}function d$(e){return e.kind==="text"&&!e.part.text?.trim()}function Ty(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(sP(o)||d$(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):sP(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function g$(e){let t=e==null?"":Ay(e);return t?`Worked for ${t}`:"Worked"}function oP(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>Oe(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return ee(s)&&s.tool==="bash"}function m$(e){if(oP(e))return e.assistantMessages[0].parts[0]}function f$(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=gx(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 y$(e){return e?e.split(`
|
|
84
|
+
`).filter(n=>n.trim()).length<=3:!1}function h$(e){if(!e)return null;let n=e.split(`
|
|
85
|
+
`).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function _$(e){if(!e)return[];let t=[],n=e.split(`
|
|
86
|
+
`).filter(r=>r.trim());for(let r of n){let s=hx(r);if(s){let o=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...s,sessionId:o?.[0]})}}return t}var mt={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 b$(e,t){let n=mt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function S$(e,t){return t?"failed":e?"running":"done"}var x$={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function P$(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function w$(e,t){if(!e)return null;let n=e.indexOf(`
|
|
87
|
+
`),r=n===-1?e:e.slice(0,n),s=n===-1?"":e.slice(n+1);if(fx(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
|
|
88
88
|
`).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
|
|
89
89
|
`)};if(/files and directories/i.test(r)){let o=t.replace(/\/$/,""),i=[];for(let a of s.split(`
|
|
90
|
-
`)){if(!a.trim())continue;let l=a.indexOf(" ");if(l===-1)continue;let p=a.slice(0,l).trim(),d=a.slice(l+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var
|
|
90
|
+
`)){if(!a.trim())continue;let l=a.indexOf(" ");if(l===-1)continue;let p=a.slice(0,l).trim(),d=a.slice(l+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var k$={add:{...mt.write,icon:"create"},delete:{...mt.delete,icon:"delete"},move:{...mt.rename,icon:"edit"},update:{...mt.edit,icon:"edit"}},iP={...mt.change,icon:"edit"};function v$(e){if(e.length===0)return iP;let t=aP(e[0]);for(let n=1;n<e.length;n++)if(aP(e[n])!==t)return iP;return k$[t]}function aP(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function A$(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 Iy(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],s;for(;(s=n.exec(e))!==null;)r.push(s[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(o,i)=>r[i]?[r[i]]:[])}function R$(e){if(!e)return null;let t=Er(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=zf(e,"content");if(r!==null){let o=r.split(`
|
|
91
91
|
`).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
|
|
92
|
-
`);return{path:n,type:"file",content:o}}let s=
|
|
93
|
-
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function
|
|
94
|
-
\u2026`:e}function
|
|
92
|
+
`);return{path:n,type:"file",content:o}}let s=zf(e,"entries");if(s!==null){let o=s.split(`
|
|
93
|
+
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function C$(e){let t=dx(e,"skill_content");return t!==null?t.trim():e}function cP(e){let t=Er(e,"<skill_files>","</skill_files>");return t===null?[]:mx(t,"<file>","</file>").map(n=>n.trim())}function T$(e){let t=px(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 I$(e){return yx(e,["Base directory","Directory","Skill directory"])?.trim()??""}function lP(e){return Xe(T$(e)||I$(e))}function E$(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Xe(n.trim())}return""}var M$="skills";function O$(e){let t=ux(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(s=>s.trim());if(n.some(s=>s===".."||s==="."))return"";let r=n.at(-1)??"";return r?`${M$}/${r}`:""}function D$(e,t,n){let s=Xe(t?.trim()??"")||lP(e)||O$(n),o=cP(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(o){if(o.startsWith("/"))return o;if(s)return`${s}/${o}`}return s?`${s}/SKILL.md`:null}var j$=4e3;function Br(e,t=j$){return e.length>t?`${e.slice(0,t)}
|
|
94
|
+
\u2026`:e}function uP(e){if(e!==void 0)try{return Br(JSON.stringify(e,null,2))}catch{return}}function ne(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function hn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function L$(e){let t=ne(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=hn(e.outputParsed);if(!n)return{kind:"web-search",query:t};let s=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(o=>{let i=hn(o)??{};return{title:ne(i.title)??"",url:ne(i.url,i.link)??"",snippet:ne(i.snippet,i.description,i.source)}});return{kind:"web-search",query:ne(n.query)??t,results:s.length>0?s:void 0,answer:ne(n.answer)}}var $$=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function My(e){let t=e.match($$);return t?Number(t[1]):void 0}function U$(e,t,n){let r="",s=0;for(;;){let o=e.indexOf(t,s);if(o===-1)return r+e.slice(s);let i=e.indexOf(n,o+t.length);if(i===-1)return r+e.slice(s);r+=e.slice(s,o),s=i+n.length}}var F$=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function N$(e){let t=-1;for(let n of F$){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}function B$(e){let t=ne(e.input?.command)??"",n=e.output??"",r=My(n),o=ey(N$(U$(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:o||void 0,exitCode:r}}function Oy(e){return ne(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function K$(e){let t=e.status==="error"?e.error:e.output&&Br(e.output)||void 0;return{kind:"file-read",path:Oy(e),preview:t}}function q$(e){let t=ne(e.input?.content),n=e.status==="error"?e.error:Br(t??e.output??"")||void 0;return{kind:"file-write",path:Oy(e),preview:n}}var G$=256*1024;function W$(e,t){if(e.length+t.length>G$)return;let n=e.split(`
|
|
95
95
|
`),r=t.split(`
|
|
96
|
-
`),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let l=0;l<s;l++)a.push({type:"unchanged",text:n[l]});for(let l=s;l<o;l++)a.push({type:"removed",text:n[l]});for(let l=s;l<i;l++)a.push({type:"added",text:r[l]});for(let l=o;l<n.length;l++)a.push({type:"unchanged",text:n[l]});return a}function
|
|
97
|
-
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function H$(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=px.test(e.output.trim())?G$(e.output):W$(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function V$(e){let t=ne(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=ne(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function Ty(e){let t=hn(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function z$(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(Ty)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(Ty)};let n=hn(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(Ty)}:{kind:"todo",items:[]}}function Y$(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=hn(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let l=hn(a),p=l&&ne(l.label);return p?[{label:p,description:l?ne(l.description):void 0}]:[]});return{question:ne(s.question)??"",header:ne(s.header),options:i}})}}function J$(e){let n=e.input&&Object.keys(e.input).length>0?lx(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Nr(e.outputParsed):lx(e.outputParsed):e.outputText!==void 0?r=Nr(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function dx(e){switch(ae(e.name)){case"web_search":return M$(e);case"bash":return $$(e);case"read":return U$(e);case"write":return F$(e);case"edit":return K$(e);case"grep":case"glob":return H$(e);case"task":return V$(e);case"todowrite":return z$(e);case"question":return Y$(e);default:return J$(e)}}var Q$=new Set(["AbortError","MessageAbortedError"]),X$=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],Z$=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function gx(e){let t=e.toLowerCase();return Z$.some(n=>t.includes(n))?!1:X$.some(n=>t.includes(n))}function e0(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 Br(e){if(typeof e=="string")return gx(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&Q$.has(n))return!0;let r=e0(t);return typeof r=="string"?gx(r):!1}var mx=["user","runtime-disposed","orphan-finalized","wake"],t0=["orphan-finalized","wake"];function n0(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 mx.includes(n)?n:void 0}var Kr="kortix-active-instance",fx=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function yx(e){return fx.some(t=>e===t||e.startsWith(`${t}/`))}function _n(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 r0(e){let t=_n(e);return!!t&&t.innerPath===""}function s0(e){let t=_n(e);return!t||!t.innerPath?e:t.innerPath}function hx(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=_n(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return yx(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function _x(e){return e?_n(e)?.instanceId??null:null}function o0(){return typeof window>"u"?null:_x(window.location.pathname)||bx()}function bx(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Kr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function i0(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Kr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Kr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Kr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function a0(e,t){return t?hx(t,e):e}function c0(e){let t=_n(e);return t?t.innerPath||"/dashboard":e}function Gr(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e??"")}function My(e){let t=Gr(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}var l0=My;function Ho(e){let t=My(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var u0=Ho;function Sx(e){return Ho(e)!==null}var p0=Sx,d0=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],g0=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],m0=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function Px(e){return m0.test(Gr(e))}function bn(e){let t=Gr(e);return t?Px(t)||d0.some(n=>n.test(t)):!1}var f0=/server url not ready|sandbox is still loading/i;function y0(e){return f0.test(Gr(e))||bn(e)}var qr=class extends Error{constructor(t){let n=t?.trim();super(n&&bn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function xx(e){let t=Ho(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${a}`,detail:o?`${i?`${i}: `:""}${o}`:void 0}}let n=Gr(e);return bn(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 h0=xx;function Oy(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`${ot()}/p/${e.external_id}/${Ke.KORTIX_MASTER}`}function _0(e,t){return e.external_id?`${ot()}/p/${e.external_id}/${t}`:null}async function b0(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function wx(e){let t=await tr();if(t)return{sandbox:t.sandbox,created:!1};let r=(await xt())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await Rt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await nt(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Ns(r,s,o),created:!0}}async function S0(){return(await tr().catch(()=>null))?.sandbox??null}async function P0(e){return{sandbox:(await wx(e)).sandbox}}async function x0(e){let t=er(e);if(!t)return null;try{let n=await tm(t);return n?Ns(await wt(n.project_id),n,null):(await tr(t))?.sandbox??null}catch{return null}}async function w0(e,t){throw await Bs(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function k0(e){let t=er(e);return(await em().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function v0(){return null}async function A0(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Bs(e);if(!t)throw new Error("Project session sandbox not found");await Yn(t.projectId,t.sessionId)}async function R0(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Bs(e);if(!t)throw new Error("Project session sandbox not found");await Jn(t.projectId,t.sessionId)}async function C0(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function T0(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function Dy(e,t,n){let r=Oy(e),s=await $(`${le(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function I0(e,t){return Dy(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function E0(e,t,n,r="member"){await Dy(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function M0(e,t,n){await Dy(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var jy="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function O0(e){throw N("getInvite",jy)}async function D0(e){throw N("acceptInvite",jy)}async function j0(e){throw N("declineInvite",jy)}async function L0(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function $0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function U0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function F0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function N0(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function B0(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var kx=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function K0(e){return kx.includes(e)}async function q0(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 G0(e){let t=e?`?channel=${e}`:"",r=await(await Le(`${ot()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await vx(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function vx(e){let t=e?`?channel=${e}`:"";return(await(await Le(`${ot()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function W0(){return(await Le(`${ot()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function H0(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function V0(e){}async function z0(e){}async function Y0(e){return{serverTypes:[],location:e||"hel1"}}async function J0(e){throw new Error("Retired instance provisioning is unavailable. Create a project session on platinum (or the legacy daytona fallback).")}async function Q0(e){throw N("deleteInstance")}async function X0(e,t){}async function Z0(){throw N("claimComputer")}async function eU(e){return null}function tU(e,t){throw N("getSandboxProvisionStreamUrl")}var Wr=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function Ax(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 Rx(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Cx(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 te(e,t,n){let r=n?.body!==void 0,s=await fetch(`${qe(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:Ax(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await Rx(s);if(!s.ok)throw new Wr(Cx(s,o),s.status,o);return o}function nU(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 rU(e,t){return te(`/marketplace/items${nU(t)}`,e)}function sU(e){return te("/marketplace/marketplaces",e)}function oU(e,t){return te(`/marketplace/items/${encodeURIComponent(e)}`,t)}function iU(e,t,n){return te(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function aU(e,t){return te("/access/check-email",t,{method:"POST",body:{email:e}})}function cU(e,t){return te("/access/request-access",t,{method:"POST",body:e})}function lU(e){return te("/auth/logout",e,{method:"POST",body:{}})}function uU(e,t){return te(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function pU(e,t){return te("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function dU(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function gU(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function mU(e,t,n={}){return te(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function fU(e,t){return te(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function yU(e,t,n,r){return te(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function hU(e,t){return te(`/p/public-share/${encodeURIComponent(e)}`,t)}function _U(e,t,n){return te(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function bU(e){return te("/system/maintenance",e)}function SU(e,t){return te("/system/maintenance",t,{method:"PUT",body:e})}function PU(e){return te("/user-roles",e)}function xU(e,t){return te("/system/demo-request",t,{method:"POST",body:e})}async function wU(e,t,n){let r=await fetch(`${qe(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Ht(t)}`,{headers:Ax(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await Rx(r);throw new Wr(Cx(r,s),r.status,s)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function kU(e,t){throw N("openStressTestStream")}function vU(e,t){throw N("buildPublicTemplateUrl")}async function AU(e,t,n){throw N("getPublicTemplate")}var RU="kortix:connect-link:";function Ly(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);t=Math.imul(t^s,16777619)>>>0,n=Math.imul(n^s,1540483477)>>>0}return`${RU}${t.toString(36)}${n.toString(36)}`}function CU(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(Ly(i));if(!a)return;let l=JSON.parse(a);if(Date.parse(l.expires_at)<=Date.now()){t.removeItem(Ly(i));return}return l}catch{return}},o=(i,a)=>{if(t)try{t.setItem(Ly(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let l=s(i);return l&&r.set(i,l),l},load(i){let a=n.get(i);if(a)return a;let l=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,l),l}}}var Tx="Could not start the connect flow.";async function TU(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:Tx}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:Tx};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var Ix=3e3,Ex=5e3,Mx=5*6e4;function IU(e,t){let n=e===0?Ix:Ex;return t+n>Mx?null:n}function EU(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 MU(){let e=await c.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function OU(e={}){let t=await c.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function DU(e){let t=await c.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function jU(e){let t=await c.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function LU(){let e=await c.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var DJ="1";var $U="kortix.query-cache";function Dx(e){return!!e&&typeof e.then=="function"}function Ox(e){return Dx(e)?e:Promise.resolve()}function UU(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 FU(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:l=$U,now:p=()=>Date.now()}=e,d=`${l}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),S=()=>{try{return Ox(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},v=(P,k)=>{if(!k)return 0;let C;try{C=JSON.parse(k)}catch{return S(),0}if(!C||C.v!==s||C.user!==n||!Array.isArray(C.queries)||p()-C.at>o)return S(),0;let j=0;for(let R of C.queries){if(!R||!Array.isArray(R.k)||R.d===void 0||typeof R.t!="number"||p()-R.t>o||!r(R.k))continue;let L=P.getQueryState(R.k);L&&L.data!==void 0&&L.dataUpdatedAt>=R.t||(P.setQueryData(R.k,R.d,{updatedAt:R.t}),P.invalidateQueries?.({queryKey:R.k,exact:!0,refetchType:"none"}),j+=1)}return j},T=P=>P.getQueryCache().getAll().filter(k=>k.state.data!==void 0&&r(k.queryKey)).map(k=>({k:k.queryKey,d:k.state.data,t:k.state.dataUpdatedAt})).sort((k,C)=>C.t-k.t),_=(P,k)=>{let C=[],j=0;for(let R of P){let L=JSON.stringify(R).length+1;j+L>k||(C.push(R),j+=L)}return C},b=async P=>{let k=_(T(P),i);for(;;){let C={v:s,user:n,at:p(),queries:k};try{await Ox(t.setItem(d,JSON.stringify(C)));return}catch{if(k.length===0)return;k=k.slice(0,Math.floor(k.length/2))}}},O=()=>{f!==null&&(clearTimeout(f),f=null)},y=()=>{O();let P=g;return!P||!m||(m=!1,h=h.then(()=>b(P)).catch(()=>{})),h},w=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,y()},a))};return{storageKey:d,restore(P){let k;try{k=t.getItem(d)}catch{return 0}return Dx(k)?k.then(C=>v(P,C)).catch(()=>0):v(P,k)},persist(P){g=P,m=!0;let k=P.getQueryCache().subscribe(C=>{C.type!=="updated"&&C.type!=="removed"&&C.type!=="added"||r(C.query.queryKey)&&w()});return()=>{k(),g===P&&(g=null,O())}},flush(){return y()},async clear(){O(),g=null,m=!1,await h,await S()}}}function NU(){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 jx="/kortix/part/";function Lx(e){return typeof e=="string"&&e.startsWith(jx)}async function BU(e){if(!Lx(e))throw new Error(`not an attachment part reference: ${e}`);let t=ze();if(!t)throw new Error("runtime url not bound");let n=await $(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function $x(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 KU(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.has(n.origin)}catch{return!1}}function $y(e,t){return KU(e,t)?(t?$x(t):null)??$x(e):null}function Hr(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 qU(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var GU=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function WU(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function HU(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let s=(t.slice(n+3).split("/")[0]??"").toLowerCase(),o=`${r}://${s}`.split("{port}").map(i=>i.split("{sandbox}").map(WU).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function VU(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function Ux(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function zU(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:GU.test(n.hostname)?t.backendUrls.some(r=>{let s=VU(r);return s!==null&&Ux(s)===Ux(n)}):t.templates.some(r=>HU(n.origin,r))}async function Fx(e,t={}){if(!Hr(e))return!1;let n=I().backendUrl;n&&await it(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return zU(e,{templates:sb(),backendUrls:r})}async function Nx(e,t={}){let n=$y(e,t.serverUrl||I().backendUrl||void 0);if(!n)return!1;let r=await Ft();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 YU(e,t={}){if(Hr(e)){if(!await Fx(e,t)||!await Ft())return e;let r=await c.post("/p/ticket",{preview_url:e}),s=r.data;if(!r.success||!s||typeof s.ticket!="string"||!s.ticket)throw new Error("Preview authorization failed");let o=new URL(e);return o.searchParams.delete("token"),o.searchParams.set("preview_ticket",s.ticket),o.toString()}return await Nx(e,t),e}var JU=3e3;function Bx(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 QU(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return Bx(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function XU(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function ZU(e,t){throw N("buildPresentationTemplatePdfUrl")}function eF(e,t){throw N("buildPresentationTemplateImageUrl")}function Kx(e,t){return`${XU(e)}/presentation/convert-to-${t}`}async function tF(e,t,n,r){let s=Kx(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),l=!1;for(;;){let p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(l||(l=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,S)=>{let v=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(v),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 nF(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 rF(e){return e==="unreachable"}function sF(e){return!e||e.status===0?"unknown":e.ok&&rf(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var qx=1e4,oF={connection:"unknown",faultSinceMs:null};function iF(e,t,n,r=qx){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let s=e.faultSinceMs??n;return n-s>=r?{connection:t,faultSinceMs:s}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:s}}function Gx({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<Vo,l=!!t&&i-t.atMs<Jo;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:l,abortFloor:l?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=zo,streamFresh:!!s&&i-s.atMs<=Sn,inboxFresh:!!n&&i-n.atMs<=Yo,activityFresh:!!o&&i-o.atMs<=Sn}}function Pn(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Uy(e,t,n){if(!t)return!1;let r=Pn(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=Pn(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function aF(e,t,n,r){let{activity:s,server:o}=e,{serverFresh:i,abortFloor:a,activityFresh:l}=t;return l&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!Uy(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function cF(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,l=i?s.turns.filter(g=>!Uy(g,n,s)):[],p=l.find(g=>g.state==="active")??l[0],d=!!o&&!(o.type==="idle"&&o.origin==="local");return p&&s.atMs>=a&&(!d||s.atMs>=o.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:Pn(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function lF(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:l,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...l&&o.type!=="idle"&&(!p||o.atMs>s.atMs)&&o.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&s.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function uF(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:l,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,S=l&&!n&&s.atMs>=p,v=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(S&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:Pn(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(v)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let T=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:a};return{state:"idle",source:T.source,turnId:null,since:T.atMs,serverOpenTurnToken:r}}function Wx(e){let t=Gx(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=aF(e,t,s,o);if(i)return i;let{result:a,openTurn:l}=cF(e,t,s,o);return a??lF(e,t,o)??uF(e,t,l,o)}var Vo=6e4,zo=45e3,Sn=45e3,Yo=1e4,pF=3e3,Jo=15e3;function dF(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function gF(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 mF(e){return Wx(e)}function fF(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,l=[null,t?t.atMs+Vo:null,n?n.atMs+Jo:null,r?r.atMs+Yo:null,s?s.atMs+zo:null,o?o.atMs+Sn:null,i?i.atMs+Sn:null],p=null;for(let d of l)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function Hx(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(o=>o.message_id===t),r=e.last_ended,s=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!s?.message||Br({name:s.name??void 0,message:s.message})?null:s}var yF="SandboxMemoryGuard";function hF(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=Hx(e,t);if(r?.message){if(r.name!==yF)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],l=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:l}}let s=e.recent_failures?.find(a=>a.message_id===t);if(!s)return null;let o=s.ended_at?Date.parse(s.ended_at):Number.NaN;return Number.isFinite(o)&&typeof e.atMs=="number"&&e.atMs-o<2500?null:{kind:"unexplained"}}var _F=6e4;function bF(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function SF(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var Vx=9e4;function PF(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+Vx}var xF=75e3,wF=2,kF=2e4;function Fy(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function vF(e){return e.filter(t=>t!=null).join("|")}function AF(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function RF(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Fy(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Fy(),settled:!0};let i=e.lastProgressAtMs,a=i===null,l=t.progress!==e.fingerprint,p=i===null||l?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!l&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return g;let f=AF(e.attempts,s);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var CF={"retry-start":"retrying",restart:"restarting"};function TF(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${CF[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function IF(e){return e===1?"once":e===2?"twice":`${e} times`}function EF(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(s=>s.step==="restart").length,n=e.attempts.some(s=>s.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${IF(t)}`),`Tried: ${r.join(", then ")}.`}var MF={"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 zx(e){return!!(e.metadata??{}).legacy_migration}function OF(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return e.working?.state==="idle"?"done":"running";case"completed":case"stopped":return zx(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function DF(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 jF={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 LF(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 Yx(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 $F(e){let t=Yx(e);return t?Qo(e).filter(n=>(n.parent_id===t.id||!n.parent_id&&n.fork_source_id)&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function UF(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>Qo(r).some(s=>s.id===t))??null)}var FF=new Set;function Jx(e){for(let t of[...FF])try{t(e)}catch{}}var tw={schema:ce,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var nw=e=>Object.values(e.ext??{}).find(t=>t.version===ke),rw=e=>!!e&&nw(e)!==void 0,sw=e=>{let t=nw(e);return t?t.native_id??null:e.thread_id};function ow(e){let t=e&&Object.values(e.threads).find(r=>r.parent_thread_id===null);if(!e||!t)return null;let n=(e.messages[t.thread_id]?.length??0)>0;return{runtimeSessionId:sw(t),hasMessages:n,empty:!n&&e.older[t.thread_id]===!1}}var Qx=new WeakMap;function iw(e,t){let n=sw(e),r=Qx.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=Vs({...tw,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return Qx.set(t,{native:n,rows:o}),o}var Ny=e=>e.info.time?.created;var NF=(e,t)=>(Ny(e)??-1/0)-(Ny(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var Xx=new WeakMap,Zx=new WeakMap,aw=e=>typeof e=="object"&&e!==null,BF=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,KF=e=>e.info.role==="user"&&e.parts.some(t=>aw(t)&&t.type==="compaction"),qF=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},ew=new WeakMap;function GF(e,t,n){let r=t.info,s=`${e}|${String(r.id)}|${String(r.time?.created)}`,o=!1,i=n.blocks.map((a,l)=>{let p=t.parts[l];if(!aw(p)||a.type==="compaction")return a;let d=`${s}|${l}|${a.id}`,g=ew.get(p);return g&&g.key===d?(o=!0,g.block):(ew.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function WF(e){let t=new Map,n=new Set;for(let r of e){if(!KF(r))continue;let s=e.find(o=>!n.has(o)&&qF(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function HF(e,t,n,r,s){let o=Xx.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=zs({session_id:e,root_id:t,rows:(r?[n,r]:[n]).map(d=>({runtime_session_id:t,info:d.info,parts:d.parts}))},{live:!0}),l=GF(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:s,message:{...l,seq:s},lost:a.grade_counts};return Xx.set(n,p),p}function cw(e,t,n){let r=Zx.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(NF),{paired:o,used:i}=WF(s),a={tool_input:0,cut_point:0,attachment:0},l=[];for(let m of s){if(i.has(m))continue;let f=HF(e,t,m,o.get(m),l.length+1);for(let h of["tool_input","cut_point","attachment"])a[h]+=f.lost[h];l.push(f.message)}let p=BF(s.map(Ny).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=l.filter(m=>m.role==="user"&&m.kind==="turn"),g={...tw,session_id:e,created_at:p,restore_grade:a.tool_input+a.cut_point+a.attachment>0?"partial":"converted",grade_counts:a,harness:{current:"opencode",history:[]},selection:{agent:d.at(-1)?.agent??null,model:d.at(-1)?.model??null},threads:[{schema:ce,v:1,thread_id:t,parent_thread_id:null,spawned_by:null,agent:d[0]?.agent??null,title:null,created_at:l[0]?.created_at||p,messages:l,ext:{opencode:{version:ke,native_id:t}}}]};return Zx.set(n,{sessionId:e,native:t,log:g}),g}var By=new WeakMap,xn=new WeakMap,lw=new WeakMap;function Xo(e){let t,n=xn.get(e);return n&&(t=VF(n).get(e.id)),t?(By.set(t,e),t):(e.type!=="harness"?t=bm(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=lw.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},lw.set(e,t)),t&&By.set(t,e),t)}var Vr=e=>By.get(e),Ot=e=>e.flatMap(t=>Xo(t)??[]),uw=new WeakMap;function VF(e){let t=uw.get(e);return t||uw.set(e,t=new Map(ft(e)[0]?.parts.map(n=>[n.id,n]))),t}var pw=new Map;function ft(e){let t=pw.get(e.thread_id);return t||(t={schema:ce,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},pw.set(e.thread_id,t)),iw(t,e)}var zF="kortix-v1-import",Ky={schema:ce,v:1};function Zo(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var qy=e=>e.type==="tool_call",YF=e=>e.status==="pending"||e.status==="running",Gy=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function hw(e,t){let n=Gy(e);return!YF(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var dw=new WeakMap;function _w(e,t){let n=dw.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),s={...Ky,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"kortix-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return dw.set(e,s),s}var gw=new WeakMap;function JF(e){let t=gw.get(e);return t||(t={...Ky,message_id:e.reply_to,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},gw.set(e,t)),t}var mw=new WeakMap;function QF(e){let t=mw.get(e);return t||(t={...Ky,message_id:`${e.message_id}:continued`,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},mw.set(e,t)),t}var XF=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function ZF(e,t){let n=[],r=new Map;for(let g of e){if(g.role!=="user"||g.kind==="context"||r.has(g.message_id))continue;let m={user:g,assistant:[],partial:!1};r.set(g.message_id,m),n.push(m)}let s=[],o=[],i=new Map,a=new Map,l=null,p=null;for(let g of e){if(g.role==="user"){let S=r.get(g.message_id);S&&!t.has(g.message_id)&&(l=S,i.has(S)||i.set(S,i.size),S.user.kind==="compaction"&&(p=S));continue}if(g.role!=="assistant"||XF(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??l;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let S=a.get(p);S||(S={user:QF(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,S)),f=S}if(f){f.assistant.push(g);continue}if(!g.reply_to){o.push(g);continue}let h=s[s.length-1];h&&h.user.message_id===g.reply_to?h.assistant.push(g):s.push({user:JF(g),assistant:[g],partial:!0})}if(o.length){let g=n[0]??s[0];g?g.assistant.unshift(...o):n.push({user:o[0],assistant:o.slice(1),partial:!1})}let d=n.filter(g=>!t.has(g.user.message_id)).flatMap(g=>{let m=a.get(g);return m?[g,m]:[g]});return[...s,...d,...[...t].flatMap(g=>r.get(g)??[])]}function eN(e,t){let n=[],r=new Map,s=t;for(let o of e){let i=n[n.length-1],a=o.continues?r.get(o.continues.marker):o.user.kind==="compaction"&&i?.user.kind!=="compaction"?i:void 0;if(!a){n.push({...o,assistant:[...o.assistant]});continue}r.set(o.user.message_id,a),o.user.kind==="compaction"&&a.assistant.push(o.user),a.assistant.push(...o.assistant),t===o.user.message_id&&(s=a.user.message_id)}return{list:n,hint:s}}function tN(e,t){if(!t)return t;let n=t;for(let r of e){let s=r.continues;s&&(n===s.marker||n===s.prompt||t===s.prompt)&&(n=r.user.message_id)}return n}function bw(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=ft(n)[0]?.info?.error??n.error.message,s=Se(r),o=Cr(r);return{code:n.error.code,message:s?.message||ye(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function nN(e,t,n){return e.length&&e.every(t)?Wo(e.flatMap(r=>ft(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:Wy(e,n)}function Wy(e,t){let n=e.flatMap(r=>{let s=r.usage;if(!s)return[];let o={type:"step-finish",cost:s.cost??0,tokens:{input:s.input,output:s.output,reasoning:s.reasoning??0,cache:{read:s.cache_read,write:s.cache_write}}};return[{part:o,message:{info:{id:r.message_id,role:"assistant",providerID:r.model?.provider,modelID:r.model?.model},parts:[o]}}]});return Wo(n,t)??null}function rN(e){if(e.kind!=="compaction")return null;let t=e.blocks.find(n=>n.type==="compaction")??null;return{block:t,hasContent:!!t?.summary?.trim(),inFlight:e.status==="streaming"}}function sN(e){let t=e.user.blocks;if(!t.length||!t.every(r=>r.type==="text"&&r.synthetic))return null;let n=e.assistant.length===1&&e.assistant[0].blocks.length===1?e.assistant[0].blocks[0]:null;return n&&qy(n)&&n.name==="bash"?n:null}function oN(e,t,n,r){if(!n.length)return[];let s=new Set(e.assistant.map(i=>i.message_id)),o=new Set;for(let i of n)i.spawned_by&&s.has(i.spawned_by.message_id)&&o.add(i.thread_id);for(let i of t){let a=i.type==="subtask"?i.thread_id:qy(i)?Or(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var iN=e=>e.assistant.some(t=>t.blocks.some(n=>qy(n)&&ae(n.name)==="todowrite"&&gn(n))),aN=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function cN(e,t){let n=e.map(s=>bw(s)!==null),r=e.map((s,o)=>n[o]===!0&&t[o+1]===!0);return e.map((s,o)=>{if(r[o])return{continued:!0,retries:0};if(!n[o])return;let i=0;for(let a=o-1;a>=0&&r[a];a--)i+=1;return i>0?{continued:!1,retries:i}:void 0})}var fw=new WeakMap,lN=[];function Hy(e){let t=Zo(e.messages,n=>n.role==="assistant");return!!t&&iy(ft(t))}var yw=new WeakMap;function uN(e){let t=yw.get(e);if(!t){let n=e.messages.filter(r=>r.in_context||r.status==="streaming");t=n.length===e.messages.length?e:{...e,messages:n},yw.set(e,t)}return t}function ei(e,t={}){let n=t.hideOutOfContext?uN(e):e,r=new Set(t.held??lN),s=ZF(n.messages,r),o=tN(s,t.liveMessageId),{list:i,hint:a}=t.foldCompactions?eN(s,o):{list:s,hint:o},l=Zo(n.messages,_=>_.role==="assistant"),p=Hy(n),d=Py({turns:i.map(_=>({userMessage:{info:{id:_.user.message_id}},assistantMessages:_.assistant.map(b=>({info:{time:b.status==="streaming"?{}:{completed:1},error:b.error??void 0}}))})),hintMessageId:a,unrunTurnIds:r}),g=Zo(i,iN)??i[i.length-1],m=i.map(_=>!_.partial&&aN(_.user)),f=cN(i,m),h=rw(n),S=_=>h||_.producer.harness===zF,v=t.threads??[],T=new Set(v.map(_=>_.thread_id));return i.map((_,b)=>{let O=t.busy===!0&&d.workingTurnId===_.user.message_id,y=d.pendingTurnIds.includes(_.user.message_id),w=p&&_.assistant.includes(l),P=f[b],k=`${_.partial}|${O}|${y}|${_===g}|${w}|${P?(P.continued?"c":"")+P.retries:"-"}`,C=fw.get(_.user);if(C&&C.key===k&&C.pricing===t.pricing&&C.heads===t.threads&&C.assistant.length===_.assistant.length&&C.assistant.every((D,q)=>D===_.assistant[q]))return C.turn;let j=_.assistant.flatMap(D=>D.blocks);for(let D of _.assistant)for(let q of D.blocks)xn.set(q,D);let R=oN(_,j,v,T),L=_.assistant[_.assistant.length-1],pe={internal:m[b],autoRetry:P,id:_.user.message_id,user:_.user,assistant:_.assistant,partial:_.partial,continues:_.continues??null,blocks:j,status:w?"streaming":L?L.status:_.user.kind==="compaction"?_.user.status:"pending",error:bw(_),cost:nN([_.user,..._.assistant],S,t.pricing),compaction:rN(_.user),threads:R,plan:_===g,shell:sN(_),response:Zo(j,D=>D.type==="text"&&!!D.text.trim())??null,attachments:_.user.blocks.filter(D=>D.type==="attachment"&&(D.mime.startsWith("image/")||D.mime==="application/pdf")),live:O,queued:y,retrying:w};return fw.set(_.user,{assistant:_.assistant,key:k,pricing:t.pricing,heads:t.threads,turn:pe}),pe})}var Vy=e=>Vr(e);function ww(e,t={}){return _y(hy(Ot(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(Vr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Vy)}:n.kind==="text"?{kind:n.kind,block:Vr(n.part)}:{kind:n.kind,block:Vy(n.part)})}var pN=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:Ot(e.blocks)}:{kind:e.kind,part:Xo(e.block)};function kw(e,t){let n=new Map(e.map(o=>[pN(o),o])),r=Ry([...n.keys()],t);if(!r)return null;let s=o=>o.map(i=>n.get(i));return{work:s(r.work),hoisted:s(r.hoisted),final:s(r.final)}}function dN(e){if(!ee(e)||!Sm(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=ty(e);return(n.answers??Cy(n.outputText??"",t.length)??[]).length>0}function vw(e){return yy(Ot(e),n=>yn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(dN)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:Vr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Vy),family:n.step.family,label:n.step.label,status:n.step.status,durationMs:n.step.durationMs};let r=e.find(o=>o.id===n.key.slice(8)),s=r&&xn.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function Aw(e,t){return wy(Ot(e.blocks).map(n=>({part:n})),t?.flatMap(ft))}function Rw(e){return Bo(Ot(e))}function Cw(e){return my(Ot(e))}function Tw(e,t){return t.working?t.trailing?!0:e.some(n=>{if(n.type==="tool_call")return n.status==="pending"||n.status==="running";if(n.type!=="reasoning")return!1;let r=Xo(n),s=xn.get(n);return!!r&&we(r)&&Ko(r)&&(!s||s.status==="streaming")}):!1}var Sw=new WeakMap;function Iw(e){if(!Gy(e))return e;let t=Sw.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},Sw.set(e,t)}return t}function gN(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function Ew(e){let t=e.map(oe),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=by(t).map(gN);return lr({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function Mw(e,t,n){let r=oe(e),s=r.state;return lr({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function Ow(e){let t=ft(e).map(r=>Do(r)),n=t.find(r=>r.error)?.error;return{parts:t.flatMap(r=>r.parts),error:n,isEmpty:t.every(r=>r.isEmpty)&&!n}}var Pw=Object.freeze([]),xw=new WeakMap;function Dw(e){if(!e)return Pw;let t=xw.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&gn(s)):[]);t=n.length?n:Pw,xw.set(e,t)}return t}function jw(e,t={}){let n={cost:0,messages:{all:0,user:0,assistant:0},tokens:{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},context:null};for(let r of ei(e)){let s=Wy([r.user,...r.assistant],t.pricing);if(s){n.cost+=s.cost;for(let o of Object.keys(n.tokens))n.tokens[o]+=s.tokens[o]}}for(let r of e.messages){r.role==="user"?n.messages.user++:r.role==="assistant"&&n.messages.assistant++,r.kind==="compaction"&&r.status!=="streaming"&&n.messages.assistant++;let s=r.usage;(r.role==="assistant"||r.kind==="compaction")&&s&&s.input+s.output+(s.reasoning??0)+s.cache_read+s.cache_write>0&&(n.context=r)}return n.messages.all=n.messages.user+n.messages.assistant,n}var mN="prt_kortix_restore_g";function $w(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(mN))}function Uw(e,t){let n=new Map,r=[...e??[]].sort((s,o)=>s.from_seq-o.from_seq);for(let s=1;s<r.length;s++){let o=r[s],i=r[s-1].harness;if(o.harness===i)continue;let a=t.findIndex(l=>l.user.seq>=o.from_seq);a<0||a===0&&t[0].user.seq!==o.from_seq||n.set(t[a].id,{harness:o.harness,previous:i,version:o.version,at:o.at})}return n}var zy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ze=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,fN=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function Fw(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=zy(t)?t.restore:void 0;if(!zy(n))return null;let r=zy(n.dropped)?n.dropped:{},s=e.grade_counts,o=[{kind:"message",count:Ze(r.message)},{kind:"attachment",count:Ze(s?.attachment)},{kind:"text",count:Ze(r.text)+Ze(n.truncated)},{kind:"tool_input",count:Ze(s?.tool_input)},{kind:"tool_result",count:Ze(r.tool_result)},{kind:"cut_point",count:Ze(s?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,l])=>fN.has(a)?i:i+Ze(l),0)}];return{generation:Ze(n.generation),missing:o.filter(i=>i.count>0)}}var Nw=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function Bw(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of Nw(r))s.ref&&s.bytes!==void 0&&!t.has(s.ref)&&t.set(s.ref,s.bytes);return[...t].map(([n,r])=>({ref:n,bytes:r}))}var Kw=(e,t)=>{let n=e.ref===void 0?void 0:t.get(e.ref);if(n===void 0)return e;let{ref:r,bytes:s,...o}=e;return{...o,text:n}},yN=(e,t)=>e.map(n=>n.type==="text"?Kw(n,t):n),Lw=new WeakMap;function hN(e,t){let n=Lw.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>Nw(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?Kw(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:yN(s.result.content,t)}}:s)}:e;return Lw.set(e,{texts:t,out:r}),r}var ti=1024*1024;function qw(e){return e.reduce((t,n)=>t+n.bytes,0)>ti?"download":"inline"}function Gw(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>ti)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function Ww(e,t){if(t.size===0)return e;let n=e.messages.map(r=>hN(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function _N(e){return e==="TIMEOUT"||e==="request_deadline"}function bN(e){let t=Vw(e)?e.code:void 0;return typeof t=="string"?t:void 0}var Vw=e=>typeof e=="object"&&e!==null;function Hw(e){let t=e?.metadata;return!!Vw(t)&&t.warm===!0}var SN=5,PN=2e3,xN=e=>new Promise(t=>setTimeout(t,e));async function wN(e,{attempts:t=SN,delayMs:n=PN,sleep:r=xN}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function kN(e,t){let n=new Map,r=new Set,s=new Set,o=new Set,i=0,a=(l,p,d)=>{if(r.has(l)||n.has(l))return Promise.resolve();r.add(l);let g=i,m=(async()=>{let f=null;try{let h=await e.ensure(l,p);if(g!==i)return;s.has(h.sessionId)?f=h.sessionId:n.set(l,h)}catch{}finally{g===i&&r.delete(l)}f&&d>0&&await a(l,f,d-1)})();return o.add(m),m.finally(()=>o.delete(m)),m};return{ensure:(l,p)=>a(l,p?.excludeSessionId,1),take:(l,p,{replenish:d})=>{let g=n.get(l);return g?(n.delete(l),s.add(g.sessionId),d&&a(l,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(l,p,d)=>{try{return await e.claim(l,d),!0}catch(g){return _N(bN(g))?wN(async()=>!Hw(await e.read(l,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:l=>{for(let[p,d]of n)if(d.sessionId===l)return n.delete(p),s.add(l),p;return null},revalidate:async l=>{let p=n.get(l);if(!p)return!1;try{if(Hw(await e.read(l,p.sessionId)))return!1}catch{return!1}return n.get(l)?.sessionId!==p.sessionId?!1:(n.delete(l),s.add(p.sessionId),!0)},held:l=>n.get(l)??null,reset:()=>{i+=1,n.clear(),r.clear(),s.clear()},settled:async()=>{for(;o.size>0;)await Promise.all([...o])}}}var vN=12e4,ni=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},AN=1e3,RN=15e3,zw=100,CN=50,TN=10;function Yw(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let i=new URLSearchParams({limit:String(r)});s&&i.set("before",s);let a=await e.getToken?.(),l=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!l.ok)throw l.status===503?new qr(`session ${l.status}`):new x(`Session synchronization failed: ${l.status}`,{status:l.status});return{messages:await l.json(),nextCursor:l.headers.get("x-next-cursor")||void 0}}}function Jw(e){return IN(Yw(e))}function Qw(e){return new Yy({...e,loadPage:Yw(e)})}async function IN(e){let t=[],n=new Set,r;do{let i=await e({limit:zw,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])o.has(a.info.id)||(o.add(a.info.id),s.push(a));return s}var EN={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Yy=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??EN,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??vN,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed||t==="visible"&&this.streamReliable&&this.snapshot.freshness==="fresh"?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":this.snapshot.freshness}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof ni;if(!r&&Br(n))return;if(r||this.update({freshness:bn(n)?"loading":"error"}),n instanceof x&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(AN*2**this.retryAttempt,RN);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?CN:zw,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,s=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",s,{once:!0});let o,i=new Promise((l,p)=>{o=this.startTimer(()=>{let d=new ni(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(l){a=Promise.reject(l)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(o),n.removeEventListener("abort",s)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let i=[...t.messages],a=new Set(this.knownUserMessageIds),l=new Set(s?[s]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<TN&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(l.has(p))throw new Error(`Session history cursor repeated: ${p}`);l.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw o?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,o?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,i=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};var MN=5e3,Zw=40,OX=5*6e4,ON=16,zr=new Map;function ek(e,t,n,r=Date.now()){let s=tk(e,t);for(zr.delete(s),zr.set(s,{envelope:n,atMs:r});zr.size>ON;){let o=zr.keys().next().value;if(o===void 0)break;zr.delete(o)}}var Xw=new Map;function tk(e,t){return`${e}/${t}`}function DN(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=MN}function nk(e,t,n=Date.now()){if(!e||!t)return null;let r=tk(e,t),s=Xw.get(r);return s?DN(s,n)?s.promise:(Xw.delete(r),null):null}function rk(e){let t=e.transcript;if(!t||t.known!==!0||t.requested!==!0)return null;let{known:n,requested:r,...s}=t;if(!s.available)return s;let o=e.session?.runtime_session_id??e.session?.opencode_session_id,i=s.runtime_session_id??s.opencode_session_id;return o&&i===o?s:null}var sk=Object.freeze({generation:0,session:{},threads:{},messages:{},revs:{},older:{}});function jN(e,t){let n=(e[t.thread_id]??[]).filter(s=>s.message_id!==t.message_id),r=n.length;for(;r>0&&n[r-1].seq>t.seq;)r--;return n.splice(r,0,t),{...e,[t.thread_id]:n}}function ok(e,t,n){let r=e.messages,s=e.older,o=t.thread_id,i=o===null?void 0:r[o];if(o!==null){let p=t.messages[0]?.seq;(n!==void 0||!i?.length||!t.has_more||p!==void 0&&p<=i[0].seq)&&e.older[o]!==t.has_more&&(s={...s,[o]:t.has_more})}if(o!==null&&i){let p=t.has_more?t.messages[0]?.seq??1/0:-1/0,d=n??1/0,g=new Set(t.messages.map(f=>f.message_id)),m=i.filter(f=>f.seq<p||f.seq>=d||g.has(f.message_id)||e.revs[f.message_id]!==void 0);m.length!==i.length&&(r={...r,[o]:m})}for(let p of t.messages)!El(p)||e.revs[p.message_id]!==void 0||(r=jN(r,p));let a={...e.threads};for(let p of t.threads)Ml(p)&&(a[p.thread_id]=p);let l=t.generation>e.generation;return{...e,generation:Math.max(t.generation,e.generation),session:l?{...e.session,...t.session}:{...t.session,...e.session},threads:a,messages:r,older:s}}var LN=2e3;async function $N(e,t,n){let r=nk(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??LN,null)})]).finally(()=>clearTimeout(s)):null;return(o&&rk(o))??Hn(e,t,{limit:Zw,history:!0,signal:n.signal})}async function ak(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};if(e.sessionLog){let o=Gn?await t_(Gn,t,n):null,i=o&&ow(ok(sk,o));return{envelope:null,empty:!!i?.empty&&i.runtimeSessionId===r&&await ik(t,n,r),log:o}}let s;try{s=await $N(t,n,{})}catch{return{envelope:null,empty:!1}}return ek(t,n,s),Jy(s)!==r?{envelope:s,empty:!1}:{envelope:s,empty:await ik(t,n,r)}}async function ik(e,t,n){try{let r=await Vn(e,t);return Qy({savedEmptyRoot:n,rootSessionId:n,turnRead:!0,hasEndedTurn:r.last_ended!=null,hasOpenOrQueuedTurn:r.turns.length>0})}catch{return!1}}function Jy(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 Qy(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function UN(e){throw N("buildTunnelEventStreamUrl")}function FN(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:l,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(b,O){o?.(b,O);let y=d.get(b);if(y)for(let w of y)try{w(O)}catch{}}async function S(){if(m)return;let b=new AbortController;g=b,p&&(p.aborted?b.abort():p.addEventListener("abort",()=>b.abort(),{once:!0}));let O=b.signal;try{let y={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(y["Content-Type"]="application/json"),f&&(y["Last-Event-ID"]=f);let w=await fetch(t,{method:r,headers:y,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:O,credentials:"include"});if(!w.ok)throw new Error(`SSE connection failed: ${w.status} ${w.statusText}`);if(!w.body)throw new Error("SSE response has no body");i?.();let P=w.body.getReader(),k=new TextDecoder,C="",j="message",R=[],L=D=>{if(D===""){R.length>0&&h(j,R.join(`
|
|
98
|
-
`)),j="message",R=[];return}if(D.startsWith(":"))return;let q=D.indexOf(":"),W=q===-1?D:D.slice(0,q),K=q===-1?"":D.slice(q+1);K.startsWith(" ")&&(K=K.slice(1)),W==="event"?j=K.trim()||"message":W==="data"?R.push(K):W==="id"&&!K.includes("\0")&&(f=K)},pe=D=>{let q="";!D&&C.endsWith("\r")&&(q="\r",C=C.slice(0,-1));let W=C.split(/\r\n|\n|\r/);C=(W.pop()??"")+q;for(let K of W)L(K)};for(;!m;){let{done:D,value:q}=await P.read();if(D)break;C+=k.decode(q,{stream:!0}),pe(!1)}m||(C+=k.decode(),pe(!0),l?.())}catch(y){if(m||y instanceof DOMException&&y.name==="AbortError")return;a?.(y instanceof Error?y:new Error(String(y)))}}function v(){m=!0,g?.abort(),g=null,d.clear()}function T(b,O){let y=d.get(b)??new Set;y.add(O),d.set(b,y)}function _(b,O){d.get(b)?.delete(O)}return{connect:S,close:v,addEventListener:T,removeEventListener:_}}function NN(e,t){throw N("createTunnelEventStream")}var ck="/_kortix/viewer",ri=6e4,wn=new Map;function lk(){wn.clear(),Yr.clear()}async function BN(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 Xy(e={}){let t=e.path??ck,n=e.fetch??((o,i)=>fetch(o,i)),r=wn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=BN(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-ri:Date.now()+ri;return wn.set(t,{session:o,expiresAt:a}),o});return wn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function uk(e={}){let t=e.path??ck;return Object.assign(async()=>(await Xy(e))?.access_token??null,{invalidate:n=>{let r=wn.get(t);r&&!r.inflight&&r.session?.access_token===n&&wn.delete(t)}})}var Yr=new Map;async function KN(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let o=await n.json().catch(()=>null);o?.error==="app_not_linked"&&console.warn(`[kortix] ${String(o.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let s=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return Yr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-ri:Date.now()+ri}),r.token}catch{return null}}function Zy(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((s,o)=>fetch(s,o));return async(s={})=>{let o=Yr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=KN(n,r).then(a=>(a===null&&Yr.delete(n),a));return Yr.set(n,i),i}}function pk(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:`${le(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:Zy({audience:e,fetch:t.fetch})}}var yt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},Pe=e=>typeof e=="string"&&e.length>0?e:null;function dk(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function si(e){if(!e||typeof e!="object")return null;let t=e,n=Pe(t.sub)??Pe(t.subject)??Pe(t.user_id)??Pe(t.userId);return n?{userId:n,email:Pe(t.email),name:Pe(t.name),picture:Pe(t.picture)??Pe(t.pictureUrl),groups:dk(t.groups),groupIds:dk(t.group_ids??t.groupIds),role:Pe(t.role),accountId:Pe(t.account_id)??Pe(t.accountId),projectId:Pe(t.project_id)??Pe(t.projectId)}:null}function mk(e,t={}){let n=si(e);if(!n)throw new yt("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:s}=t;if(r&&!r.some(o=>n.groups.includes(o)||n.groupIds.includes(o)))throw new yt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new yt("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var qN=60,eh=new Map;function fk(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 gk(e){return JSON.parse(new TextDecoder().decode(fk(e)))}async function GN(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),s=e.slice(n+1),o=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(s),i=>i.charCodeAt(0))):decodeURIComponent(s);return JSON.parse(o)}if(/^https?:\/\//.test(e)){let n=eh.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(()=>eh.delete(e)),eh.set(e,n)),n}return JSON.parse(e)}async function yk(e,t={}){let n=b=>{throw new yt("unauthenticated",`Kortix sign-in token refused: ${b}.`)},r=t.jwks??st("KORTIX_AUTH_JWKS"),s=t.issuer??st("KORTIX_AUTH_ISSUER"),o=t.audience??st("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(o!==!1&&!o)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,l,p]=i,d,g;try{d=gk(a),g=gk(l)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await GN(r,t.fetch??((b,O)=>fetch(b,O)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(b=>b.kty==="EC"&&(d.kid===void 0||b.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${l}`),S;try{S=fk(p)}catch{return n("malformed")}let v=!1;for(let b of f)try{let{kid:O,alg:y,use:w,key_ops:P,...k}=b,C=await crypto.subtle.importKey("jwk",k,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},C,S,h)){v=!0;break}}catch{}if(!v)return n("bad signature");let T=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+qN<T)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let b=g.aud;if(!(b===o||Array.isArray(b)&&b.includes(o)))return n("wrong audience")}let _=si(g);return _||n("no subject")}function th(e){let t=e.agents.map(WN),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function WN(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.hidden===!0||e.enabled===!1}}function nh(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Qs(n?{...r,mode:null}:r))}function hk(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let o=e.selectedAgent?.trim();return o?{selected:o,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=nh(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(o=>o.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let s=e.defaultAgent?.trim();return s&&n.some(o=>o.name===s)?{selected:s,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var _k=th;function bk(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function rh(e){return{providerID:"kortix",modelID:e}}function kn(e,t){return rh(e.startsWith("kortix/")?e.slice(7):e)}var Sk=[{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"amd",env:["AMD_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"infer",env:["INFER_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"liquid",env:["LIQUID_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"bee",env:["BEE_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]}];function sh(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function VN(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function Pk(e,t){let n=new Map;for(let r of e){let s=t(r),o=n.get(s);o?o.push(r):n.set(s,[r])}return n}function Jr(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 xk(e){return e.reduce((t,n)=>{let r=sh(n)??0,s=sh(t)??0;return r!==s?r>s?n:t:Jr(n.id)>Jr(t.id)?n:t})}function oh(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of Pk(e,VN)){let a=[...Pk(o,p=>p.family||p.id).values()].map(xk),l=a.filter(p=>{let d=sh(p);return d!==null&&Math.abs(n-d)<r});for(let p of l.length>0?l:[xk(a)])s.add(p.id)}return s}function ih(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=>Jr(r.id)>0)?n.filter(r=>Jr(r.id)>0):n}var wk={id:"platinum",name:"Platinum",env:["PLATINUM_API_KEY"],doc:"https://platinum.dev",api:"https://api.platinum.dev/v1/inference",npm:"@ai-sdk/openai-compatible",models:[]},kk=[...Sk,{id:wk.id,env:wk.env}],zN={"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 vk(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var YN=(()=>{let e=new Map;for(let{id:n,env:r}of kk)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let s=[...r].sort((o,i)=>o.length-i.length||o.localeCompare(i));t.set(n,r.find(o=>vk(o)===n)??s[0])}return t})();function Ak(e){let t=zN[e.id];if(t)return t;let n=e.env??[],r=n.length===1?YN.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[vk(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}var JN=["low","medium","high"];function Rk(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:[...JN]}:void 0,s=e.temperature===!0,o=e.limit?.output,i=typeof o=="number"&&o>0?{ceiling:o}:void 0;return{reasoningEffort:r,temperature:s,topP:s,maxOutputTokens:i}}var Ck=kk;var c4=Ck.map(e=>({id:e.id,authRequirement:Ak(e)})),Tk=new Set(["kortix"]);function QN(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,s])=>{if(s.variants&&Object.keys(s.variants).length>0)return[r,s];let o=Rk({id:r,name:s.name,reasoning:s.reasoning,reasoning_options:s.reasoning_options}).reasoningEffort?.values;return o?.length?[r,{...s,variants:Object.fromEntries(o.map(i=>[i,{}]))}]:[r,s]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function Ik(e){return e.modelPicker?QN(e.modelPicker):void 0}function XN(e){return"capabilities"in e&&e.capabilities!=null}function oi(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1&&n.available!==!1}function Ek(e,t){if(!e)return[];let n=Array.isArray(e.all)?e.all:[],r=Array.isArray(e.connected)?e.connected:[],s=[];for(let o of n)if(r.includes(o.id)&&Tk.has(o.id))for(let[i,a]of Object.entries(o.models)){if(i==="auto"||i==="kortix/auto")continue;let l;if(XN(a)){let p=a.capabilities;l={reasoning:p.reasoning??!1,vision:p.input?p.input.image??!1:void 0,toolcall:p.toolcall??!1}}else{let p=a.modalities?.input;l={reasoning:a.reasoning??!1,vision:p?p.includes("image"):a.attachment,toolcall:a.tool_call??!1}}s.push({id:bk({providerID:o.id,modelID:i}),providerID:o.id,providerName:a.provider_name??o.name,modelID:i,modelName:(a.name||i).replace("(latest)","").trim(),variants:a.variants,capabilities:l,contextWindow:a.limit?.context,releaseDate:a.release_date,family:a.family,cost:a.cost?{input:a.cost.input??0,output:a.cost.output??0}:void 0,providerSource:o.source,provider:a.provider,reasoningOptions:a.reasoning_options,description:a.description,openWeights:a.open_weights,lastUpdated:a.last_updated,enabled:a.enabled,free:a.free===!0,available:a.available,availability:a.availability})}return s}function Mk(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var Dk="kortix",Ok="codex";function jk(e){return e.providerID===Dk&&!e.modelID.includes("/")}function ZN(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function vn(e){return jk(e)}function eB(e){return oh(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function Lk(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=eB(e.catalogModels),s=Mk(e.catalogModels),o=new Map;for(let i of e.pins??[])o.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,l=o.get(a);if(l==="hide")return!1;if(i.providerID===Dk){let d=ZN(i.modelID,i.provider),g=d===Ok?t?.has(Ok)??!1:t?.has(d)??!1;if(jk(i))return!n;if(!g)return!1;if(l==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return vn(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return vn(i)}catch{return vn(i)}return!1}if(l==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return vn(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return vn(i)}catch{return vn(i)}return!1}}function $k(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 Uk(e,t){let r=(t?e?.agentDefaults?.[t]:void 0)??(e?.resolvedForCaller!==void 0?e.resolvedForCaller:e?.projectDefault??e?.accountDefault??(e?.freeTier?void 0:e?.platformDefault));return r?rh(r):void 0}function Fk(e){for(let t=(e?.length??0)-1;t>=0;t--){let n=e[t],{provider:r,model:s}=n.model??{};if(n.role==="user"&&r&&s)return{providerID:r,modelID:s}}}var tB=new Set(["explicit","repointed","fallback"]);function Nk(e){let t=e?.metadata;if(t?.opencode_model_source!=="fallback")return;let{opencode_model:n,opencode_model_fallback_from:r,opencode_model_fallback_at:s}=t;if(typeof n!="string"||typeof r!="string"||typeof s!="number")return;let o=t.opencode_model_fallback_reason;return{model:kn(n),from:kn(r),reason:typeof o=="string"?o:"other",atMs:s}}function Bk(e,t){return!t||(e??-1)>=t.atMs}function Kk(e){let t=e.session?Qn(e.session):null,n=t?kn(t):void 0,r=e.session?.metadata;return(tB.has(String(r?.opencode_model_source))||r?.opencode_model_restored===!0?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(i=>!!i)}function qk(e){let{models:t,providers:n}=e,r=l=>oi(t,l),s=l=>l.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let l=e.configModel.split("/");if(l.length>=2){let[p,...d]=l,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let l of e.recent??[])if(r(l))return l;if(n){let l=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=l[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of ih(Object.keys(m.models).map(S=>({id:S})))){let S={providerID:m.id,modelID:h.id};if(r(S))return S}}}})(),i=s(e.picks??[]);return{model:i??s([e.serverDefault,e.globalDefault,e.agentModel,o]),explicit:i,fallback:o}}return Jk(nB);})();
|
|
96
|
+
`),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let l=0;l<s;l++)a.push({type:"unchanged",text:n[l]});for(let l=s;l<o;l++)a.push({type:"removed",text:n[l]});for(let l=s;l<i;l++)a.push({type:"added",text:r[l]});for(let l=o;l<n.length;l++)a.push({type:"unchanged",text:n[l]});return a}function H$(e){let t=Eo(e.input),n=t.map(([s,o])=>W$(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:Oy(e),diff:r}}var dP=/^Found\s+(\d+)\s+match/i,V$=/^(\/[^:]+?):\s*/,pP=/Line\s+(\d+):/g;function z$(e){let t=e.trim(),n=t.match(dP),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let s=[];for(let o of r.split(/\n\n+/)){let i=o.trim();if(!i)continue;let a=i.match(V$);if(!a)continue;let l=a[1],p=i.slice(a[0].length),d=[],g;for(pP.lastIndex=0;(g=pP.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,f).trim();s.push({path:l,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return s}function Y$(e){return e.trim().split(`
|
|
97
|
+
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function J$(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=dP.test(e.output.trim())?z$(e.output):Y$(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function Q$(e){let t=ne(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=ne(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function Ey(e){let t=hn(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function X$(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(Ey)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(Ey)};let n=hn(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(Ey)}:{kind:"todo",items:[]}}function Z$(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=hn(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let l=hn(a),p=l&&ne(l.label);return p?[{label:p,description:l?ne(l.description):void 0}]:[]});return{question:ne(s.question)??"",header:ne(s.header),options:i}})}}function e0(e){let n=e.input&&Object.keys(e.input).length>0?uP(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Br(e.outputParsed):uP(e.outputParsed):e.outputText!==void 0?r=Br(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function gP(e){switch(ae(e.name)){case"web_search":return L$(e);case"bash":return B$(e);case"read":return K$(e);case"write":return q$(e);case"edit":return H$(e);case"grep":case"glob":return J$(e);case"task":return Q$(e);case"todowrite":return X$(e);case"question":return Z$(e);default:return e0(e)}}var t0=new Set(["AbortError","MessageAbortedError"]),n0=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],r0=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function mP(e){let t=e.toLowerCase();return r0.some(n=>t.includes(n))?!1:n0.some(n=>t.includes(n))}function s0(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 Kr(e){if(typeof e=="string")return mP(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&t0.has(n))return!0;let r=s0(t);return typeof r=="string"?mP(r):!1}var fP=["user","runtime-disposed","orphan-finalized","wake"],o0=["orphan-finalized","wake"];function i0(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 fP.includes(n)?n:void 0}var qr="kortix-active-instance",yP=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function hP(e){return yP.some(t=>e===t||e.startsWith(`${t}/`))}function _n(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 a0(e){let t=_n(e);return!!t&&t.innerPath===""}function c0(e){let t=_n(e);return!t||!t.innerPath?e:t.innerPath}function _P(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=_n(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return hP(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function bP(e){return e?_n(e)?.instanceId??null:null}function l0(){return typeof window>"u"?null:bP(window.location.pathname)||SP()}function SP(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${qr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function u0(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${qr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${qr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${qr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function p0(e,t){return t?_P(t,e):e}function d0(e){let t=_n(e);return t?t.innerPath||"/dashboard":e}function Wr(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 Dy(e){let t=Wr(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}var g0=Dy;function Vo(e){let t=Dy(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var m0=Vo;function xP(e){return Vo(e)!==null}var f0=xP,y0=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],h0=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],_0=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function PP(e){return _0.test(Wr(e))}function bn(e){let t=Wr(e);return t?PP(t)||y0.some(n=>n.test(t)):!1}var b0=/server url not ready|sandbox is still loading/i;function S0(e){return b0.test(Wr(e))||bn(e)}var Gr=class extends Error{constructor(t){let n=t?.trim();super(n&&bn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function wP(e){let t=Vo(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${a}`,detail:o?`${i?`${i}: `:""}${o}`:void 0}}let n=Wr(e);return bn(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 x0=wP;function jy(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`${ot()}/p/${e.external_id}/${Ke.KORTIX_MASTER}`}function P0(e,t){return e.external_id?`${ot()}/p/${e.external_id}/${t}`:null}async function w0(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function kP(e){let t=await tr();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Pt())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await Rt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await nt(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Bs(r,s,o),created:!0}}async function k0(){return(await tr().catch(()=>null))?.sandbox??null}async function v0(e){return{sandbox:(await kP(e)).sandbox}}async function A0(e){let t=er(e);if(!t)return null;try{let n=await rm(t);return n?Bs(await wt(n.project_id),n,null):(await tr(t))?.sandbox??null}catch{return null}}async function R0(e,t){throw await Ks(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function C0(e){let t=er(e);return(await nm().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function T0(){return null}async function I0(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Ks(e);if(!t)throw new Error("Project session sandbox not found");await Yn(t.projectId,t.sessionId)}async function E0(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Ks(e);if(!t)throw new Error("Project session sandbox not found");await Jn(t.projectId,t.sessionId)}async function M0(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function O0(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function Ly(e,t,n){let r=jy(e),s=await $(`${le(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function D0(e,t){return Ly(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function j0(e,t,n,r="member"){await Ly(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function L0(e,t,n){await Ly(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var $y="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function $0(e){throw N("getInvite",$y)}async function U0(e){throw N("acceptInvite",$y)}async function F0(e){throw N("declineInvite",$y)}async function N0(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function B0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function K0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function q0(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function G0(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function W0(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var vP=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function H0(e){return vP.includes(e)}async function V0(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 z0(e){let t=e?`?channel=${e}`:"",r=await(await Le(`${ot()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await AP(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function AP(e){let t=e?`?channel=${e}`:"";return(await(await Le(`${ot()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function Y0(){return(await Le(`${ot()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function J0(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function Q0(e){}async function X0(e){}async function Z0(e){return{serverTypes:[],location:e||"hel1"}}async function eU(e){throw new Error("Retired instance provisioning is unavailable. Create a project session on platinum (or the legacy daytona fallback).")}async function tU(e){throw N("deleteInstance")}async function nU(e,t){}async function rU(){throw N("claimComputer")}async function sU(e){return null}function oU(e,t){throw N("getSandboxProvisionStreamUrl")}var Hr=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function RP(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 CP(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function TP(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 te(e,t,n){let r=n?.body!==void 0,s=await fetch(`${qe(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:RP(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await CP(s);if(!s.ok)throw new Hr(TP(s,o),s.status,o);return o}function iU(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 aU(e,t){return te(`/marketplace/items${iU(t)}`,e)}function cU(e){return te("/marketplace/marketplaces",e)}function lU(e,t){return te(`/marketplace/items/${encodeURIComponent(e)}`,t)}function uU(e,t,n){return te(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function pU(e,t){return te("/access/check-email",t,{method:"POST",body:{email:e}})}function dU(e,t){return te("/access/request-access",t,{method:"POST",body:e})}function gU(e){return te("/auth/logout",e,{method:"POST",body:{}})}function mU(e,t){return te(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function fU(e,t){return te("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function yU(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function hU(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function _U(e,t,n={}){return te(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function bU(e,t){return te(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function SU(e,t,n,r){return te(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function xU(e,t){return te(`/p/public-share/${encodeURIComponent(e)}`,t)}function PU(e,t,n){return te(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function wU(e){return te("/system/maintenance",e)}function kU(e,t){return te("/system/maintenance",t,{method:"PUT",body:e})}function vU(e){return te("/user-roles",e)}function AU(e,t){return te("/system/demo-request",t,{method:"POST",body:e})}async function RU(e,t,n){let r=await fetch(`${qe(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Ht(t)}`,{headers:RP(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await CP(r);throw new Hr(TP(r,s),r.status,s)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function CU(e,t){throw N("openStressTestStream")}function TU(e,t){throw N("buildPublicTemplateUrl")}async function IU(e,t,n){throw N("getPublicTemplate")}var EU="kortix:connect-link:";function Uy(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);t=Math.imul(t^s,16777619)>>>0,n=Math.imul(n^s,1540483477)>>>0}return`${EU}${t.toString(36)}${n.toString(36)}`}function MU(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(Uy(i));if(!a)return;let l=JSON.parse(a);if(Date.parse(l.expires_at)<=Date.now()){t.removeItem(Uy(i));return}return l}catch{return}},o=(i,a)=>{if(t)try{t.setItem(Uy(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let l=s(i);return l&&r.set(i,l),l},load(i){let a=n.get(i);if(a)return a;let l=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,l),l}}}var IP="Could not start the connect flow.";async function OU(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:IP}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:IP};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var EP=3e3,MP=5e3,OP=5*6e4;function DU(e,t){let n=e===0?EP:MP;return t+n>OP?null:n}function jU(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 LU(){let e=await c.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function $U(e={}){let t=await c.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function UU(e){let t=await c.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function FU(e){let t=await c.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function NU(){let e=await c.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var NJ="1";var BU="kortix.query-cache";function jP(e){return!!e&&typeof e.then=="function"}function DP(e){return jP(e)?e:Promise.resolve()}function KU(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 qU(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:l=BU,now:p=()=>Date.now()}=e,d=`${l}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),S=()=>{try{return DP(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},v=(x,k)=>{if(!k)return 0;let C;try{C=JSON.parse(k)}catch{return S(),0}if(!C||C.v!==s||C.user!==n||!Array.isArray(C.queries)||p()-C.at>o)return S(),0;let j=0;for(let R of C.queries){if(!R||!Array.isArray(R.k)||R.d===void 0||typeof R.t!="number"||p()-R.t>o||!r(R.k))continue;let L=x.getQueryState(R.k);L&&L.data!==void 0&&L.dataUpdatedAt>=R.t||(x.setQueryData(R.k,R.d,{updatedAt:R.t}),x.invalidateQueries?.({queryKey:R.k,exact:!0,refetchType:"none"}),j+=1)}return j},T=x=>x.getQueryCache().getAll().filter(k=>k.state.data!==void 0&&r(k.queryKey)).map(k=>({k:k.queryKey,d:k.state.data,t:k.state.dataUpdatedAt})).sort((k,C)=>C.t-k.t),_=(x,k)=>{let C=[],j=0;for(let R of x){let L=JSON.stringify(R).length+1;j+L>k||(C.push(R),j+=L)}return C},b=async x=>{let k=_(T(x),i);for(;;){let C={v:s,user:n,at:p(),queries:k};try{await DP(t.setItem(d,JSON.stringify(C)));return}catch{if(k.length===0)return;k=k.slice(0,Math.floor(k.length/2))}}},O=()=>{f!==null&&(clearTimeout(f),f=null)},y=()=>{O();let x=g;return!x||!m||(m=!1,h=h.then(()=>b(x)).catch(()=>{})),h},w=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,y()},a))};return{storageKey:d,restore(x){let k;try{k=t.getItem(d)}catch{return 0}return jP(k)?k.then(C=>v(x,C)).catch(()=>0):v(x,k)},persist(x){g=x,m=!0;let k=x.getQueryCache().subscribe(C=>{C.type!=="updated"&&C.type!=="removed"&&C.type!=="added"||r(C.query.queryKey)&&w()});return()=>{k(),g===x&&(g=null,O())}},flush(){return y()},async clear(){O(),g=null,m=!1,await h,await S()}}}function GU(){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 LP="/kortix/part/";function $P(e){return typeof e=="string"&&e.startsWith(LP)}async function WU(e){if(!$P(e))throw new Error(`not an attachment part reference: ${e}`);let t=ze();if(!t)throw new Error("runtime url not bound");let n=await $(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function UP(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 HU(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.has(n.origin)}catch{return!1}}function Fy(e,t){return HU(e,t)?(t?UP(t):null)??UP(e):null}function Vr(e){try{let{hostname:t}=new URL(e);return/^p\d+-[^.]+\./.test(t)||/^(?:dev|staging|prod|preview)-p\d+-[a-z0-9-]+\./i.test(t)}catch{return!1}}function VU(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var zU=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function YU(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function JU(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let s=(t.slice(n+3).split("/")[0]??"").toLowerCase(),o=`${r}://${s}`.split("{port}").map(i=>i.split("{sandbox}").map(YU).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function QU(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function FP(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function XU(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:zU.test(n.hostname)?t.backendUrls.some(r=>{let s=QU(r);return s!==null&&FP(s)===FP(n)}):t.templates.some(r=>JU(n.origin,r))}async function NP(e,t={}){if(!Vr(e))return!1;let n=I().backendUrl;n&&await it(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return XU(e,{templates:ib(),backendUrls:r})}async function BP(e,t={}){let n=Fy(e,t.serverUrl||I().backendUrl||void 0);if(!n)return!1;let r=await Ft();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 ZU(e,t={}){if(Vr(e)){if(!await NP(e,t)||!await Ft())return e;let r=await c.post("/p/ticket",{preview_url:e}),s=r.data;if(!r.success||!s||typeof s.ticket!="string"||!s.ticket)throw new Error("Preview authorization failed");let o=new URL(e);return o.searchParams.delete("token"),o.searchParams.set("preview_ticket",s.ticket),o.toString()}return await BP(e,t),e}var eF=3e3;function KP(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 tF(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return KP(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function nF(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function rF(e,t){throw N("buildPresentationTemplatePdfUrl")}function sF(e,t){throw N("buildPresentationTemplateImageUrl")}function qP(e,t){return`${nF(e)}/presentation/convert-to-${t}`}async function oF(e,t,n,r){let s=qP(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),l=!1;for(;;){let p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(l||(l=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,S)=>{let v=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(v),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 iF(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 aF(e){return e==="unreachable"}function cF(e){return!e||e.status===0?"unknown":e.ok&&of(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var GP=1e4,lF={connection:"unknown",faultSinceMs:null};function uF(e,t,n,r=GP){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let s=e.faultSinceMs??n;return n-s>=r?{connection:t,faultSinceMs:s}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:s}}function WP({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<zo,l=!!t&&i-t.atMs<Qo;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:l,abortFloor:l?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=Yo,streamFresh:!!s&&i-s.atMs<=Sn,inboxFresh:!!n&&i-n.atMs<=Jo,activityFresh:!!o&&i-o.atMs<=Sn}}function xn(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function Ny(e,t,n){if(!t)return!1;let r=xn(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=xn(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function pF(e,t,n,r){let{activity:s,server:o}=e,{serverFresh:i,abortFloor:a,activityFresh:l}=t;return l&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!Ny(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function dF(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,l=i?s.turns.filter(g=>!Ny(g,n,s)):[],p=l.find(g=>g.state==="active")??l[0],d=!!o&&!(o.type==="idle"&&o.origin==="local");return p&&s.atMs>=a&&(!d||s.atMs>=o.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:xn(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function gF(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:l,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...l&&o.type!=="idle"&&(!p||o.atMs>s.atMs)&&o.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&s.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function mF(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:l,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,S=l&&!n&&s.atMs>=p,v=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(S&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:xn(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(v)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let T=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:a};return{state:"idle",source:T.source,turnId:null,since:T.atMs,serverOpenTurnToken:r}}function HP(e){let t=WP(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=pF(e,t,s,o);if(i)return i;let{result:a,openTurn:l}=dF(e,t,s,o);return a??gF(e,t,o)??mF(e,t,l,o)}var zo=6e4,Yo=45e3,Sn=45e3,Jo=1e4,fF=3e3,Qo=15e3;function yF(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function hF(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 _F(e){return HP(e)}function bF(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,l=[null,t?t.atMs+zo:null,n?n.atMs+Qo:null,r?r.atMs+Jo:null,s?s.atMs+Yo:null,o?o.atMs+Sn:null,i?i.atMs+Sn:null],p=null;for(let d of l)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function VP(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(o=>o.message_id===t),r=e.last_ended,s=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!s?.message||Kr({name:s.name??void 0,message:s.message})?null:s}var SF="SandboxMemoryGuard";function xF(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=VP(e,t);if(r?.message){if(r.name!==SF)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],l=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:l}}let s=e.recent_failures?.find(a=>a.message_id===t);if(!s)return null;let o=s.ended_at?Date.parse(s.ended_at):Number.NaN;return Number.isFinite(o)&&typeof e.atMs=="number"&&e.atMs-o<2500?null:{kind:"unexplained"}}var PF=6e4;function wF(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function kF(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var zP=9e4;function vF(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+zP}var AF=75e3,RF=2,CF=2e4;function By(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function TF(e){return e.filter(t=>t!=null).join("|")}function IF(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function EF(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...By(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...By(),settled:!0};let i=e.lastProgressAtMs,a=i===null,l=t.progress!==e.fingerprint,p=i===null||l?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!l&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return g;let f=IF(e.attempts,s);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var MF={"retry-start":"retrying",restart:"restarting"};function OF(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${MF[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function DF(e){return e===1?"once":e===2?"twice":`${e} times`}function jF(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(s=>s.step==="restart").length,n=e.attempts.some(s=>s.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${DF(t)}`),`Tried: ${r.join(", then ")}.`}var LF={"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 YP(e){return!!(e.metadata??{}).legacy_migration}function $F(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return e.working?.state==="idle"?"done":"running";case"completed":case"stopped":return YP(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function UF(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 FF={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 NF(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function Xo(e){return e.runtime_sessions??e.opencode_sessions??[]}function JP(e){let t=Xo(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function BF(e){let t=JP(e);return t?Xo(e).filter(n=>(n.parent_id===t.id||!n.parent_id&&n.fork_source_id)&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function KF(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>Xo(r).some(s=>s.id===t))??null)}var qF=new Set;function QP(e){for(let t of[...qF])try{t(e)}catch{}}var nw={schema:ce,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var rw=e=>Object.values(e.ext??{}).find(t=>t.version===ke),sw=e=>!!e&&rw(e)!==void 0,ow=e=>{let t=rw(e);return t?t.native_id??null:e.thread_id};function iw(e){let t=e&&Object.values(e.threads).find(r=>r.parent_thread_id===null);if(!e||!t)return null;let n=(e.messages[t.thread_id]?.length??0)>0;return{runtimeSessionId:ow(t),hasMessages:n,empty:!n&&e.older[t.thread_id]===!1}}var XP=new WeakMap;function aw(e,t){let n=ow(e),r=XP.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=zs({...nw,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return XP.set(t,{native:n,rows:o}),o}var Ky=e=>e.info.time?.created;var GF=(e,t)=>(Ky(e)??-1/0)-(Ky(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var ZP=new WeakMap,ew=new WeakMap,cw=e=>typeof e=="object"&&e!==null,WF=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,HF=e=>e.info.role==="user"&&e.parts.some(t=>cw(t)&&t.type==="compaction"),VF=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},tw=new WeakMap;function zF(e,t,n){let r=t.info,s=`${e}|${String(r.id)}|${String(r.time?.created)}`,o=!1,i=n.blocks.map((a,l)=>{let p=t.parts[l];if(!cw(p)||a.type==="compaction")return a;let d=`${s}|${l}|${a.id}`,g=tw.get(p);return g&&g.key===d?(o=!0,g.block):(tw.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function YF(e){let t=new Map,n=new Set;for(let r of e){if(!HF(r))continue;let s=e.find(o=>!n.has(o)&&VF(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function JF(e,t,n,r,s){let o=ZP.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=Ys({session_id:e,root_id:t,rows:(r?[n,r]:[n]).map(d=>({runtime_session_id:t,info:d.info,parts:d.parts}))},{live:!0}),l=zF(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:s,message:{...l,seq:s},lost:a.grade_counts};return ZP.set(n,p),p}function lw(e,t,n){let r=ew.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(GF),{paired:o,used:i}=YF(s),a={tool_input:0,cut_point:0,attachment:0},l=[];for(let m of s){if(i.has(m))continue;let f=JF(e,t,m,o.get(m),l.length+1);for(let h of["tool_input","cut_point","attachment"])a[h]+=f.lost[h];l.push(f.message)}let p=WF(s.map(Ky).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=l.filter(m=>m.role==="user"&&m.kind==="turn"),g={...nw,session_id:e,created_at:p,restore_grade:a.tool_input+a.cut_point+a.attachment>0?"partial":"converted",grade_counts:a,harness:{current:"opencode",history:[]},selection:{agent:d.at(-1)?.agent??null,model:d.at(-1)?.model??null},threads:[{schema:ce,v:1,thread_id:t,parent_thread_id:null,spawned_by:null,agent:d[0]?.agent??null,title:null,created_at:l[0]?.created_at||p,messages:l,ext:{opencode:{version:ke,native_id:t}}}]};return ew.set(n,{sessionId:e,native:t,log:g}),g}var qy=new WeakMap,Pn=new WeakMap,uw=new WeakMap;function Zo(e){let t,n=Pn.get(e);return n&&(t=QF(n).get(e.id)),t?(qy.set(t,e),t):(e.type!=="harness"?t=xm(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=uw.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},uw.set(e,t)),t&&qy.set(t,e),t)}var zr=e=>qy.get(e),Ot=e=>e.flatMap(t=>Zo(t)??[]),pw=new WeakMap;function QF(e){let t=pw.get(e);return t||pw.set(e,t=new Map(ft(e)[0]?.parts.map(n=>[n.id,n]))),t}var dw=new Map;function ft(e){let t=dw.get(e.thread_id);return t||(t={schema:ce,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},dw.set(e.thread_id,t)),aw(t,e)}var XF="kortix-v1-import",Gy={schema:ce,v:1};function ei(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var Wy=e=>e.type==="tool_call",ZF=e=>e.status==="pending"||e.status==="running",Hy=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function _w(e,t){let n=Hy(e);return!ZF(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var gw=new WeakMap;function bw(e,t){let n=gw.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),s={...Gy,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"kortix-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return gw.set(e,s),s}var mw=new WeakMap;function eN(e){let t=mw.get(e);return t||(t={...Gy,message_id:e.reply_to,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},mw.set(e,t)),t}var fw=new WeakMap;function tN(e){let t=fw.get(e);return t||(t={...Gy,message_id:`${e.message_id}:continued`,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},fw.set(e,t)),t}var nN=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function rN(e,t){let n=[],r=new Map;for(let g of e){if(g.role!=="user"||g.kind==="context"||r.has(g.message_id))continue;let m={user:g,assistant:[],partial:!1};r.set(g.message_id,m),n.push(m)}let s=[],o=[],i=new Map,a=new Map,l=null,p=null;for(let g of e){if(g.role==="user"){let S=r.get(g.message_id);S&&!t.has(g.message_id)&&(l=S,i.has(S)||i.set(S,i.size),S.user.kind==="compaction"&&(p=S));continue}if(g.role!=="assistant"||nN(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??l;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let S=a.get(p);S||(S={user:tN(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,S)),f=S}if(f){f.assistant.push(g);continue}if(!g.reply_to){o.push(g);continue}let h=s[s.length-1];h&&h.user.message_id===g.reply_to?h.assistant.push(g):s.push({user:eN(g),assistant:[g],partial:!0})}if(o.length){let g=n[0]??s[0];g?g.assistant.unshift(...o):n.push({user:o[0],assistant:o.slice(1),partial:!1})}let d=n.filter(g=>!t.has(g.user.message_id)).flatMap(g=>{let m=a.get(g);return m?[g,m]:[g]});return[...s,...d,...[...t].flatMap(g=>r.get(g)??[])]}function sN(e,t){let n=[],r=new Map,s=t;for(let o of e){let i=n[n.length-1],a=o.continues?r.get(o.continues.marker):o.user.kind==="compaction"&&i?.user.kind!=="compaction"?i:void 0;if(!a){n.push({...o,assistant:[...o.assistant]});continue}r.set(o.user.message_id,a),o.user.kind==="compaction"&&a.assistant.push(o.user),a.assistant.push(...o.assistant),t===o.user.message_id&&(s=a.user.message_id)}return{list:n,hint:s}}function oN(e,t){if(!t)return t;let n=t;for(let r of e){let s=r.continues;s&&(n===s.marker||n===s.prompt||t===s.prompt)&&(n=r.user.message_id)}return n}function Sw(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=ft(n)[0]?.info?.error??n.error.message,s=Se(r),o=Cr(r);return{code:n.error.code,message:s?.message||ye(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function iN(e,t,n){return e.length&&e.every(t)?Ho(e.flatMap(r=>ft(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:Vy(e,n)}function Vy(e,t){let n=e.flatMap(r=>{let s=r.usage;if(!s)return[];let o={type:"step-finish",cost:s.cost??0,tokens:{input:s.input,output:s.output,reasoning:s.reasoning??0,cache:{read:s.cache_read,write:s.cache_write}}};return[{part:o,message:{info:{id:r.message_id,role:"assistant",providerID:r.model?.provider,modelID:r.model?.model},parts:[o]}}]});return Ho(n,t)??null}function aN(e){if(e.kind!=="compaction")return null;let t=e.blocks.find(n=>n.type==="compaction")??null;return{block:t,hasContent:!!t?.summary?.trim(),inFlight:e.status==="streaming"}}function cN(e){let t=e.user.blocks;if(!t.length||!t.every(r=>r.type==="text"&&r.synthetic))return null;let n=e.assistant.length===1&&e.assistant[0].blocks.length===1?e.assistant[0].blocks[0]:null;return n&&Wy(n)&&n.name==="bash"?n:null}function lN(e,t,n,r){if(!n.length)return[];let s=new Set(e.assistant.map(i=>i.message_id)),o=new Set;for(let i of n)i.spawned_by&&s.has(i.spawned_by.message_id)&&o.add(i.thread_id);for(let i of t){let a=i.type==="subtask"?i.thread_id:Wy(i)?Or(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var uN=e=>e.assistant.some(t=>t.blocks.some(n=>Wy(n)&&ae(n.name)==="todowrite"&&gn(n))),pN=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function dN(e,t){let n=e.map(s=>Sw(s)!==null),r=e.map((s,o)=>n[o]===!0&&t[o+1]===!0);return e.map((s,o)=>{if(r[o])return{continued:!0,retries:0};if(!n[o])return;let i=0;for(let a=o-1;a>=0&&r[a];a--)i+=1;return i>0?{continued:!1,retries:i}:void 0})}var yw=new WeakMap,gN=[];function zy(e){let t=ei(e.messages,n=>n.role==="assistant");return!!t&&ly(ft(t))}var hw=new WeakMap;function mN(e){let t=hw.get(e);if(!t){let n=e.messages.filter(r=>r.in_context||r.status==="streaming");t=n.length===e.messages.length?e:{...e,messages:n},hw.set(e,t)}return t}function ti(e,t={}){let n=t.hideOutOfContext?mN(e):e,r=new Set(t.held??gN),s=rN(n.messages,r),o=oN(s,t.liveMessageId),{list:i,hint:a}=t.foldCompactions?sN(s,o):{list:s,hint:o},l=ei(n.messages,_=>_.role==="assistant"),p=zy(n),d=wy({turns:i.map(_=>({userMessage:{info:{id:_.user.message_id}},assistantMessages:_.assistant.map(b=>({info:{time:b.status==="streaming"?{}:{completed:1},error:b.error??void 0}}))})),hintMessageId:a,unrunTurnIds:r}),g=ei(i,uN)??i[i.length-1],m=i.map(_=>!_.partial&&pN(_.user)),f=dN(i,m),h=sw(n),S=_=>h||_.producer.harness===XF,v=t.threads??[],T=new Set(v.map(_=>_.thread_id));return i.map((_,b)=>{let O=t.busy===!0&&d.workingTurnId===_.user.message_id,y=d.pendingTurnIds.includes(_.user.message_id),w=p&&_.assistant.includes(l),x=f[b],k=`${_.partial}|${O}|${y}|${_===g}|${w}|${x?(x.continued?"c":"")+x.retries:"-"}`,C=yw.get(_.user);if(C&&C.key===k&&C.pricing===t.pricing&&C.heads===t.threads&&C.assistant.length===_.assistant.length&&C.assistant.every((D,q)=>D===_.assistant[q]))return C.turn;let j=_.assistant.flatMap(D=>D.blocks);for(let D of _.assistant)for(let q of D.blocks)Pn.set(q,D);let R=lN(_,j,v,T),L=_.assistant[_.assistant.length-1],pe={internal:m[b],autoRetry:x,id:_.user.message_id,user:_.user,assistant:_.assistant,partial:_.partial,continues:_.continues??null,blocks:j,status:w?"streaming":L?L.status:_.user.kind==="compaction"?_.user.status:"pending",error:Sw(_),cost:iN([_.user,..._.assistant],S,t.pricing),compaction:aN(_.user),threads:R,plan:_===g,shell:cN(_),response:ei(j,D=>D.type==="text"&&!!D.text.trim())??null,attachments:_.user.blocks.filter(D=>D.type==="attachment"&&(D.mime.startsWith("image/")||D.mime==="application/pdf")),live:O,queued:y,retrying:w};return yw.set(_.user,{assistant:_.assistant,key:k,pricing:t.pricing,heads:t.threads,turn:pe}),pe})}var Yy=e=>zr(e);function kw(e,t={}){return Sy(by(Ot(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(zr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Yy)}:n.kind==="text"?{kind:n.kind,block:zr(n.part)}:{kind:n.kind,block:Yy(n.part)})}var fN=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:Ot(e.blocks)}:{kind:e.kind,part:Zo(e.block)};function vw(e,t){let n=new Map(e.map(o=>[fN(o),o])),r=Ty([...n.keys()],t);if(!r)return null;let s=o=>o.map(i=>n.get(i));return{work:s(r.work),hoisted:s(r.hoisted),final:s(r.final)}}function yN(e){if(!ee(e)||!Pm(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=sy(e);return(n.answers??Iy(n.outputText??"",t.length)??[]).length>0}function Aw(e){return _y(Ot(e),n=>yn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(yN)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:zr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Yy),family:n.step.family,label:n.step.label,status:n.step.status,durationMs:n.step.durationMs};let r=e.find(o=>o.id===n.key.slice(8)),s=r&&Pn.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function Rw(e,t){return vy(Ot(e.blocks).map(n=>({part:n})),t?.flatMap(ft))}function Cw(e){return Ko(Ot(e))}function Tw(e){return yy(Ot(e))}function Iw(e,t){return t.working?t.trailing?!0:e.some(n=>{if(n.type==="tool_call")return n.status==="pending"||n.status==="running";if(n.type!=="reasoning")return!1;let r=Zo(n),s=Pn.get(n);return!!r&&we(r)&&qo(r)&&(!s||s.status==="streaming")}):!1}var xw=new WeakMap;function Ew(e){if(!Hy(e))return e;let t=xw.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},xw.set(e,t)}return t}function hN(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function Mw(e){let t=e.map(oe),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=xy(t).map(hN);return lr({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function Ow(e,t,n){let r=oe(e),s=r.state;return lr({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function Dw(e){let t=ft(e).map(r=>jo(r)),n=t.find(r=>r.error)?.error;return{parts:t.flatMap(r=>r.parts),error:n,isEmpty:t.every(r=>r.isEmpty)&&!n}}var Pw=Object.freeze([]),ww=new WeakMap;function jw(e){if(!e)return Pw;let t=ww.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&gn(s)):[]);t=n.length?n:Pw,ww.set(e,t)}return t}function Lw(e,t={}){let n={cost:0,messages:{all:0,user:0,assistant:0},tokens:{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},context:null};for(let r of ti(e)){let s=Vy([r.user,...r.assistant],t.pricing);if(s){n.cost+=s.cost;for(let o of Object.keys(n.tokens))n.tokens[o]+=s.tokens[o]}}for(let r of e.messages){r.role==="user"?n.messages.user++:r.role==="assistant"&&n.messages.assistant++,r.kind==="compaction"&&r.status!=="streaming"&&n.messages.assistant++;let s=r.usage;(r.role==="assistant"||r.kind==="compaction")&&s&&s.input+s.output+(s.reasoning??0)+s.cache_read+s.cache_write>0&&(n.context=r)}return n.messages.all=n.messages.user+n.messages.assistant,n}var _N="prt_kortix_restore_g";function Uw(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(_N))}function Fw(e,t){let n=new Map,r=[...e??[]].sort((s,o)=>s.from_seq-o.from_seq);for(let s=1;s<r.length;s++){let o=r[s],i=r[s-1].harness;if(o.harness===i)continue;let a=t.findIndex(l=>l.user.seq>=o.from_seq);a<0||a===0&&t[0].user.seq!==o.from_seq||n.set(t[a].id,{harness:o.harness,previous:i,version:o.version,at:o.at})}return n}var Jy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ze=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,bN=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function Nw(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=Jy(t)?t.restore:void 0;if(!Jy(n))return null;let r=Jy(n.dropped)?n.dropped:{},s=e.grade_counts,o=[{kind:"message",count:Ze(r.message)},{kind:"attachment",count:Ze(s?.attachment)},{kind:"text",count:Ze(r.text)+Ze(n.truncated)},{kind:"tool_input",count:Ze(s?.tool_input)},{kind:"tool_result",count:Ze(r.tool_result)},{kind:"cut_point",count:Ze(s?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,l])=>bN.has(a)?i:i+Ze(l),0)}];return{generation:Ze(n.generation),missing:o.filter(i=>i.count>0)}}var Bw=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function Kw(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of Bw(r))s.ref&&s.bytes!==void 0&&!t.has(s.ref)&&t.set(s.ref,s.bytes);return[...t].map(([n,r])=>({ref:n,bytes:r}))}var qw=(e,t)=>{let n=e.ref===void 0?void 0:t.get(e.ref);if(n===void 0)return e;let{ref:r,bytes:s,...o}=e;return{...o,text:n}},SN=(e,t)=>e.map(n=>n.type==="text"?qw(n,t):n),$w=new WeakMap;function xN(e,t){let n=$w.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>Bw(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?qw(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:SN(s.result.content,t)}}:s)}:e;return $w.set(e,{texts:t,out:r}),r}var ni=1024*1024;function Gw(e){return e.reduce((t,n)=>t+n.bytes,0)>ni?"download":"inline"}function Ww(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>ni)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function Hw(e,t){if(t.size===0)return e;let n=e.messages.map(r=>xN(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function PN(e){return e==="TIMEOUT"||e==="request_deadline"}function wN(e){let t=zw(e)?e.code:void 0;return typeof t=="string"?t:void 0}var zw=e=>typeof e=="object"&&e!==null;function Vw(e){let t=e?.metadata;return!!zw(t)&&t.warm===!0}var kN=5,vN=2e3,AN=e=>new Promise(t=>setTimeout(t,e));async function RN(e,{attempts:t=kN,delayMs:n=vN,sleep:r=AN}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function CN(e,t){let n=new Map,r=new Set,s=new Set,o=new Set,i=0,a=(l,p,d)=>{if(r.has(l)||n.has(l))return Promise.resolve();r.add(l);let g=i,m=(async()=>{let f=null;try{let h=await e.ensure(l,p);if(g!==i)return;s.has(h.sessionId)?f=h.sessionId:n.set(l,h)}catch{}finally{g===i&&r.delete(l)}f&&d>0&&await a(l,f,d-1)})();return o.add(m),m.finally(()=>o.delete(m)),m};return{ensure:(l,p)=>a(l,p?.excludeSessionId,1),take:(l,p,{replenish:d})=>{let g=n.get(l);return g?(n.delete(l),s.add(g.sessionId),d&&a(l,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(l,p,d)=>{try{return await e.claim(l,d),!0}catch(g){return PN(wN(g))?RN(async()=>!Vw(await e.read(l,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:l=>{for(let[p,d]of n)if(d.sessionId===l)return n.delete(p),s.add(l),p;return null},revalidate:async l=>{let p=n.get(l);if(!p)return!1;try{if(Vw(await e.read(l,p.sessionId)))return!1}catch{return!1}return n.get(l)?.sessionId!==p.sessionId?!1:(n.delete(l),s.add(p.sessionId),!0)},held:l=>n.get(l)??null,reset:()=>{i+=1,n.clear(),r.clear(),s.clear()},settled:async()=>{for(;o.size>0;)await Promise.all([...o])}}}var TN=12e4,ri=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},IN=1e3,EN=15e3,Yw=100,MN=50,ON=10;function Jw(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let i=new URLSearchParams({limit:String(r)});s&&i.set("before",s);let a=await e.getToken?.(),l=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!l.ok)throw l.status===503?new Gr(`session ${l.status}`):new P(`Session synchronization failed: ${l.status}`,{status:l.status});return{messages:await l.json(),nextCursor:l.headers.get("x-next-cursor")||void 0}}}function Qw(e){return DN(Jw(e))}function Xw(e){return new Qy({...e,loadPage:Jw(e)})}async function DN(e){let t=[],n=new Set,r;do{let i=await e({limit:Yw,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])o.has(a.info.id)||(o.add(a.info.id),s.push(a));return s}var jN={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Qy=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??jN,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??TN,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed||t==="visible"&&this.streamReliable&&this.snapshot.freshness==="fresh"?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":this.snapshot.freshness}),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 ri;if(!r&&Kr(n))return;if(r||this.update({freshness:bn(n)?"loading":"error"}),n instanceof P&&(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(IN*2**this.retryAttempt,EN);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?MN:Yw,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,s=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",s,{once:!0});let o,i=new Promise((l,p)=>{o=this.startTimer(()=>{let d=new ri(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(l){a=Promise.reject(l)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(o),n.removeEventListener("abort",s)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let i=[...t.messages],a=new Set(this.knownUserMessageIds),l=new Set(s?[s]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<ON&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(l.has(p))throw new Error(`Session history cursor repeated: ${p}`);l.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw o?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,o?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,i=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};var LN=5e3,ek=40,FX=5*6e4,$N=16,Yr=new Map;function tk(e,t,n,r=Date.now()){let s=nk(e,t);for(Yr.delete(s),Yr.set(s,{envelope:n,atMs:r});Yr.size>$N;){let o=Yr.keys().next().value;if(o===void 0)break;Yr.delete(o)}}var Zw=new Map;function nk(e,t){return`${e}/${t}`}function UN(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=LN}function rk(e,t,n=Date.now()){if(!e||!t)return null;let r=nk(e,t),s=Zw.get(r);return s?UN(s,n)?s.promise:(Zw.delete(r),null):null}function sk(e){let t=e.transcript;if(!t||t.known!==!0||t.requested!==!0)return null;let{known:n,requested:r,...s}=t;if(!s.available)return s;let o=e.session?.runtime_session_id??e.session?.opencode_session_id,i=s.runtime_session_id??s.opencode_session_id;return o&&i===o?s:null}var FN=/(?:\n\n)?Command exited with code (-?\d+)\s*$/;function NN(e){if(e.status!=="error"||e.name!=="bash"||!e.result)return e;let n=e.result.content.filter(i=>i.type==="text").map(i=>i.text).join(""),r=FN.exec(n);if(!r)return e;let{error:s,...o}=e.result;return{...e,status:"complete",result:{...o,content:[{type:"text",text:n.slice(0,r.index)},...e.result.content.filter(i=>i.type!=="text")],is_error:!1,exit_code:Number(r[1])}}}function ok(e){let t=!1,n=e.blocks.map(r=>{if(r.type!=="tool_call")return r;let s=NN(r);return s!==r&&(t=!0),s});return t?{...e,blocks:n}:e}var ik=Object.freeze({generation:0,session:{},threads:{},messages:{},revs:{},older:{}});function BN(e,t){let n=ok(t),r=(e[n.thread_id]??[]).filter(o=>o.message_id!==n.message_id),s=r.length;for(;s>0&&r[s-1].seq>n.seq;)s--;return r.splice(s,0,n),{...e,[n.thread_id]:r}}function ak(e,t,n){let r=e.messages,s=e.older,o=t.thread_id,i=o===null?void 0:r[o];if(o!==null){let p=t.messages[0]?.seq;(n!==void 0||!i?.length||!t.has_more||p!==void 0&&p<=i[0].seq)&&e.older[o]!==t.has_more&&(s={...s,[o]:t.has_more})}if(o!==null&&i){let p=t.has_more?t.messages[0]?.seq??1/0:-1/0,d=n??1/0,g=new Set(t.messages.map(f=>f.message_id)),m=i.filter(f=>f.seq<p||f.seq>=d||g.has(f.message_id)||e.revs[f.message_id]!==void 0);m.length!==i.length&&(r={...r,[o]:m})}for(let p of t.messages)!Ml(p)||e.revs[p.message_id]!==void 0||(r=BN(r,p));let a={...e.threads};for(let p of t.threads)Ol(p)&&(a[p.thread_id]=p);let l=t.generation>e.generation;return{...e,generation:Math.max(t.generation,e.generation),session:l?{...e.session,...t.session}:{...t.session,...e.session},threads:a,messages:r,older:s}}var KN=2e3;async function qN(e,t,n){let r=rk(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??KN,null)})]).finally(()=>clearTimeout(s)):null;return(o&&sk(o))??Hn(e,t,{limit:ek,history:!0,signal:n.signal})}async function lk(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s=Gn?await r_(Gn,t,n):null;if(s){let i=iw(ak(ik,s));return{envelope:null,empty:!!i?.empty&&i.runtimeSessionId===r&&await ck(t,n,r),log:s}}let o;try{o=await qN(t,n,{})}catch{return{envelope:null,empty:!1}}return tk(t,n,o),Xy(o)!==r?{envelope:o,empty:!1}:{envelope:o,empty:await ck(t,n,r)}}async function ck(e,t,n){try{let r=await Vn(e,t);return Zy({savedEmptyRoot:n,rootSessionId:n,turnRead:!0,hasEndedTurn:r.last_ended!=null,hasOpenOrQueuedTurn:r.turns.length>0})}catch{return!1}}function Xy(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 Zy(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function GN(e){throw N("buildTunnelEventStreamUrl")}function WN(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:l,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(b,O){o?.(b,O);let y=d.get(b);if(y)for(let w of y)try{w(O)}catch{}}async function S(){if(m)return;let b=new AbortController;g=b,p&&(p.aborted?b.abort():p.addEventListener("abort",()=>b.abort(),{once:!0}));let O=b.signal;try{let y={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(y["Content-Type"]="application/json"),f&&(y["Last-Event-ID"]=f);let w=await fetch(t,{method:r,headers:y,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:O,credentials:"include"});if(!w.ok)throw new Error(`SSE connection failed: ${w.status} ${w.statusText}`);if(!w.body)throw new Error("SSE response has no body");i?.();let x=w.body.getReader(),k=new TextDecoder,C="",j="message",R=[],L=D=>{if(D===""){R.length>0&&h(j,R.join(`
|
|
98
|
+
`)),j="message",R=[];return}if(D.startsWith(":"))return;let q=D.indexOf(":"),W=q===-1?D:D.slice(0,q),K=q===-1?"":D.slice(q+1);K.startsWith(" ")&&(K=K.slice(1)),W==="event"?j=K.trim()||"message":W==="data"?R.push(K):W==="id"&&!K.includes("\0")&&(f=K)},pe=D=>{let q="";!D&&C.endsWith("\r")&&(q="\r",C=C.slice(0,-1));let W=C.split(/\r\n|\n|\r/);C=(W.pop()??"")+q;for(let K of W)L(K)};for(;!m;){let{done:D,value:q}=await x.read();if(D)break;C+=k.decode(q,{stream:!0}),pe(!1)}m||(C+=k.decode(),pe(!0),l?.())}catch(y){if(m||y instanceof DOMException&&y.name==="AbortError")return;a?.(y instanceof Error?y:new Error(String(y)))}}function v(){m=!0,g?.abort(),g=null,d.clear()}function T(b,O){let y=d.get(b)??new Set;y.add(O),d.set(b,y)}function _(b,O){d.get(b)?.delete(O)}return{connect:S,close:v,addEventListener:T,removeEventListener:_}}function HN(e,t){throw N("createTunnelEventStream")}var uk="/_kortix/viewer",si=6e4,wn=new Map;function pk(){wn.clear(),Jr.clear()}async function VN(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 eh(e={}){let t=e.path??uk,n=e.fetch??((o,i)=>fetch(o,i)),r=wn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=VN(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-si:Date.now()+si;return wn.set(t,{session:o,expiresAt:a}),o});return wn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function dk(e={}){let t=e.path??uk;return Object.assign(async()=>(await eh(e))?.access_token??null,{invalidate:n=>{let r=wn.get(t);r&&!r.inflight&&r.session?.access_token===n&&wn.delete(t)}})}var Jr=new Map;async function zN(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let o=await n.json().catch(()=>null);o?.error==="app_not_linked"&&console.warn(`[kortix] ${String(o.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let s=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return Jr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-si:Date.now()+si}),r.token}catch{return null}}function th(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((s,o)=>fetch(s,o));return async(s={})=>{let o=Jr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=zN(n,r).then(a=>(a===null&&Jr.delete(n),a));return Jr.set(n,i),i}}function gk(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:`${le(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:th({audience:e,fetch:t.fetch})}}var yt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},xe=e=>typeof e=="string"&&e.length>0?e:null;function mk(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 oi(e){if(!e||typeof e!="object")return null;let t=e,n=xe(t.sub)??xe(t.subject)??xe(t.user_id)??xe(t.userId);return n?{userId:n,email:xe(t.email),name:xe(t.name),picture:xe(t.picture)??xe(t.pictureUrl),groups:mk(t.groups),groupIds:mk(t.group_ids??t.groupIds),role:xe(t.role),accountId:xe(t.account_id)??xe(t.accountId),projectId:xe(t.project_id)??xe(t.projectId)}:null}function yk(e,t={}){let n=oi(e);if(!n)throw new yt("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:s}=t;if(r&&!r.some(o=>n.groups.includes(o)||n.groupIds.includes(o)))throw new yt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new yt("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var YN=60,nh=new Map;function hk(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 fk(e){return JSON.parse(new TextDecoder().decode(hk(e)))}async function JN(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),s=e.slice(n+1),o=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(s),i=>i.charCodeAt(0))):decodeURIComponent(s);return JSON.parse(o)}if(/^https?:\/\//.test(e)){let n=nh.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(()=>nh.delete(e)),nh.set(e,n)),n}return JSON.parse(e)}async function _k(e,t={}){let n=b=>{throw new yt("unauthenticated",`Kortix sign-in token refused: ${b}.`)},r=t.jwks??st("KORTIX_AUTH_JWKS"),s=t.issuer??st("KORTIX_AUTH_ISSUER"),o=t.audience??st("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(o!==!1&&!o)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,l,p]=i,d,g;try{d=fk(a),g=fk(l)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await JN(r,t.fetch??((b,O)=>fetch(b,O)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(b=>b.kty==="EC"&&(d.kid===void 0||b.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${l}`),S;try{S=hk(p)}catch{return n("malformed")}let v=!1;for(let b of f)try{let{kid:O,alg:y,use:w,key_ops:x,...k}=b,C=await crypto.subtle.importKey("jwk",k,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},C,S,h)){v=!0;break}}catch{}if(!v)return n("bad signature");let T=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+YN<T)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let b=g.aud;if(!(b===o||Array.isArray(b)&&b.includes(o)))return n("wrong audience")}let _=oi(g);return _||n("no subject")}function rh(e){let t=e.agents.map(QN),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function QN(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.hidden===!0||e.enabled===!1}}function sh(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>Xs(n?{...r,mode:null}:r))}function bk(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let o=e.selectedAgent?.trim();return o?{selected:o,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=sh(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(o=>o.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let s=e.defaultAgent?.trim();return s&&n.some(o=>o.name===s)?{selected:s,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var Sk=rh;function xk(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function oh(e){return{providerID:"kortix",modelID:e}}function kn(e,t){return oh(e.startsWith("kortix/")?e.slice(7):e)}var Pk=[{id:"bee",env:["BEE_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"liquid",env:["LIQUID_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"infer",env:["INFER_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"inferx",env:["INFERX_API_KEY"]}];function ih(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function ZN(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function wk(e,t){let n=new Map;for(let r of e){let s=t(r),o=n.get(s);o?o.push(r):n.set(s,[r])}return n}function Qr(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 kk(e){return e.reduce((t,n)=>{let r=ih(n)??0,s=ih(t)??0;return r!==s?r>s?n:t:Qr(n.id)>Qr(t.id)?n:t})}function ah(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of wk(e,ZN)){let a=[...wk(o,p=>p.family||p.id).values()].map(kk),l=a.filter(p=>{let d=ih(p);return d!==null&&Math.abs(n-d)<r});for(let p of l.length>0?l:[kk(a)])s.add(p.id)}return s}function ch(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=>Qr(r.id)>0)?n.filter(r=>Qr(r.id)>0):n}var vk={id:"platinum",name:"Platinum",env:["PLATINUM_API_KEY"],doc:"https://platinum.dev",api:"https://api.platinum.dev/v1/inference",npm:"@ai-sdk/openai-compatible",models:[]},Ak=[...Pk,{id:vk.id,env:vk.env}],eB={"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 Rk(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var tB=(()=>{let e=new Map;for(let{id:n,env:r}of Ak)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let s=[...r].sort((o,i)=>o.length-i.length||o.localeCompare(i));t.set(n,r.find(o=>Rk(o)===n)??s[0])}return t})();function Ck(e){let t=eB[e.id];if(t)return t;let n=e.env??[],r=n.length===1?tB.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[Rk(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}var nB=["low","medium","high"];function Tk(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:[...nB]}:void 0,s=e.temperature===!0,o=e.limit?.output,i=typeof o=="number"&&o>0?{ceiling:o}:void 0;return{reasoningEffort:r,temperature:s,topP:s,maxOutputTokens:i}}var Ik=Ak;var y4=Ik.map(e=>({id:e.id,authRequirement:Ck(e)})),Ek=new Set(["kortix"]);function rB(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,s])=>{if(s.variants&&Object.keys(s.variants).length>0)return[r,s];let o=Tk({id:r,name:s.name,reasoning:s.reasoning,reasoning_options:s.reasoning_options}).reasoningEffort?.values;return o?.length?[r,{...s,variants:Object.fromEntries(o.map(i=>[i,{}]))}]:[r,s]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function Mk(e){return e.modelPicker?rB(e.modelPicker):void 0}function sB(e){return"capabilities"in e&&e.capabilities!=null}function ii(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1&&n.available!==!1}function Ok(e,t){if(!e)return[];let n=Array.isArray(e.all)?e.all:[],r=Array.isArray(e.connected)?e.connected:[],s=[];for(let o of n)if(r.includes(o.id)&&Ek.has(o.id))for(let[i,a]of Object.entries(o.models)){if(i==="auto"||i==="kortix/auto")continue;let l;if(sB(a)){let p=a.capabilities;l={reasoning:p.reasoning??!1,vision:p.input?p.input.image??!1:void 0,toolcall:p.toolcall??!1}}else{let p=a.modalities?.input;l={reasoning:a.reasoning??!1,vision:p?p.includes("image"):a.attachment,toolcall:a.tool_call??!1}}s.push({id:xk({providerID:o.id,modelID:i}),providerID:o.id,providerName:a.provider_name??o.name,modelID:i,modelName:(a.name||i).replace("(latest)","").trim(),variants:a.variants,capabilities:l,contextWindow:a.limit?.context,releaseDate:a.release_date,family:a.family,cost:a.cost?{input:a.cost.input??0,output:a.cost.output??0}:void 0,providerSource:o.source,provider:a.provider,reasoningOptions:a.reasoning_options,description:a.description,openWeights:a.open_weights,lastUpdated:a.last_updated,enabled:a.enabled,free:a.free===!0,available:a.available,availability:a.availability})}return s}function Dk(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var Lk="kortix",jk="codex";function $k(e){return e.providerID===Lk&&!e.modelID.includes("/")}function oB(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function vn(e){return $k(e)}function iB(e){return ah(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function Uk(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=iB(e.catalogModels),s=Dk(e.catalogModels),o=new Map;for(let i of e.pins??[])o.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,l=o.get(a);if(l==="hide")return!1;if(i.providerID===Lk){let d=oB(i.modelID,i.provider),g=d===jk?t?.has(jk)??!1:t?.has(d)??!1;if($k(i))return!n;if(!g)return!1;if(l==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return vn(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return vn(i)}catch{return vn(i)}return!1}if(l==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return vn(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return vn(i)}catch{return vn(i)}return!1}}function Fk(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 Nk(e,t){let r=(t?e?.agentDefaults?.[t]:void 0)??(e?.resolvedForCaller!==void 0?e.resolvedForCaller:e?.projectDefault??e?.accountDefault??(e?.freeTier?void 0:e?.platformDefault));return r?oh(r):void 0}function Bk(e){for(let t=(e?.length??0)-1;t>=0;t--){let n=e[t],{provider:r,model:s}=n.model??{};if(n.role==="user"&&r&&s)return{providerID:r,modelID:s}}}var aB=new Set(["explicit","repointed","fallback"]);function Kk(e){let t=e?.metadata;if(t?.opencode_model_source!=="fallback")return;let{opencode_model:n,opencode_model_fallback_from:r,opencode_model_fallback_at:s}=t;if(typeof n!="string"||typeof r!="string"||typeof s!="number")return;let o=t.opencode_model_fallback_reason;return{model:kn(n),from:kn(r),reason:typeof o=="string"?o:"other",atMs:s}}function qk(e,t){return!t||(e??-1)>=t.atMs}function Gk(e){let t=e.session?Qn(e.session):null,n=t?kn(t):void 0,r=e.session?.metadata;return(aB.has(String(r?.opencode_model_source))||r?.opencode_model_restored===!0?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(i=>!!i)}function Wk(e){let{models:t,providers:n}=e,r=l=>ii(t,l),s=l=>l.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let l=e.configModel.split("/");if(l.length>=2){let[p,...d]=l,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let l of e.recent??[])if(r(l))return l;if(n){let l=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=l[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of ch(Object.keys(m.models).map(S=>({id:S})))){let S={providerID:m.id,modelID:h.id};if(r(S))return S}}}})(),i=s(e.picks??[]);return{model:i??s([e.serverDefault,e.globalDefault,e.agentModel,o]),explicit:i,fallback:o}}return Xk(cB);})();
|