@kortix/sdk 0.14.7 → 0.14.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +22 -0
  2. package/dist/core/client/kortix.d.ts.map +1 -1
  3. package/dist/core/client/project-core.d.ts.map +1 -1
  4. package/dist/core/http/runtime-errors.d.ts +7 -1
  5. package/dist/core/http/runtime-errors.d.ts.map +1 -1
  6. package/dist/core/http/runtime-errors.js +2 -0
  7. package/dist/core/http/runtime-errors.js.map +1 -1
  8. package/dist/core/rest/platform-client/host-boundary.d.ts +52 -0
  9. package/dist/core/rest/platform-client/host-boundary.d.ts.map +1 -1
  10. package/dist/core/rest/platform-client/host-boundary.js +23 -0
  11. package/dist/core/rest/platform-client/host-boundary.js.map +1 -1
  12. package/dist/core/rest/projects-client/git-history.d.ts +1 -1
  13. package/dist/core/rest/projects-client/git-history.d.ts.map +1 -1
  14. package/dist/core/rest/projects-client/projects.d.ts +14 -8
  15. package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
  16. package/dist/core/rest/projects-client/projects.js +1 -1
  17. package/dist/core/rest/projects-client/projects.js.map +1 -1
  18. package/dist/core/rest/projects-client/sessions.d.ts +46 -2
  19. package/dist/core/rest/projects-client/sessions.d.ts.map +1 -1
  20. package/dist/core/rest/projects-client/sessions.js +24 -2
  21. package/dist/core/rest/projects-client/sessions.js.map +1 -1
  22. package/dist/core/runtime/runtime-types.d.ts +11 -0
  23. package/dist/core/runtime/runtime-types.d.ts.map +1 -1
  24. package/dist/core/session-sync/session-sync-controller.d.ts +6 -0
  25. package/dist/core/session-sync/session-sync-controller.d.ts.map +1 -1
  26. package/dist/core/session-sync/session-sync-controller.js +29 -1
  27. package/dist/core/session-sync/session-sync-controller.js.map +1 -1
  28. package/dist/core/turns/shell.d.ts +5 -1
  29. package/dist/core/turns/shell.d.ts.map +1 -1
  30. package/dist/core/turns/shell.js +5 -1
  31. package/dist/core/turns/shell.js.map +1 -1
  32. package/dist/kortix.esm.min.js +33 -33
  33. package/dist/kortix.global.js +33 -33
  34. package/dist/react/runtime-actions.d.ts +1 -0
  35. package/dist/react/runtime-actions.d.ts.map +1 -1
  36. package/dist/react/runtime-actions.js +1 -0
  37. package/dist/react/runtime-actions.js.map +1 -1
  38. package/dist/react/use-feature-flag.d.ts +1 -1
  39. package/dist/react/use-feature-flag.d.ts.map +1 -1
  40. package/dist/react/use-feature-flag.js +2 -1
  41. package/dist/react/use-feature-flag.js.map +1 -1
  42. package/dist/react/use-opencode-config.d.ts +3 -0
  43. package/dist/react/use-opencode-config.d.ts.map +1 -1
  44. package/dist/react/use-opencode-config.js +3 -0
  45. package/dist/react/use-opencode-config.js.map +1 -1
  46. package/dist/react/use-opencode-mcp.d.ts +1 -0
  47. package/dist/react/use-opencode-mcp.d.ts.map +1 -1
  48. package/dist/react/use-opencode-mcp.js.map +1 -1
  49. package/dist/react/use-opencode-sessions/sessions.d.ts +1 -0
  50. package/dist/react/use-opencode-sessions/sessions.d.ts.map +1 -1
  51. package/dist/react/use-opencode-sessions/sessions.js +1 -0
  52. package/dist/react/use-opencode-sessions/sessions.js.map +1 -1
  53. package/package.json +2 -2
@@ -1,24 +1,24 @@
1
- "use strict";var Kortix=(()=>{var pi=Object.defineProperty;var Zv=Object.getOwnPropertyDescriptor;var ek=Object.getOwnPropertyNames;var tk=Object.prototype.hasOwnProperty;var nk=(e,t)=>{for(var n in t)pi(e,n,{get:t[n],enumerable:!0})},rk=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ek(t))!tk.call(e,s)&&s!==n&&pi(e,s,{get:()=>t[s],enumerable:!(r=Zv(t,s))||r.enumerable});return e};var sk=e=>rk(pi({},"__esModule",{value:!0}),e);var vB={};nk(vB,{ABORT_REASONS:()=>Px,ABORT_REASONS_NOT_YET_EMITTED:()=>P0,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>wi,ACTIVE_INSTANCE_COOKIE:()=>Gr,ANALYTICS_UNAVAILABLE_CODE:()=>xi,ATTACHMENT_PART_REF_PREFIX:()=>Kx,ApiError:()=>_,AuthError:()=>re,BillingError:()=>et,CAPTURE_DEVICE_DEFAULTS:()=>sj,CAPTURE_EXCLUSION_GROUPS:()=>ej,CAPTURE_FRAME_INTERVALS_MS:()=>nj,CAPTURE_LAYERS:()=>ZO,CAPTURE_MAX_HEIGHTS:()=>rj,CAPTURE_RETENTION_LIMITS:()=>tj,CONNECTION_FAULT_GRACE_MS:()=>Jx,CONNECTOR_POLL_FIRST_DELAY_MS:()=>$x,CONNECTOR_POLL_INTERVAL_MS:()=>Ux,CONNECTOR_POLL_WINDOW_MS:()=>Fx,CONTEXT_TOOLS:()=>CP,COST_MARKUP:()=>Oy,ConnectorApprovalPendingError:()=>ws,ConnectorCallError:()=>Ln,ConnectorPageLimitError:()=>vs,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>TP,DEFAULT_NOTIFICATION_PREFERENCES:()=>vI,DEFAULT_TRANSCRIPT_OPTIONS:()=>Jf,DESTRUCTIVE_PHASES:()=>Ex,FEATURE_DISABLED_CODE:()=>jt,FEATURE_FLAG_KEYS:()=>Uk,FEATURE_NOT_SUPPORTED_CODE:()=>_i,FILE_VERBS:()=>mt,FileExistsError:()=>rn,HeadlessAuthError:()=>Yt,HostBoundaryError:()=>Vr,IMPERSONATION_HEADER:()=>xh,INBOX_NOTIFICATION_KINDS:()=>wI,INBOX_OBSERVATION_MAX_MS:()=>Zo,INITIAL_SETTLED_CONNECTION:()=>kF,INSTANCE_SCOPED_ROUTES:()=>xx,KNOWN_TOOL_KINDS:()=>Vh,KORTIX_TRANSCRIPT_SCHEMA:()=>ve,KortixMemberError:()=>yt,MAX_PROMPT_ATTACHMENTS_BYTES:()=>$A,MAX_PROMPT_ATTACHMENT_BYTES:()=>fl,MAX_PROMPT_ATTACHMENT_FILES:()=>Bh,MEMORY_VERBS:()=>$$,MODEL_NOT_SERVABLE_CODE:()=>bi,NO_GROUP_ACTIVITY_TOOLS:()=>rb,OPTIMISTIC_ABORT_MAX_MS:()=>ei,OPTIMISTIC_COMPACTION_MAX_MS:()=>UF,OPTIMISTIC_RECEIPT_MAX_MS:()=>Qo,PERSISTED_QUERY_CACHE_VERSION:()=>iQ,PLUMBING_TOOLS:()=>YP,PREVIEW_PROBE_TIMEOUT_MS:()=>yF,PROJECT_ACTIONS:()=>Q,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>PR,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>SR,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>u_,PROVISION_IN_FLIGHT_CODE:()=>Si,PROVISION_STREAM_UNTERMINATED_CODE:()=>Dh,PublicSessionShareError:()=>Ls,REPOSITORY_DISCONNECTED_CODE:()=>An,REVIEW_CONTROL_ACTIONS:()=>EC,RUNTIME_NOT_READY_MARKERS:()=>O0,RUNTIME_PERMISSION_CAPABILITIES:()=>CI,RUNTIME_PERMISSION_REPLIES:()=>RI,RequestTooLargeError:()=>bt,RuntimeNotReadyError:()=>tn,SANDBOX_FS_ROOTS:()=>ko,SANDBOX_PORTS:()=>Ke,SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE:()=>Pi,SERVER_COMPACTION_REVALIDATE_MS:()=>ew,SERVER_OBSERVATION_MAX_MS:()=>Xo,SESSION_LIST_STATUS:()=>XF,SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES:()=>oi,SESSION_LOG_MINOR:()=>_e,SESSION_LOG_SCHEMA:()=>ce,SESSION_NOTICE:()=>tN,STANDALONE_TOOLS:()=>sb,STREAM_OBSERVATION_MAX_MS:()=>Sn,SandboxNotReadyError:()=>Wr,SessionNotReadyError:()=>Ct,SessionStartError:()=>Es,TRIGGER_CONTROL_ACTIONS:()=>TC,TURN_END_LEDGER_LAG_MS:()=>EF,TURN_ERROR_CODES:()=>U_,WAKE_ESCALATION_COOLDOWN_MS:()=>GF,WAKE_MAX_RESTARTS:()=>qF,WAKE_NO_PROGRESS_MS:()=>KF,WIRE_ID_BACKDATE_MS:()=>_o,WIRE_ID_CLOCK_TOLERANCE:()=>ct,WIRE_ID_TIME_MASK:()=>Ve,WIRE_ID_TIME_SCALE:()=>Xt,WIRE_MESSAGE_ID:()=>Rb,__getConfigResolver:()=>ak,__setConfigResolver:()=>ik,abortErrorReason:()=>x0,acceptAccountInvite:()=>ps,acceptAccountInviteAndLand:()=>Yi,acceptEnterpriseOffer:()=>ip,acceptInvite:()=>eU,accountInviteLanding:()=>Oh,actReviewItem:()=>Cd,activateConnection:()=>Pc,addComputerToProject:()=>vc,addGroupMembers:()=>td,addMarketplaceSource:()=>xg,addRoomPerson:()=>zd,addRoomSession:()=>Hd,advanceWakeEscalation:()=>VF,allDescendantIds:()=>FP,appendPreviewToken:()=>lF,approveCaptureDeviceGrant:()=>Kf,approveCaptureEnrollment:()=>Cf,approveCliDevice:()=>KT,approveProjectAccessRequest:()=>Ca,approveTask:()=>LE,archiveProject:()=>jn,assignTicket:()=>GE,attachGroupToProject:()=>Ua,authMfa:()=>mo,authUser:()=>uo,authenticatedFetch:()=>$,authenticatedRequest:()=>Un,authorizePreviewUrl:()=>fF,backendApi:()=>c,bindSlackIdentity:()=>XR,bindTeamsIdentity:()=>ZR,brokerProjectSecretRequest:()=>Ja,browserKeyValueStorage:()=>iF,buildInstancePath:()=>vx,buildPresentationTemplateImageUrl:()=>SF,buildPresentationTemplatePdfUrl:()=>bF,buildPreviewAuthEndpoint:()=>Wy,buildPublicTemplateUrl:()=>WU,buildRuntimePresentationConversionUrl:()=>Yx,buildSandboxTemplate:()=>il,buildScrapeFailureResults:()=>GP,buildStaticFileHealthPreviewUrl:()=>NO,buildStaticFileLocalUrl:()=>FO,buildStaticFilePreviewUrl:()=>UO,buildStaticFileServicePath:()=>AS,buildTunnelEventStreamUrl:()=>iB,buildWebProxyUrl:()=>WO,bulkActReviewItems:()=>Td,bulkDeletePolicies:()=>BC,bulkImportPolicies:()=>KC,burstSummary:()=>Wo,burstSummaryLabel:()=>JP,burstWorkLabel:()=>xy,callConnector:()=>vt,canManageBilling:()=>P_,canOfferTopup:()=>KR,cancelAccountDeletion:()=>RT,cancelAccountInvite:()=>Wi,cancelSandbox:()=>z0,cancelSandboxUpdate:()=>mU,cancelScheduledChange:()=>Zu,cancelSubscription:()=>Ju,captureHealthBucket:()=>cj,changeRequestControlsFrom:()=>T_,checkAccessEmail:()=>RU,checkMcpServerSignIn:()=>AA,childMapByParent:()=>ND,claimComputer:()=>bU,claimNext:()=>eP,claimPerSeatBilling:()=>VR,claimWarmProjectSession:()=>Ql,classifyPart:()=>py,classifyPreviewProbeStatus:()=>zx,classifyPtyClose:()=>Lb,classifySessionLogMessage:()=>Nw,classifyTurn:()=>Uo,cleanErrorMessage:()=>nL,cleanResultSnippet:()=>iL,cleanWorkerOutput:()=>E$,clearImpersonationSession:()=>Ri,clearKortixAppViewerCache:()=>hv,clearModelDefault:()=>Du,clearSessionFresh:()=>QA,closeChangeRequest:()=>Tl,closeMilestone:()=>_M,collectTurnParts:()=>WD,commentTicket:()=>HE,commitSessionChanges:()=>Ml,compactionExpiryAtMs:()=>NF,compactionTurnInfo:()=>qL,compareForDisplayAt:()=>No,compareMessagesForDisplay:()=>FD,compareSemver:()=>dj,completeInFlight:()=>tP,completeSlackInstall:()=>fp,completeTeamsInstall:()=>yp,composerSelectableAgents:()=>uh,computeStatusFromPart:()=>Iy,configureAutoTopup:()=>rp,configureKortix:()=>es,confirmCheckoutSession:()=>zu,connectEmail:()=>vp,connectSlack:()=>gp,connectTelegram:()=>sC,connectionFromHealth:()=>vF,connectionIsFaulted:()=>wF,connectionSharedWithEveryone:()=>dA,connectorConnect:()=>Uh,connectorFinalize:()=>Fh,connectorHeadline:()=>QU,contactEnterpriseSales:()=>ap,contextLabelForTool:()=>fL,contextToolSummary:()=>qj,contextToolTrigger:()=>Gj,convertPresentationToGoogleSlides:()=>UT,convertRuntimePresentation:()=>PF,copyFile:()=>vr,costExportUrl:()=>lp,countLiveInboxPrompts:()=>OF,countReviewItemsBySegment:()=>hC,createAccount:()=>ji,createAccountAuditWebhook:()=>pg,createAccountSecretResource:()=>sc,createAccountToken:()=>Xd,createApp:()=>kg,createAppAccessSession:()=>Og,createAppDeployment:()=>Dg,createAppToken:()=>Cg,createAppVolume:()=>Xg,createAppVolumeSnapshot:()=>nm,createArtifactKind:()=>$L,createAssignment:()=>Pd,createAuditWebhook:()=>_T,createBackup:()=>rU,createCaptureEnrollmentToken:()=>kf,createCheckoutSession:()=>Vu,createConnector:()=>Uc,createConnectorLinkInfoCache:()=>zU,createFile:()=>wr,createGatewayKey:()=>Kp,createGroup:()=>Qp,createHttpSessionSyncController:()=>sv,createInstance:()=>yU,createKortix:()=>JS,createKortixPty:()=>Qm,createKortixSession:()=>yo,createMarketplaceInstallSession:()=>HT,createMilestone:()=>yM,createModelVisibility:()=>Gv,createOAuthClient:()=>yd,createPerSeatCheckout:()=>HR,createPersistedQueryCache:()=>oF,createPolicy:()=>UC,createPortalSession:()=>Yu,createProject:()=>oa,createProjectAgent:()=>nM,createProjectCliToken:()=>rg,createProjectRepo:()=>ia,createProjectResourceGrant:()=>Ka,createProjectSession:()=>Rt,createProjectSkill:()=>da,createProjectTrigger:()=>Su,createPromptAttachmentController:()=>bf,createRole:()=>cd,createRoom:()=>Nd,createSSEStream:()=>aB,createSandbox:()=>B0,createSandboxShare:()=>Ed,createSandboxTemplate:()=>rl,createSavedCopyStore:()=>dR,createScimToken:()=>HC,createServiceAccountApi:()=>mT,createSessionPrompt:()=>zn,createSessionPublicShare:()=>zl,createSessionQueue:()=>XS,createSessionReminder:()=>jd,createSsoGroupMapping:()=>oT,createTask:()=>OE,createTicket:()=>BE,createTunnelEventStream:()=>cB,createWarmSessionPool:()=>GN,currentSavedCopyStore:()=>Ul,declineAccountInvite:()=>Ji,declineInvite:()=>tU,deleteAccountImmediately:()=>CT,deleteAccountSecretResource:()=>ac,deleteApp:()=>Rg,deleteAppDeployment:()=>Bg,deleteAuditWebhook:()=>ST,deleteBackup:()=>oU,deleteConnector:()=>Kc,deleteConnectorCredential:()=>zc,deleteCredential:()=>kM,deleteCustomLlmProvider:()=>ar,deleteDriveFile:()=>lI,deleteEnv:()=>zm,deleteFile:()=>Et,deleteGatewayBudget:()=>Np,deleteGitHubInstallation:()=>va,deleteGroup:()=>Zp,deleteInstance:()=>hU,deleteKortixProject:()=>pM,deleteMilestone:()=>SM,deleteOAuthClient:()=>bd,deletePersonalProjectSecret:()=>tc,deletePolicy:()=>NC,deleteProjectAgent:()=>sM,deleteProjectProviderOAuth:()=>Xa,deleteProjectResourceGrant:()=>qa,deleteProjectSecret:()=>Dn,deleteProjectSession:()=>cu,deleteProjectTrigger:()=>xu,deletePromptAttachment:()=>Bt,deleteRole:()=>pd,deleteSandboxTemplate:()=>ol,deleteServiceAccountApi:()=>yT,deleteSessionPrompt:()=>nu,deleteSessionReminder:()=>Us,deleteSessionReminders:()=>$d,deleteSsoGroupMapping:()=>iT,deleteSsoProvider:()=>rT,deleteTask:()=>$E,deleteTicket:()=>VE,denyCaptureDeviceGrant:()=>qf,denyCaptureEnrollment:()=>Tf,describeAccountInvite:()=>zi,describeConnectorTool:()=>_s,destroyAppMachine:()=>zg,destroyAppVolume:()=>em,detachGroupFromProject:()=>Na,detectLocalhostUrls:()=>xS,directSubsessions:()=>rN,disableServiceAccountApi:()=>fT,disconnectEmail:()=>kp,disconnectGitHubApp:()=>nF,disconnectSlack:()=>_p,disconnectTelegram:()=>iC,discoverConnectionOAuth2:()=>yA,discoverConnectionOAuth2Resource:()=>hA,discoverConnectorAuth:()=>Fc,discoverLocalSandbox:()=>W0,dismissDriveConflict:()=>nI,downloadAccountAudit:()=>qU,downloadDriveFile:()=>sI,dropClientForUrl:()=>DM,dropPublicClientForUrl:()=>UM,editQueued:()=>oP,editSessionPrompt:()=>ru,enqueue:()=>ZS,ensurePmSession:()=>eM,ensurePreviewSessionCookie:()=>Vx,ensureProjectConnectorConnection:()=>gA,ensureSandbox:()=>Ix,ensureWarmProjectSession:()=>Jl,env:()=>jb,exchangeCode:()=>ao,execInApp:()=>Jg,exportAccountAudit:()=>lg,extractGatewayErrorDetails:()=>Se,extractInstanceRoute:()=>_n,extractSkillBaseDir:()=>fx,extractSkillContent:()=>G$,extractSkillFiles:()=>mx,extractWorkerPreview:()=>O$,failInFlight:()=>nP,fallbackBusyRowAfterTurnId:()=>c$,familyForTool:()=>fn,featureDisabledKey:()=>fi,featureFlags:()=>Um,fetchAccountStateWithToken:()=>qR,fetchAccountsWithToken:()=>$k,fetchAttachmentPart:()=>aF,fetchCostExportCsv:()=>QR,fetchKortixAppViewer:()=>ih,fetchProjectArchive:()=>dl,fetchProjectFileRaw:()=>LA,fetchProjectsForAccountWithToken:()=>Jk,fetchSessionAttachment:()=>Lm,fileDownloadRequest:()=>rS,filePhase:()=>L$,fileVerb:()=>D$,files:()=>dS,finalizeAppArtifact:()=>Bs,finalizeConnectorSetupLink:()=>jU,findActiveTranscriptShare:()=>wR,findFiles:()=>Pr,findLastTextPart:()=>HD,findSessionAttachments:()=>uE,findText:()=>xr,fireProjectTrigger:()=>vu,fixSandboxWithAgent:()=>nl,flattenModels:()=>Fv,flattenThought:()=>zL,forkAppVolume:()=>sm,formatBillingErrorForUI:()=>hi,formatCost:()=>w$,formatDuration:()=>My,formatJsonFailureOutput:()=>rL,formatMessageDay:()=>e$,formatMessageExact:()=>t$,formatOpenCodeRuntimeError:()=>$0,formatRawOutput:()=>oL,formatRuntimeError:()=>Tx,formatTokens:()=>v$,formatTranscript:()=>aP,freshSendHint:()=>d$,generateSessionId:()=>QS,getAccount:()=>Di,getAccountAuditActivity:()=>ag,getAccountAutomations:()=>CR,getAccountBranding:()=>$i,getAccountDeletionStatus:()=>kT,getAccountState:()=>Nu,getAccountStateMinimal:()=>Bu,getActiveInstanceIdFromCookie:()=>Ax,getAdminProviderAnalytics:()=>OT,getAdminProviderDistribution:()=>IT,getAdminProviderFallback:()=>DT,getAdminRole:()=>TT,getAgentCardLabel:()=>MP,getAgentConfig:()=>$R,getAgentPersona:()=>oM,getAllVersions:()=>pU,getAnsweredQuestionParts:()=>zD,getApp:()=>Fs,getAppAccess:()=>Ig,getAppAuthEnv:()=>Tg,getAppDeployment:()=>$g,getAppDeploymentLogs:()=>Ug,getApprovalLink:()=>WT,getAuthToken:()=>Ft,getAuthTokenWithRetry:()=>aA,getAutoTopupSettings:()=>np,getAutoTopupSetupStatus:()=>WR,getBillingCreditBreakdown:()=>Gu,getBillingTierConfigurations:()=>Hu,getBillingTransactionsSummary:()=>qu,getBillingUsageHistory:()=>Wu,getCaptureAssetUrl:()=>Nf,getCaptureChunkMedia:()=>Ff,getCaptureDays:()=>Lf,getCaptureDeviceGrant:()=>Bf,getCaptureFrame:()=>Uf,getCapturePolicy:()=>If,getCaptureStorage:()=>Mf,getCaptureTimeline:()=>jf,getCaptureTimelineItems:()=>Df,getCaptureWorkspace:()=>Gf,getChangeRequest:()=>vl,getChangeRequestDiff:()=>kl,getChangeRequestMergePreview:()=>Al,getChildSessionError:()=>sD,getChildSessionId:()=>jr,getChildSessionToolParts:()=>oD,getClient:()=>ut,getClientForUrl:()=>Me,getConnectStatus:()=>Hc,getConnectionOAuth2Application:()=>fA,getConnectionOAuth2Status:()=>xA,getConnectionPolicies:()=>wA,getConnectorCatalog:()=>Nt,getConnectorConfig:()=>Dc,getConnectorPolicies:()=>Oc,getConnectorSetupLink:()=>MU,getCostSummary:()=>JR,getCurrentInstanceIdFromPathname:()=>kx,getCurrentInstanceIdFromWindow:()=>k0,getCurrentProject:()=>lf,getDefaultAccountState:()=>Fu,getDiagnostics:()=>uD,getDirectory:()=>EP,getDiscoverConnector:()=>xs,getDiscoverIntegration:()=>IA,getDriveFileUrl:()=>im,getEmailInstallation:()=>xp,getEmailMode:()=>wp,getEnterpriseDemo:()=>xT,getFileStatus:()=>Sr,getFileWithDir:()=>sy,getFilename:()=>IP,getFolderAccess:()=>QT,getFullChangelog:()=>Mx,getGatewayBreakdown:()=>Dp,getGatewayBudgets:()=>Up,getGatewayErrors:()=>$p,getGatewayKeys:()=>Bp,getGatewayLog:()=>Mp,getGatewayOverview:()=>Op,getGatewayRoutingPolicy:()=>Rp,getGatewaySeries:()=>jp,getGatewaySessions:()=>Lp,getGitHubAppStatus:()=>XU,getGitHubInstallation:()=>ya,getGoogleAuthUrl:()=>$T,getGroup:()=>Jp,getHiddenToolParts:()=>Zj,getImpersonationSession:()=>kh,getInvite:()=>Z0,getJustavpsServerTypes:()=>fU,getKortixProject:()=>cM,getKortixProjectBySession:()=>lM,getKortixPtyWebSocketUrl:()=>ef,getLatestSandboxVersion:()=>uU,getMaintenanceConfig:()=>FU,getManagedGitBackend:()=>ka,getManagedGitStatus:()=>Gk,getMarketplaceCatalogItem:()=>bg,getMarketplaceCatalogItemFile:()=>Sg,getMfaRequired:()=>zC,getMilestone:()=>mM,getMobileClientPolicy:()=>Yf,getModelDefaults:()=>Ou,getMyCaptureFrame:()=>zf,getMyCaptureTimeline:()=>Vf,getNotificationPreferences:()=>fm,getOAuthClient:()=>fd,getOAuthConsentRequest:()=>IU,getOpenCodeConfigInvalidError:()=>I0,getPartText:()=>Jj,getPatPolicy:()=>pT,getPermissionForTool:()=>pD,getProject:()=>wt,getProjectActivity:()=>iM,getProjectCommit:()=>bl,getProjectCommitDiff:()=>Sl,getProjectDetail:()=>In,getProjectDrive:()=>om,getProjectFileHistory:()=>Pl,getProjectGitConnectionState:()=>Xk,getProjectGitToken:()=>sa,getProjectGoalFiles:()=>PI,getProjectLlmCatalog:()=>En,getProjectLlmCatalogProviders:()=>Nk,getProjectModelAccess:()=>rr,getProjectModelPicker:()=>Mn,getProjectQuota:()=>qk,getProjectSandboxHealth:()=>$n,getProjectSandboxProviderTransition:()=>Hk,getProjectSession:()=>Wn,getProjectSessionConfigState:()=>pu,getProjectSessionScope:()=>mu,getProrationPreview:()=>ep,getProviders:()=>F0,getProxyBaseUrl:()=>BO,getPublicClientForUrl:()=>$M,getPublicMarketplaceItem:()=>kU,getPublicMarketplaceItemFile:()=>AU,getPublicSessionShare:()=>FT,getPublicSessionShareMessages:()=>NT,getPublicShareByToken:()=>$U,getPublicTemplate:()=>HU,getQuestionForTool:()=>dD,getReferralCode:()=>pC,getReferralStats:()=>mC,getRetryInfo:()=>k$,getRetryMessage:()=>A$,getReviewItem:()=>Ad,getReviewSummary:()=>kd,getRolePermissions:()=>id,getRoleUsage:()=>ad,getRoom:()=>Bd,getRuntimeConfigInvalidError:()=>Jo,getSSHConnection:()=>aU,getSandbox:()=>N0,getSandboxById:()=>K0,getSandboxPortUrl:()=>U0,getSandboxProvisionStatus:()=>SU,getSandboxProvisionStreamUrl:()=>PU,getSandboxUpdateStatus:()=>lU,getSandboxUrl:()=>By,getSandboxUrlForExternalId:()=>Ie,getSecretSetupLink:()=>DU,getServerHealth:()=>Ao,getServiceLogs:()=>IM,getSessionAudit:()=>Xl,getSessionCost:()=>x$,getSessionCostRecord:()=>Zn,getSessionDrives:()=>j_,getSessionHealth:()=>gf,getSessionLogPage:()=>eu,getSessionMessageAuthors:()=>hu,getSessionModelUsage:()=>_u,getSessionOpenBundle:()=>vR,getSessionOversight:()=>QC,getSessionParticipants:()=>Bl,getSessionPolicy:()=>aT,getSessionPreviewCandidates:()=>Hl,getSessionProviderSecretPool:()=>pc,getSessionTranscript:()=>Zl,getSessionTranscriptSync:()=>Hn,getSessionTurn:()=>Vn,getSessionWatch:()=>Kl,getShellModePart:()=>I$,getSlackChannelFile:()=>bp,getSlackInstallation:()=>dp,getSlackManifest:()=>hp,getSlackMode:()=>mp,getSsoProvider:()=>ZC,getStaticFileHealthPath:()=>RS,getSupabaseAccessToken:()=>ms,getSupabaseAccessTokenWithRetry:()=>$h,getTask:()=>IE,getTaskStatus:()=>ME,getTelegramInstallation:()=>rC,getTemplate:()=>VT,getTicket:()=>FE,getToolInfo:()=>aD,getToolPrimaryArg:()=>Oo,getTranscriptFilename:()=>cP,getTurnCost:()=>Yo,getTurnError:()=>y$,getTurnErrorDetails:()=>_$,getTurnErrorRawText:()=>h$,getTurnStatus:()=>Ey,getUsageRollup:()=>cp,getUserRolesWithToken:()=>BU,getVersionDiff:()=>xl,getWebPushPublicKey:()=>hm,getWorkingState:()=>m$,goalHealth:()=>D_,grantAccountSecretResource:()=>cc,grantSandboxProjectAccess:()=>Q0,grantSecretToAgent:()=>FR,groupMessagesIntoTurns:()=>KD,groupShowSegments:()=>Ay,groupSteps:()=>wy,hasDiffs:()=>R$,hasLocalhostUrls:()=>DO,hasPreviewTarget:()=>kS,hasRetryingAssistantTurn:()=>fy,heartbeatGapEvent:()=>Qb,holdSessionPrompts:()=>iu,humanizeReviewActionPath:()=>zp,humanizeSearchQuery:()=>Ir,humanizeToolName:()=>cy,impersonationHeaders:()=>Ci,importSsoProviderFromMetadata:()=>tT,inboxObservationSupersedes:()=>MF,initialWakeEscalationState:()=>Vy,inputPath:()=>ke,installTemplate:()=>zT,interruptSessionPrompt:()=>su,invalidateTokenCache:()=>fs,inviteAccountMember:()=>qi,inviteProjectMember:()=>Oa,inviteRepoCollaborator:()=>na,isAbortError:()=>qr,isAdminBypassEnabled:()=>Th,isAgentPart:()=>Wj,isAppRouteUrl:()=>PS,isAttachment:()=>Qj,isAttachmentPartRef:()=>qx,isAuthFailure:()=>Dt,isBillingError:()=>yi,isCompactionPart:()=>Hj,isConfigured:()=>ts,isContextTool:()=>Kj,isDestructivePhase:()=>cU,isEmptyConversation:()=>oh,isEmptyShowPart:()=>Zs,isErrorOutput:()=>YD,isExternalUrl:()=>zO,isFeatureDisabledError:()=>mi,isFilePart:()=>oy,isImpersonationSessionLive:()=>wh,isInstanceDetailPath:()=>w0,isInstanceScopedAppPath:()=>wx,isInternalLocalhostUrl:()=>GO,isInvisibleActivityPart:()=>Im,isInviteSent:()=>eA,isLastUserMessage:()=>g$,isLegacyMigratedSession:()=>tw,isManagedGithubProject:()=>Fk,isNoGroupActivityTool:()=>Tm,isOfferedModel:()=>li,isOpenCodeConfigInvalidError:()=>E0,isPaintableSavedCopy:()=>s_,isPatchPart:()=>zj,isPersistableQueryKey:()=>sF,isPreviewUrl:()=>qO,isProxiableLocalhostUrl:()=>CS,isQuestionTool:()=>Cm,isReasoningPart:()=>we,isRepositoryDisconnectedError:()=>hh,isRetryableTurnError:()=>NP,isRuntimeConfigInvalidError:()=>Rx,isRuntimeNotReadyResponse:()=>Cx,isRuntimeReady:()=>df,isRuntimeStartingError:()=>L0,isSandboxNotReadyError:()=>bn,isSelectableAgent:()=>to,isServerReachable:()=>uf,isSessionAttachmentRef:()=>rE,isSessionFresh:()=>jl,isSessionLogRestoreNote:()=>Gw,isSessionStartError:()=>MR,isShellActivityTool:()=>XI,isShellMode:()=>px,isShortOutput:()=>M$,isShowContentUnavailable:()=>kI,isShowPayloadEmpty:()=>cr,isSnapshotPart:()=>Vj,isStandaloneActivityTool:()=>Em,isStepPart:()=>Yj,isSubdomainPreviewUrl:()=>zr,isTextPart:()=>Oe,isToolPart:()=>ee,isToolPartHidden:()=>eD,isTurnErrorCode:()=>Pm,isUnderSandboxRoot:()=>af,isWebProxyUrl:()=>VO,isWireIdAheadOf:()=>Tb,kortixAppViewerToken:()=>_v,kortixBinding:()=>bv,kortixPty:()=>Fb,kortixToken:()=>ah,latestPromptModel:()=>Vv,leaveAccount:()=>Zi,linkCaptureDevice:()=>wf,linkGitHubInstallation:()=>xa,linkRepository:()=>ma,listAccountAudit:()=>ig,listAccountAuditWebhooks:()=>ug,listAccountInvites:()=>Gi,listAccountMembers:()=>Ki,listAccountResourceGrants:()=>LC,listAccountSecretResources:()=>rc,listAccountSessions:()=>lT,listAccountTokens:()=>Qd,listAccounts:()=>Oi,listActions:()=>qC,listAdminSandboxes:()=>ET,listAgentIdentities:()=>sd,listAllConnections:()=>yc,listAppAgents:()=>Eg,listAppDeployments:()=>Lg,listAppMachines:()=>qg,listAppVolumeSnapshots:()=>tm,listAppVolumes:()=>Qg,listApps:()=>vg,listAssignments:()=>Sd,listAuditEvents:()=>PT,listAuditWebhooks:()=>hT,listBackups:()=>nU,listBillingTransactions:()=>Ku,listCaptureDevices:()=>Pf,listCaptureEnrollmentTokens:()=>vf,listCaptureEnrollments:()=>Rf,listChangeRequests:()=>wl,listChannelBindings:()=>cC,listColumns:()=>zE,listConnectSections:()=>CA,listConnectToolkits:()=>RA,listConnections:()=>fc,listConnectorAccounts:()=>bs,listConnectorMoves:()=>Nc,listConnectorTools:()=>hs,listConnectors:()=>Cc,listCostByProject:()=>YR,listCredentialEvents:()=>xM,listCredentials:()=>PM,listCustomLlmProviders:()=>or,listDiscoverConnectors:()=>Ps,listDiscoverIntegrations:()=>TA,listDiscoverSections:()=>Wc,listDriveConflicts:()=>tI,listDriveFiles:()=>rI,listDriveFolder:()=>Ks,listDriveVersions:()=>uI,listEnv:()=>Hm,listFeaturedMarketplaces:()=>_g,listFields:()=>JE,listFiles:()=>on,listFolderPrincipals:()=>eI,listGatewayLogs:()=>Ep,listGitHubInstallations:()=>ha,listGitHubRepositories:()=>ba,listGitHubRepositoryBranches:()=>Sa,listGroupMembers:()=>ed,listGroupProjectGrants:()=>OC,listGroups:()=>Yp,listKortixProjectSessions:()=>uM,listKortixProjects:()=>aM,listKortixPty:()=>Jm,listLinkableGitHubInstallations:()=>_a,listManagedGitRepositories:()=>Aa,listMarketplaceCatalogItems:()=>yg,listMarketplaceSources:()=>Pg,listMarketplaces:()=>hg,listMemberGroups:()=>jC,listMemberProjectAccess:()=>DC,listMilestoneEvents:()=>fM,listMilestones:()=>gM,listMyAccountInvites:()=>Vi,listNotifications:()=>gm,listOAuthClients:()=>md,listOAuthGrants:()=>eg,listPendingApprovals:()=>Ga,listPendingProjectInvites:()=>ja,listPermissions:()=>wd,listPipedreamApps:()=>qc,listPipedreamSections:()=>Gc,listPolicies:()=>$C,listProjectAccess:()=>Ia,listProjectAccessRequests:()=>Ra,listProjectAgentIdentities:()=>od,listProjectAgents:()=>tM,listProjectAudit:()=>cg,listProjectBranches:()=>hl,listProjectCliTokens:()=>ng,listProjectCommits:()=>_l,listProjectDirectory:()=>ll,listProjectFiles:()=>cl,listProjectGoals:()=>SI,listProjectGroupGrants:()=>$a,listProjectPolicies:()=>Qc,listProjectProviderOAuth:()=>Qa,listProjectReminders:()=>er,listProjectResourceGrants:()=>Ba,listProjectSandboxTemplates:()=>Zc,listProjectSandboxes:()=>al,listProjectSecrets:()=>Va,listProjectSessions:()=>At,listProjectSessionsPage:()=>Fl,listProjectSnapshots:()=>el,listProjectTriggerEventApps:()=>Tu,listProjectTriggerEventTypes:()=>Cu,listProjectTriggerRuns:()=>Au,listProjectTriggers:()=>bu,listProjects:()=>xt,listProjectsForAccount:()=>ta,listPublicMarketplaceItems:()=>wU,listPublicMarketplaces:()=>vU,listReferrals:()=>fC,listReviewItems:()=>vd,listRoles:()=>rd,listRoomMessages:()=>qd,listRoomPeople:()=>Jd,listRooms:()=>Fd,listSandboxProjectMembers:()=>J0,listSandboxShares:()=>Id,listSandboxes:()=>G0,listScimTokens:()=>WC,listServiceAccountsApi:()=>gT,listServiceTemplates:()=>TM,listServices:()=>CM,listSessionConnectRequests:()=>kA,listSessionCosts:()=>pp,listSessionDrives:()=>gI,listSessionPrompts:()=>tu,listSessionProviderSecretPools:()=>dc,listSessionPublicShares:()=>Vl,listSessionReminders:()=>Od,listSessionsNeedingInput:()=>Wa,listSignedInDevices:()=>qT,listSsoGroupMappings:()=>sT,listTaskEvents:()=>EE,listTasks:()=>TE,listTemplates:()=>XE,listTicketEvents:()=>NE,listTickets:()=>UE,listTriggerRuns:()=>ku,loadHttpSessionHistory:()=>rv,loadPreviewUrlTemplate:()=>it,looksLikeError:()=>yy,looksLikeHtml:()=>uL,looksLikeJsonPayload:()=>sL,makeDriveFolder:()=>aI,mapApiReviewItem:()=>CC,markInstanceError:()=>_U,markNotificationsRead:()=>mm,markRoomRead:()=>Wd,markSessionFresh:()=>Kn,maxWireIdClock:()=>Km,memoryRelPath:()=>U$,mergeBurstSteps:()=>vy,mergeChangeRequest:()=>Cl,messageCreatedAt:()=>YL,messageTime:()=>nx,migrateAdminSandboxProvider:()=>jT,mintWireMessageId:()=>bo,mintWireMessageIdAbove:()=>qm,mkdir:()=>un,modelInDefaultView:()=>Wv,modelRefToKey:()=>vn,moveConnector:()=>Bc,moveDriveFile:()=>cI,narrateFailedStep:()=>Sy,narrateStep:()=>Nr,narrationToolName:()=>Fr,narrowChatEvent:()=>Xb,newestWireIdClock:()=>Ib,nextConnectorPollDelay:()=>JU,normalizeActivityToolName:()=>fe,normalizeAppPathname:()=>C0,normalizeCaptureAppId:()=>aj,normalizeCaptureDomain:()=>ij,normalizeExternalInput:()=>YO,normalizeName:()=>Z,normalizeToolName:()=>ay,notifyHostSignal:()=>rw,openChangeRequest:()=>Rl,openEventStream:()=>wo,openStressTestStream:()=>GU,paginateConnector:()=>Jc,parseBillingError:()=>Rn,parseEmbeddedFailure:()=>aL,parseFlagOverride:()=>dE,parseJsonFailure:()=>hy,parseLocalhostUrl:()=>Cr,parseMemoryView:()=>F$,parseOpenCodeErrorPayload:()=>T0,parsePresentationOutput:()=>K$,parseProxyHop:()=>pf,parseQuestionAnswersFromOutput:()=>Ly,parseReadOutput:()=>q$,parseRuntimeErrorPayload:()=>Ny,parseScrapeInputUrls:()=>qP,parseScrapeOutput:()=>WP,parseSubdomainUrl:()=>ff,parseTaskRows:()=>j$,parseWebProxyUrl:()=>HO,parseWebSearchOutput:()=>_y,partOutcome:()=>Bo,patchKortixProject:()=>dM,patchVerb:()=>B$,pickerProviderList:()=>Uv,pipedreamConnect:()=>$c,pipedreamConnectConnection:()=>Ac,pipedreamFinalize:()=>Yc,pipedreamFinalizeConnection:()=>Rc,platformConfig:()=>I,pollConnectionOAuth2DeviceAuthorization:()=>PA,pollProjectProviderOAuth:()=>gs,postRoomMessage:()=>Gd,previewBillingPlan:()=>sp,previewGatewayRoute:()=>Ip,previewMfaRequired:()=>YC,previewSlackIdentity:()=>eC,previewTeamsIdentity:()=>tC,probeEffectivePermission:()=>dd,probeEffectivePermissions:()=>gd,probePreviewPort:()=>hF,projectArchiveRequest:()=>gl,projectCompacting:()=>FF,projectConfigAgentsToOpenCodeAgents:()=>Av,projectConfigAgentsToRuntimeAgents:()=>lh,projectSessionConnection:()=>xF,projectSessionForRuntimeId:()=>sN,projectSessionStartSeed:()=>Eu,projectWorking:()=>jF,provisionProject:()=>aa,provisionProjectStream:()=>Kk,provisionProjectWithToken:()=>Qk,proxyLocalhostUrl:()=>mf,proxyUrlToInternal:()=>KO,purchaseCredits:()=>tp,putConnectionOAuth2Application:()=>mA,putCustomLlmProvider:()=>ir,rawErrorText:()=>Tr,reactivateSandbox:()=>Y0,reactivateSubscription:()=>Qu,readBlob:()=>cn,readDriveFile:()=>am,readFile:()=>an,readKortixMember:()=>ci,readProjectFile:()=>pl,readSavedSessionCopy:()=>fv,reasoningIsRunning:()=>Ho,rebuildProjectSnapshot:()=>tl,reconcileConnection:()=>hc,reconcileMemberConnection:()=>_c,reconcileServices:()=>MM,recordPlatformLogout:()=>TU,recoverLinkResults:()=>Ko,recoverProjectSession:()=>lu,refreshReferralCode:()=>dC,refreshSession:()=>Jt,registerAppArtifact:()=>Ns,registerConnectionOAuth2Client:()=>_A,registerDeviceToken:()=>um,registerService:()=>OM,registerWebPushSubscription:()=>_m,rejectProjectAccessRequest:()=>Ta,relativizePath:()=>lD,releaseDeviceToken:()=>dm,reloadProjectSessionConfig:()=>du,reloadProjectSessionConfigStream:()=>gu,removeAccountAuditWebhook:()=>gg,removeAccountBrandingAsset:()=>Ni,removeAccountMember:()=>Qi,removeGroupMember:()=>nd,removeKortixPty:()=>Zm,removeMarketplaceSource:()=>wg,removeProjectSkill:()=>ga,removeQueued:()=>sP,removeRoomPerson:()=>Yd,removeRoomSession:()=>Vd,renameConnection:()=>wc,renameFile:()=>Ar,renameSandbox:()=>q0,reopenChangeRequest:()=>Il,reopenMilestone:()=>bM,reorderQueued:()=>iP,replaceColumns:()=>YE,replaceFields:()=>QE,replaceProjectRepository:()=>fa,replaceTemplates:()=>ZE,replayTriggerRun:()=>Ru,repositoryDisconnectedReason:()=>_h,requestAccountDeletion:()=>AT,requestChangesOnChangeRequest:()=>El,requestProjectAccess:()=>Zk,requestProjectConnector:()=>fg,requestProjectSecret:()=>mg,requestTopUp:()=>GR,requireKortixMember:()=>xv,resendAccountInvite:()=>Hi,resendPendingProjectInvite:()=>La,resetAccountBranding:()=>Bi,resetClient:()=>LM,resetGatewayRoutingPolicy:()=>Tp,resetPassword:()=>co,resetPublicClient:()=>FM,resetSandboxUpdateStatus:()=>gU,resolveApproval:()=>Ha,resolveComposerAgent:()=>kv,resolveComposerModel:()=>Qv,resolveConnectorStart:()=>YU,resolveModelDefault:()=>Hv,resolvePublicShareUrl:()=>xR,resolveScrapeResults:()=>pL,resolveWorkingTurn:()=>Ty,resolvedPlan:()=>BR,restartAppMachine:()=>Vg,restartProjectSession:()=>Yn,restartSandbox:()=>H0,restoreAppVolume:()=>rm,restoreBackup:()=>sU,restoreDriveVersion:()=>pI,restoreProjectSession:()=>uu,retryAccountSecretResource:()=>ic,retryFailed:()=>rP,retrySessionPrompt:()=>ou,revealCredential:()=>vM,reviewItemTarget:()=>Vp,reviewSegmentForStatus:()=>C_,reviewVerdictAllowed:()=>MC,reviewVerdictForStatus:()=>_C,revokeAccountSecretResourceGrant:()=>lc,revokeAccountSession:()=>uT,revokeAccountToken:()=>Zd,revokeAssignment:()=>xd,revokeCaptureDevice:()=>xf,revokeCaptureEnrollmentToken:()=>Af,revokeConnection:()=>Sc,revokeGatewayKey:()=>qp,revokeOAuthGrant:()=>tg,revokePendingProjectInvite:()=>Da,revokeProjectAccess:()=>Ma,revokeProjectCliToken:()=>sg,revokeSandboxProjectAccess:()=>X0,revokeSandboxShare:()=>Md,revokeScimToken:()=>VC,revokeSessionPublicShare:()=>Yl,rewriteLocalhostUrl:()=>dt,rollbackApp:()=>Kg,rootRuntimeSession:()=>nw,rotateAccountSecretResource:()=>oc,rotateOAuthClientSecret:()=>_d,runConnector:()=>ks,runGatewayPlayground:()=>Gp,runProjectProviderOAuthFlow:()=>sA,runSessionReminder:()=>Dd,runtimeSessionsOf:()=>ti,runtimeSupports:()=>yS,sanitizePtyChunk:()=>Ub,saveGitHubInstallation:()=>Pa,savedCopyEmptyRoot:()=>sh,scaleApp:()=>Yg,scheduleDowngrade:()=>Xu,searchCapture:()=>$f,searchConnectorTools:()=>mc,searchMyCapture:()=>Hf,searchProjectFiles:()=>ul,segmentTurn:()=>ky,selectableProjectAgents:()=>mE,sendMagicLink:()=>so,sendReferralEmails:()=>yC,serverCompactionRevalidateAtMs:()=>BF,serviceAction:()=>EM,sessionConnectionLabel:()=>eN,sessionListStatus:()=>ZF,sessionLogActivityText:()=>Ow,sessionLogAnsweredQuestionCall:()=>Fw,sessionLogBurstRunning:()=>Lw,sessionLogBurstSteps:()=>Mw,sessionLogBurstSummary:()=>jw,sessionLogBurstWorkLabel:()=>Dw,sessionLogCallStatus:()=>vw,sessionLogFullTextAction:()=>Jw,sessionLogFullTextPlan:()=>Qw,sessionLogHarnessSwitches:()=>Ww,sessionLogOfV1Rows:()=>fw,sessionLogOpenCall:()=>$w,sessionLogPromptMessage:()=>kw,sessionLogReferencedTexts:()=>zw,sessionLogRestoreNotice:()=>Hw,sessionLogRetrying:()=>eh,sessionLogShowGroupCall:()=>Uw,sessionLogThreadMetrics:()=>Kw,sessionLogTurnSegments:()=>Iw,sessionLogTurns:()=>si,sessionLogWithFullTexts:()=>Xw,sessionModelCandidates:()=>Jv,sessionModelFallback:()=>zv,sessionModelPin:()=>Qn,sessionParentId:()=>bR,sessionPickStands:()=>Yv,sessionPromptActions:()=>RR,sessionStartKey:()=>jR,setAccountAutomationsPaused:()=>TR,setAccountSecretResourceAccess:()=>uc,setActiveInstanceCookie:()=>A0,setAdminBypass:()=>Ch,setAdminProviderDistribution:()=>MT,setAdminProviderFallback:()=>LT,setAgentScope:()=>Lu,setBillingPlan:()=>op,setBootstrapAuthToken:()=>iA,setCachedAuthToken:()=>oA,setCaptureEnabled:()=>Wf,setCapturePolicy:()=>Ef,setCaptureStorage:()=>Of,setConnectionPolicies:()=>vA,setConnectorAuthorizationStrategy:()=>Ec,setConnectorCredential:()=>Vc,setConnectorCredentialMode:()=>Ic,setConnectorName:()=>Lc,setConnectorPolicies:()=>jc,setConnectorSecretBinding:()=>EA,setConnectorSensitive:()=>Mc,setDefaultConnection:()=>xc,setDefaultReasoningEffort:()=>Wk,setEnterpriseDemo:()=>wT,setEnv:()=>Vm,setGatewayBudget:()=>Fp,setGatewayRoutingPolicy:()=>Cp,setGitHubAppFromExisting:()=>eF,setGitHubAppPat:()=>tF,setImpersonationSession:()=>Pk,setMaintenanceConfig:()=>NU,setMemberSuperAdmin:()=>GC,setMfaRequired:()=>JC,setModelDefault:()=>ju,setPersonalProjectSecret:()=>ec,setProjectModelAccess:()=>sr,setProjectModelEnablement:()=>DR,setProjectOnboardingComplete:()=>pa,setProjectOnboardingProfile:()=>zk,setProjectPolicies:()=>Xc,setProjectSecretStrategy:()=>Ya,setProjectSessionModel:()=>yu,setProjectSessionScope:()=>fu,setProjectSessionSharing:()=>Nl,setProjectTriggersActivation:()=>wu,setSavedCopyStore:()=>gR,setSessionArchived:()=>Wl,setSessionOversight:()=>XC,setSessionPinned:()=>Gl,setSessionProviderSecretPool:()=>gc,setSessionWatch:()=>ql,setTelegramAllowedUsers:()=>oC,settleSessionConnection:()=>AF,setupSSH:()=>iU,shareConnection:()=>kc,shareFolder:()=>XT,shellActivityGroupLabel:()=>ZI,shellExitCode:()=>Uy,shouldAttachImpersonation:()=>Ah,shouldHideResponsePart:()=>f$,shouldShowToolPart:()=>gn,shouldSuppressWorkingTurnBusy:()=>i$,showGroupItems:()=>Ry,showTurnBusyIndicator:()=>Cy,signInWithPassword:()=>ro,signInWithProvider:()=>io,signInWithSso:()=>go,signOut:()=>fo,signOutDevice:()=>GT,signUp:()=>no,skillDocumentPath:()=>J$,skillInputDir:()=>V$,sortSessions:()=>BD,splitSessionLogTurnWork:()=>Ew,splitTurnWork:()=>Dy,splitUserParts:()=>Xj,startApp:()=>Fg,startAppMachine:()=>Wg,startConnectionOAuth2Authorization:()=>bA,startConnectionOAuth2DeviceAuthorization:()=>SA,startConnectorSetupLink:()=>OU,startGitHubAppManifest:()=>ZU,startProjectProviderOAuth:()=>ds,startProjectSession:()=>nt,startProjectSessionOrThrow:()=>Mu,startSessionWithToken:()=>UU,startTask:()=>DE,stepLabel:()=>yn,stopApp:()=>Ng,stopAppMachine:()=>Hg,stopProjectSession:()=>Jn,stopSandbox:()=>V0,storeGitHubUserToken:()=>wa,stripAnsi:()=>iy,stripInstancePrefix:()=>v0,stripTrailingSlashes:()=>le,subAgentCalls:()=>Bw,submitAccessRequest:()=>CU,submitDemoRequest:()=>KU,submitOAuthConsent:()=>EU,submitReviewItem:()=>Rd,submitSecretSetupLink:()=>LU,subscribeToImpersonation:()=>xk,supabaseClient:()=>Dk,syncConnectors:()=>Tc,syncSubscription:()=>zR,systemReload:()=>BM,toDaemonPath:()=>pt,toInstanceAwarePath:()=>R0,toInternalUrl:()=>TS,toSandboxAbsolutePath:()=>sn,toToolView:()=>uy,toWorkspaceRelative:()=>cf,toolCallBlock:()=>ur,toolCallError:()=>nb,toolCallMetadata:()=>X_,toolCallRawOutput:()=>tb,toolCallStatus:()=>eb,toolInfo:()=>Do,toolKind:()=>ae,toolViewModel:()=>bx,transferProject:()=>Yk,triggerControlsFrom:()=>IC,triggerSandboxUpdate:()=>dU,triggersRequest:()=>Db,turnEndCause:()=>Zx,turnEndNotice:()=>$F,turnHasSteps:()=>VD,turnIsConfirmedActive:()=>l$,turnRendersQueued:()=>u$,turnRetryLabel:()=>nN,unassignTicket:()=>WE,unregisterDeviceToken:()=>pm,unregisterWebPushSubscription:()=>bm,unshareFolder:()=>ZT,untimedAnchorOf:()=>my,unwrapError:()=>ye,updateAccountAuditWebhook:()=>dg,updateAccountBranding:()=>Ui,updateAccountMemberRole:()=>Xi,updateAccountName:()=>Li,updateAgentConfig:()=>UR,updateApp:()=>Ag,updateAppAccess:()=>Mg,updateAppVolume:()=>Zg,updateAuditWebhook:()=>bT,updateChangeRequest:()=>Ol,updateChannelBinding:()=>lC,updateConnectionCredential:()=>bc,updateEmailPolicy:()=>Ap,updateExperimentalFeature:()=>la,updateFeatureFlag:()=>ca,updateGroup:()=>Xp,updateKortixPty:()=>Xm,updateMilestone:()=>hM,updateNotificationPreferences:()=>ym,updateOAuthClient:()=>hd,updatePassword:()=>lo,updatePatPolicy:()=>dT,updatePolicy:()=>FC,updateProject:()=>On,updateProjectAccess:()=>Ea,updateProjectAgent:()=>rM,updateProjectDefaultAgent:()=>Uu,updateProjectGroupGrant:()=>Fa,updateProjectSandboxProvider:()=>ua,updateProjectSession:()=>au,updateProjectTrigger:()=>Pu,updateRole:()=>ld,updateRolePermissions:()=>ud,updateRoom:()=>Kd,updateSandboxTemplate:()=>sl,updateSessionPolicy:()=>cT,updateSessionReminder:()=>$s,updateSessionReminders:()=>Ld,updateTask:()=>jE,updateTemplateWarmPool:()=>Vk,updateTicket:()=>KE,updateTicketStatus:()=>qE,updateUserMetadata:()=>po,uploadAccountBrandingAsset:()=>Fi,uploadAppArtifactArchive:()=>jg,uploadConnectorAttachment:()=>Ss,uploadDriveFile:()=>oI,uploadFile:()=>ln,uploadNativeFile:()=>aS,uploadPromptAttachment:()=>Bn,uploadSessionAttachment:()=>Dm,uploadSlackChannelFile:()=>Sp,uploadTimeoutMsForBytes:()=>nn,upsertCredential:()=>wM,upsertProjectGitCredential:()=>Za,upsertProjectSecret:()=>za,upsertSsoProvider:()=>eT,validateProjectManifest:()=>ra,validateReferralCode:()=>gC,validateToken:()=>ea,verifyGatewayProvider:()=>uC,verifyKortixToken:()=>vv,verifyOtp:()=>oo,verifySsoDomain:()=>nT,wakeEscalationAttemptSummary:()=>QF,wakeEscalationNote:()=>YF,wakeProgressFingerprint:()=>WF,wireIdClock:()=>Tt,wireIdClockAt:()=>Zt,wireIdClockDelta:()=>It,workedForLabel:()=>T$,workingExpiryAtMs:()=>DF,workingTurnDrawsBusyRow:()=>p$,writeActivityGroupLabel:()=>eE,writeFile:()=>kr,writeProjectFile:()=>ml,wsDomain:()=>Go,wsFavicon:()=>lL,wsRootDomain:()=>cL});var ok={backendUrl:"",getToken:async()=>null},di=null,Zr=null;function ik(e){Zr=e}function ak(){return Zr}function es(e,t){t?.global!==!1&&(di=e)}function I(){return Zr?.()??di??ok}function ts(){return di!==null||Zr?.()!==void 0}function ck(e){return new Promise(t=>setTimeout(t,e))}async function ns(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 ck(s)),i=await e(),i)return i;return i}var gi=12e4;function lk(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function fh(e,t,n=gi){let r=e instanceof Request?e.signal:t?.signal;if(lk(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function rs(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var _=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},re=class extends _{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},et=class extends _{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},bt=class extends _{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},uk="ENDPOINT_RETIRED";function N(e,t){let n=t?` ${t}`:"";return new _(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:uk})}var jt="feature_disabled";function yh(e){if(!(e instanceof _)||e.status!==403||e.code!==jt)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function mi(e){let t=yh(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function fi(e){let t=yh(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",pk=new Set(["app_uninstalled","app_suspended","repo_not_accessible"]);function hh(e){return!!e&&typeof e=="object"&&e.code===An}function _h(e){if(e?.status!=="error")return null;let t=e.last_error_code;return t&&pk.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 yi(e){return e instanceof et}function Dt(e){if(e instanceof re)return!0;let t=e?.status;return t===401||t===403}function hi(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 ss(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 bh="request_deadline",dk=/^Request exceeded the \d+s server processing deadline$/,Sh=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===bh||dk.test(n),gk="git_mirror_unavailable",mk=/^git mirror is temporarily unavailable$/,fk=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===gk||mk.test(n),yk="connectors_provider_unavailable",hk=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===yk;async function _k(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 bk(e,t,n){return Sh(e,t,n)||fk(e,t,n)||hk(e,t)||e===403&&t?.code===jt||e===501&&t?.code===_i||e===409&&(t?.code===bi||t?.code===Si||t?.code===Pi||t?.code===An)||e===503&&(t?.code===xi||t?.code===wi)}async function Ph(e,t,n,r){let{message:s,data:o}=await _k(e,t),i=new _(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Sh(e.status,o,s)?bh: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&&!bk(e.status,o,s)&&I().onError?.(i,r),{error:i,success:!1}}var xh="X-Kortix-Impersonate",ki="kortix.impersonation",St=null,os=!1,vi=new Set;function Ai(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function wh(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 Sk(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 vh(){for(let e of vi)try{e()}catch{}}function kh(){return os||(os=!0,St=Sk(Ai()?.getItem(ki)??null)),St&&!wh(St)?(Ri(),null):St}function Pk(e){if(os=!0,!e){Ri();return}St=e;try{Ai()?.setItem(ki,JSON.stringify(e))}catch{}vh()}function Ri(){os=!0;let e=St!==null;St=null;try{Ai()?.removeItem(ki)}catch{}e&&vh()}function xk(e){return vi.add(e),()=>{vi.delete(e)}}var wk=/(^|\/)admin\/(api|analytics)(\/|$)/;function Ah(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!wk.test(t)}function Ci(e){if(e!==void 0&&!Ah(e))return{};let t=kh();return t?{[xh]:t.grantId}:{}}function Ch(e){}function Th(){return!1}function vk(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function is(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 as(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(vk))Cn(n,s,o);return n}function Ii(e,t,n){let r={...t},s=I().clientVersion?.trim();s&&!is(r,"x-kortix-client-version")&&Cn(r,"X-Kortix-Client-Version",s);for(let[i,a]of Object.entries(Ci(e)))Cn(r,i,a);let o=I().credentialHeader?.trim();return o?is(r,o)||Cn(r,o,n):is(r,"authorization")||Cn(r,"Authorization",`Bearer ${n}`),r}async function Lt(e,t){let n=await cs();if(!n)throw new re;return{headers:new Headers(Ii(e,as(e,{headers:t}),n)),rejected:()=>Tn(n)}}function kk(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function Rh(e,t,n,r,s){if(t instanceof Request){let l=new Headers(Ii(t.url,as(t,n),r));return e(new Request(t,{headers:l,...s?{signal:s}:{}}))}let o=String(t),i=Ii(o,as(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var Ih=null;async function Ei(e){let t=await ns(()=>I().getToken(),e);return t&&(Ih=t),t}var cs=Ei;function Tn(e=Ih){e&&I().getToken.invalidate?.(e)}var Ti=new Map;function Ak(e){let t=Ti.get(e);if(t)return t;let n=(async()=>(Tn(e),cs({attempts:2,baseDelayMs:200})))().finally(()=>Ti.delete(e));return Ti.set(e,n),n}async function Pt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=gi}=n,o=n.fetch??I().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:fh(e,t,s);if(i?.aborted)throw Ae();let a=await(i?Re(cs(),i):cs());if(!a)throw new re;let l=r&&!kk(t)&&!is(as(e,t),"authorization"),p=l&&e instanceof Request?e.clone():e,d=await Rh(o,e,t,a,i);if(d.status!==401||!l)return d;let g=await Ak(a);return!g||g===a?d:Rh(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 _(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var Eh=()=>I().backendUrl||"",Rk=new Set([502,503,504]),Ck=e=>Rk.has(e),Mh=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Tk=e=>Mh(e)||(e??"GET").toUpperCase()==="DELETE",Ik=2,ls=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 Ek(e,i,n,r,s,o,a,l)}finally{i.signal?.removeEventListener("abort",p)}}async function Ek(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 Ok(e,t,l,s,o,i,a);if(p instanceof re)return{error:p,success:!1};if(!p.ok)return await Ph(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 jk(l,e,t.method,n,r,s,a)}finally{us(a)}}function us(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Mk(e,t,n){try{await Re(e.arrayBuffer(),t)}catch(r){if(ls(r))throw r}finally{us(n)}}async function Ok(e,t,n,r,s,o,i){let a=Mh(t.method),l=Tk(t.method),p=l?Ik+1:1,d;for(let g=0;g<p;g++){g>0&&await ss(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&&ls(f)&&!t.signal?.aborted&&l&&g<p-1){i.didTimeout=!1;continue}if(ls(f)||g===p-1)throw f;continue}if(!a||!Ck(d.status)||g===p-1)return s||us(i),d;await Mk(d,m.signal,i)}return d}function jk(e,t,n,r,s,o,i){us(i);let a=ls(e);a&&(i.isAborted=!0);let l;if(a){if(!i.didTimeout)return{error:new _("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(Eh(),"")||t;l=new _(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(l=new _(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(Eh(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&I().onError?.(l,s)):(l=new _(String(e)),r&&I().onError?.(l,s));return{error:l,success:!1}}var Ue=()=>I().backendUrl||"",_i="feature_not_supported",bi="model_not_servable",Si="provision_in_flight",Pi="sandbox_state_change_in_progress",xi="analytics_unavailable",wi="accounts_list_unavailable",Dk={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new _(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 _(n.message,{name:n.name||"ApiError",stack:n.stack}):new _(String(n));return I().onError?.(r,t),{error:r,success:!1}}}};async function Lk(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 rs();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:Lk};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function Mi(e){return e.replace(/\/v1\/?$/,"")}async function $t(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=Mi(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 Oi(){return u(await c.get("/accounts"))}async function ji(e){return u(await c.post("/accounts",e))}async function Di(e){return u(await c.get(`/accounts/${e}`))}async function Li(e,t){return u(await c.patch(`/accounts/${e}`,{name:t}))}async function $i(e){return u(await c.get(`/accounts/${e}/branding`))}async function Ui(e,t){return u(await c.put(`/accounts/${e}/branding`,t))}async function Fi(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 Ni(e,t){return u(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function Bi(e){return u(await c.delete(`/accounts/${e}/branding`))}async function Ki(e){return u(await c.get(`/accounts/${e}/members`))}async function qi(e,t){return u(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Gi(e){return u(await c.get(`/accounts/${e}/invites`))}async function Wi(e,t){return u(await c.delete(`/accounts/${e}/invites/${t}`))}async function Hi(e,t){return u(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Vi(){return u(await c.get("/account-invites",{showErrors:!1})).invites}async function zi(e){return u(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function ps(e){return u(await c.post(`/account-invites/${e}/accept`,{}))}function Oh(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 Yi(e,t){let n=await ps(e);return{accepted:n,landing:Oh(n,t)}}async function Ji(e){return u(await c.post(`/account-invites/${e}/decline`,{}))}async function Qi(e,t){return u(await c.delete(`/accounts/${e}/members/${t}`))}async function Xi(e,t,n){return u(await c.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Zi(e){return u(await c.post(`/accounts/${e}/leave`,{}))}async function $k(e){return $t(e,"/v1/accounts")}async function ea(){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 Uk=["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 xt(){return u(await c.get("/projects"))}async function ta(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 na(e,t,n="write"){return u(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function ra(e,t){return u(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function sa(e){return u(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function Fk(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 Nk(e,t){return u(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function oa(e){return u(await c.post("/projects",e))}async function ia(e){return u(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function aa(e,t={}){return u(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Dh="provision_stream_unterminated",jh=200;function Bk(e){let t=e.split(`
1
+ "use strict";var Kortix=(()=>{var di=Object.defineProperty;var tv=Object.getOwnPropertyDescriptor;var nv=Object.getOwnPropertyNames;var rv=Object.prototype.hasOwnProperty;var sv=(e,t)=>{for(var n in t)di(e,n,{get:t[n],enumerable:!0})},ov=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of nv(t))!rv.call(e,s)&&s!==n&&di(e,s,{get:()=>t[s],enumerable:!(r=tv(t,s))||r.enumerable});return e};var iv=e=>ov(di({},"__esModule",{value:!0}),e);var OB={};sv(OB,{ABORT_REASONS:()=>wx,ABORT_REASONS_NOT_YET_EMITTED:()=>A0,ACCOUNTS_LIST_UNAVAILABLE_CODE:()=>ki,ACTIVE_INSTANCE_COOKIE:()=>Wr,ANALYTICS_UNAVAILABLE_CODE:()=>wi,ATTACHMENT_PART_REF_PREFIX:()=>Gx,ApiError:()=>_,AuthError:()=>re,BillingError:()=>et,CAPTURE_DEVICE_DEFAULTS:()=>lj,CAPTURE_EXCLUSION_GROUPS:()=>oj,CAPTURE_FRAME_INTERVALS_MS:()=>aj,CAPTURE_LAYERS:()=>sj,CAPTURE_MAX_HEIGHTS:()=>cj,CAPTURE_RETENTION_LIMITS:()=>ij,CONNECTION_FAULT_GRACE_MS:()=>Xx,CONNECTOR_POLL_FIRST_DELAY_MS:()=>Fx,CONNECTOR_POLL_INTERVAL_MS:()=>Nx,CONNECTOR_POLL_WINDOW_MS:()=>Bx,CONTEXT_TOOLS:()=>IP,COST_MARKUP:()=>Dy,ConnectorApprovalPendingError:()=>ws,ConnectorCallError:()=>Un,ConnectorPageLimitError:()=>ks,DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS:()=>EP,DEFAULT_NOTIFICATION_PREFERENCES:()=>TI,DEFAULT_TRANSCRIPT_OPTIONS:()=>Xf,DESTRUCTIVE_PHASES:()=>Ox,FEATURE_DISABLED_CODE:()=>Dt,FEATURE_FLAG_KEYS:()=>Nv,FEATURE_NOT_SUPPORTED_CODE:()=>bi,FILE_VERBS:()=>mt,FileExistsError:()=>sn,HeadlessAuthError:()=>Jt,HostBoundaryError:()=>Vr,IMPERSONATION_HEADER:()=>kh,INBOX_NOTIFICATION_KINDS:()=>CI,INBOX_OBSERVATION_MAX_MS:()=>Zo,INITIAL_SETTLED_CONNECTION:()=>OF,INSTANCE_SCOPED_ROUTES:()=>kx,KNOWN_TOOL_KINDS:()=>Yh,KORTIX_TRANSCRIPT_SCHEMA:()=>ke,KortixMemberError:()=>yt,MAX_PROMPT_ATTACHMENTS_BYTES:()=>FA,MAX_PROMPT_ATTACHMENT_BYTES:()=>yl,MAX_PROMPT_ATTACHMENT_FILES:()=>qh,MEMORY_VERBS:()=>K$,MODEL_NOT_SERVABLE_CODE:()=>Si,NO_GROUP_ACTIVITY_TOOLS:()=>ob,OPTIMISTIC_ABORT_MAX_MS:()=>ei,OPTIMISTIC_COMPACTION_MAX_MS:()=>HF,OPTIMISTIC_RECEIPT_MAX_MS:()=>Qo,PERSISTED_QUERY_CACHE_VERSION:()=>yQ,PLUMBING_TOOLS:()=>QP,PREVIEW_PROBE_TIMEOUT_MS:()=>kF,PROJECT_ACTIONS:()=>X,PROJECT_SESSION_NAME_LOOKUP_LIMIT:()=>wR,PROJECT_SESSION_PAGE_DEFAULT_LIMIT:()=>xR,PROJECT_SESSION_PAGE_MAX_LIMIT:()=>d_,PROVISION_IN_FLIGHT_CODE:()=>Pi,PROVISION_STREAM_UNTERMINATED_CODE:()=>$h,PublicSessionShareError:()=>Ls,REPOSITORY_DISCONNECTED_CODE:()=>Cn,REVIEW_CONTROL_ACTIONS:()=>LC,RUNTIME_NOT_READY_MARKERS:()=>U0,RUNTIME_PERMISSION_CAPABILITIES:()=>OI,RUNTIME_PERMISSION_REPLIES:()=>MI,RequestTooLargeError:()=>bt,RuntimeNotReadyError:()=>nn,SANDBOX_FS_ROOTS:()=>vo,SANDBOX_PORTS:()=>Ke,SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE:()=>xi,SERVER_COMPACTION_REVALIDATE_MS:()=>nw,SERVER_OBSERVATION_MAX_MS:()=>Xo,SESSION_LIST_STATUS:()=>iN,SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES:()=>oi,SESSION_LOG_MINOR:()=>_e,SESSION_LOG_SCHEMA:()=>ce,SESSION_NOTICE:()=>lN,STANDALONE_TOOLS:()=>ib,STREAM_OBSERVATION_MAX_MS:()=>xn,SandboxNotReadyError:()=>Sn,SessionNotReadyError:()=>Tt,SessionStartError:()=>Es,TRIGGER_CONTROL_ACTIONS:()=>jC,TURN_END_LEDGER_LAG_MS:()=>FF,TURN_ERROR_CODES:()=>N_,WAKE_ESCALATION_COOLDOWN_MS:()=>XF,WAKE_MAX_RESTARTS:()=>QF,WAKE_NO_PROGRESS_MS:()=>JF,WIRE_ID_BACKDATE_MS:()=>_o,WIRE_ID_CLOCK_TOLERANCE:()=>ct,WIRE_ID_TIME_MASK:()=>Ve,WIRE_ID_TIME_SCALE:()=>Zt,WIRE_MESSAGE_ID:()=>Tb,__getConfigResolver:()=>lv,__setConfigResolver:()=>cv,abortErrorReason:()=>R0,acceptAccountInvite:()=>ps,acceptAccountInviteAndLand:()=>Ji,acceptEnterpriseOffer:()=>cp,acceptInvite:()=>oU,accountInviteLanding:()=>Dh,actReviewItem:()=>Id,activateConnection:()=>xc,addComputerToProject:()=>vc,addGroupMembers:()=>rd,addMarketplaceSource:()=>kg,addRoomPerson:()=>Jd,addRoomSession:()=>zd,advanceWakeEscalation:()=>tN,allDescendantIds:()=>BP,appendPreviewToken:()=>hF,approveCaptureDeviceGrant:()=>Gf,approveCaptureEnrollment:()=>If,approveCliDevice:()=>VT,approveProjectAccessRequest:()=>Ta,approveTask:()=>BE,archiveProject:()=>Ln,assignTicket:()=>YE,attachGroupToProject:()=>Fa,authMfa:()=>mo,authUser:()=>uo,authenticatedFetch:()=>$,authenticatedRequest:()=>Nn,authorizePreviewUrl:()=>wF,backendApi:()=>c,bindSlackIdentity:()=>rC,bindTeamsIdentity:()=>sC,brokerProjectSecretRequest:()=>Qa,browserKeyValueStorage:()=>mF,buildInstancePath:()=>Ax,buildPresentationTemplateImageUrl:()=>CF,buildPresentationTemplatePdfUrl:()=>RF,buildPreviewAuthEndpoint:()=>Vy,buildPublicTemplateUrl:()=>ZU,buildRuntimePresentationConversionUrl:()=>Qx,buildSandboxTemplate:()=>al,buildScrapeFailureResults:()=>HP,buildStaticFileHealthPreviewUrl:()=>WO,buildStaticFileLocalUrl:()=>GO,buildStaticFilePreviewUrl:()=>qO,buildStaticFileServicePath:()=>CS,buildTunnelEventStreamUrl:()=>fB,buildWebProxyUrl:()=>JO,bulkActReviewItems:()=>Ed,bulkDeletePolicies:()=>HC,bulkImportPolicies:()=>VC,burstSummary:()=>Wo,burstSummaryLabel:()=>XP,burstWorkLabel:()=>ky,callConnector:()=>kt,canManageBilling:()=>w_,canOfferTopup:()=>VR,cancelAccountDeletion:()=>MT,cancelAccountInvite:()=>Hi,cancelSandbox:()=>Z0,cancelSandboxUpdate:()=>bU,cancelScheduledChange:()=>tp,cancelSubscription:()=>Xu,captureHealthBucket:()=>gj,changeRequestControlsFrom:()=>E_,checkAccessEmail:()=>MU,checkMcpServerSignIn:()=>CA,childMapByParent:()=>WD,claimComputer:()=>kU,claimNext:()=>nP,claimPerSeatBilling:()=>XR,claimWarmProjectSession:()=>Zl,classifyPart:()=>gy,classifyPreviewProbeStatus:()=>Jx,classifyPtyClose:()=>Ub,classifySessionLogMessage:()=>Kw,classifyTurn:()=>Uo,cleanErrorMessage:()=>aL,cleanResultSnippet:()=>pL,cleanWorkerOutput:()=>L$,clearImpersonationSession:()=>Ci,clearKortixAppViewerCache:()=>bk,clearModelDefault:()=>$u,clearSessionFresh:()=>ZA,closeChangeRequest:()=>Il,closeMilestone:()=>wM,collectTurnParts:()=>JD,commentTicket:()=>QE,commitSessionChanges:()=>Ol,compactionExpiryAtMs:()=>zF,compactionTurnInfo:()=>zL,compareForDisplayAt:()=>No,compareMessagesForDisplay:()=>GD,compareSemver:()=>hj,completeInFlight:()=>rP,completeSlackInstall:()=>hp,completeTeamsInstall:()=>_p,composerSelectableAgents:()=>dh,computeStatusFromPart:()=>My,configureAutoTopup:()=>op,configureKortix:()=>es,confirmCheckoutSession:()=>Ju,connectEmail:()=>Ap,connectSlack:()=>fp,connectTelegram:()=>lC,connectionFromHealth:()=>MF,connectionIsFaulted:()=>EF,connectionSharedWithEveryone:()=>mA,connectorConnect:()=>Nh,connectorFinalize:()=>Bh,connectorHeadline:()=>oF,contactEnterpriseSales:()=>lp,contextLabelForTool:()=>SL,contextToolSummary:()=>zj,contextToolTrigger:()=>Yj,convertPresentationToGoogleSlides:()=>qT,convertRuntimePresentation:()=>TF,copyFile:()=>vr,costExportUrl:()=>pp,countLiveInboxPrompts:()=>BF,countReviewItemsBySegment:()=>xC,createAccount:()=>Di,createAccountAuditWebhook:()=>gg,createAccountSecretResource:()=>oc,createAccountToken:()=>eg,createApp:()=>Rg,createAppAccessSession:()=>Dg,createAppDeployment:()=>$g,createAppToken:()=>Ig,createAppVolume:()=>em,createAppVolumeSnapshot:()=>sm,createArtifactKind:()=>KL,createAssignment:()=>wd,createAuditWebhook:()=>wT,createBackup:()=>cU,createCaptureEnrollmentToken:()=>Rf,createCheckoutSession:()=>Yu,createConnector:()=>Fc,createConnectorLinkInfoCache:()=>nF,createFile:()=>kr,createGatewayKey:()=>Gp,createGroup:()=>Zp,createHttpSessionSyncController:()=>ik,createInstance:()=>PU,createKortix:()=>XS,createKortixPty:()=>Zm,createKortixSession:()=>yo,createMarketplaceInstallSession:()=>QT,createMilestone:()=>PM,createModelVisibility:()=>Hk,createOAuthClient:()=>_d,createPerSeatCheckout:()=>QR,createPersistedQueryCache:()=>gF,createPolicy:()=>qC,createPortalSession:()=>Qu,createProject:()=>ia,createProjectAgent:()=>aM,createProjectCliToken:()=>og,createProjectRepo:()=>aa,createProjectResourceGrant:()=>qa,createProjectSession:()=>Rt,createProjectSkill:()=>ga,createProjectTrigger:()=>xu,createPromptAttachmentController:()=>Pf,createRole:()=>ud,createRoom:()=>Kd,createSSEStream:()=>yB,createSandbox:()=>H0,createSandboxShare:()=>Od,createSandboxTemplate:()=>sl,createSavedCopyStore:()=>mR,createScimToken:()=>QC,createServiceAccountApi:()=>bT,createSessionPrompt:()=>Jn,createSessionPublicShare:()=>Yl,createSessionQueue:()=>eP,createSessionReminder:()=>Ld,createSsoGroupMapping:()=>uT,createTask:()=>UE,createTicket:()=>HE,createTunnelEventStream:()=>hB,createWarmSessionPool:()=>XN,currentSavedCopyStore:()=>Fl,declineAccountInvite:()=>Qi,declineInvite:()=>iU,deleteAccountImmediately:()=>OT,deleteAccountSecretResource:()=>cc,deleteApp:()=>Tg,deleteAppDeployment:()=>qg,deleteAuditWebhook:()=>vT,deleteBackup:()=>uU,deleteConnector:()=>qc,deleteConnectorCredential:()=>Yc,deleteCredential:()=>IM,deleteCustomLlmProvider:()=>cr,deleteDriveFile:()=>mI,deleteEnv:()=>Jm,deleteFile:()=>Mt,deleteGatewayBudget:()=>Kp,deleteGitHubInstallation:()=>va,deleteGroup:()=>td,deleteInstance:()=>xU,deleteKortixProject:()=>yM,deleteMilestone:()=>vM,deleteOAuthClient:()=>Pd,deletePersonalProjectSecret:()=>nc,deletePolicy:()=>WC,deleteProjectAgent:()=>lM,deleteProjectProviderOAuth:()=>Za,deleteProjectResourceGrant:()=>Ga,deleteProjectSecret:()=>$n,deleteProjectSession:()=>uu,deleteProjectTrigger:()=>ku,deletePromptAttachment:()=>Kt,deleteRole:()=>gd,deleteSandboxTemplate:()=>il,deleteServiceAccountApi:()=>PT,deleteSessionPrompt:()=>su,deleteSessionReminder:()=>Us,deleteSessionReminders:()=>Fd,deleteSsoGroupMapping:()=>pT,deleteSsoProvider:()=>cT,deleteTask:()=>KE,deleteTicket:()=>XE,denyCaptureDeviceGrant:()=>Wf,denyCaptureEnrollment:()=>Ef,describeAccountInvite:()=>Yi,describeConnectorTool:()=>_s,destroyAppMachine:()=>Jg,destroyAppVolume:()=>nm,detachGroupFromProject:()=>Ba,detectLocalhostUrls:()=>kS,directSubsessions:()=>pN,disableServiceAccountApi:()=>ST,disconnectEmail:()=>Rp,disconnectGitHubApp:()=>uF,disconnectSlack:()=>Sp,disconnectTelegram:()=>pC,discoverConnectionOAuth2:()=>_A,discoverConnectionOAuth2Resource:()=>bA,discoverConnectorAuth:()=>Nc,discoverLocalSandbox:()=>J0,dismissDriveConflict:()=>aI,downloadAccountAudit:()=>QU,downloadDriveFile:()=>lI,dropClientForUrl:()=>NM,dropPublicClientForUrl:()=>qM,editQueued:()=>aP,editSessionPrompt:()=>ou,enqueue:()=>tP,ensurePmSession:()=>oM,ensurePreviewSessionCookie:()=>Yx,ensureProjectConnectorConnection:()=>fA,ensureSandbox:()=>Mx,ensureWarmProjectSession:()=>Xl,env:()=>Lb,exchangeCode:()=>ao,execInApp:()=>Xg,exportAccountAudit:()=>pg,extractGatewayErrorDetails:()=>Se,extractInstanceRoute:()=>bn,extractSkillBaseDir:()=>hx,extractSkillContent:()=>Y$,extractSkillFiles:()=>yx,extractWorkerPreview:()=>U$,failInFlight:()=>sP,fallbackBusyRowAfterTurnId:()=>g$,familyForTool:()=>yn,featureDisabledKey:()=>yi,featureFlags:()=>Nm,fetchAccountStateWithToken:()=>zR,fetchAccountsWithToken:()=>Fv,fetchAttachmentPart:()=>fF,fetchCostExportCsv:()=>nC,fetchKortixAppViewer:()=>ch,fetchProjectArchive:()=>gl,fetchProjectFileRaw:()=>UA,fetchProjectsForAccountWithToken:()=>Xv,fetchSessionAttachment:()=>Um,fileDownloadRequest:()=>oS,filePhase:()=>B$,fileVerb:()=>N$,files:()=>mS,finalizeAppArtifact:()=>Bs,finalizeConnectorSetupLink:()=>FU,findActiveTranscriptShare:()=>vR,findFiles:()=>xr,findLastTextPart:()=>QD,findSessionAttachments:()=>fE,findText:()=>wr,fireProjectTrigger:()=>Au,fixSandboxWithAgent:()=>rl,flattenModels:()=>Bk,flattenThought:()=>ZL,forkAppVolume:()=>im,formatBillingErrorForUI:()=>_i,formatCost:()=>C$,formatDuration:()=>jy,formatJsonFailureOutput:()=>cL,formatMessageDay:()=>o$,formatMessageExact:()=>i$,formatOpenCodeRuntimeError:()=>K0,formatRawOutput:()=>uL,formatRuntimeError:()=>Ex,formatTokens:()=>T$,formatTranscript:()=>lP,freshSendHint:()=>h$,generateSessionId:()=>ZS,getAccount:()=>Li,getAccountAuditActivity:()=>lg,getAccountAutomations:()=>OR,getAccountBranding:()=>Ui,getAccountDeletionStatus:()=>IT,getAccountState:()=>Ku,getAccountStateMinimal:()=>qu,getActiveInstanceIdFromCookie:()=>Cx,getAdminProviderAnalytics:()=>UT,getAdminProviderDistribution:()=>DT,getAdminProviderFallback:()=>NT,getAdminRole:()=>jT,getAgentCardLabel:()=>jP,getAgentConfig:()=>KR,getAgentPersona:()=>uM,getAllVersions:()=>yU,getAnsweredQuestionParts:()=>ZD,getApp:()=>Fs,getAppAccess:()=>Mg,getAppAuthEnv:()=>Eg,getAppDeployment:()=>Fg,getAppDeploymentLogs:()=>Ng,getApprovalLink:()=>JT,getAuthToken:()=>Nt,getAuthTokenWithRetry:()=>lA,getAutoTopupSettings:()=>sp,getAutoTopupSetupStatus:()=>JR,getBillingCreditBreakdown:()=>Hu,getBillingTierConfigurations:()=>zu,getBillingTransactionsSummary:()=>Wu,getBillingUsageHistory:()=>Vu,getCaptureAssetUrl:()=>Kf,getCaptureChunkMedia:()=>Bf,getCaptureDays:()=>Uf,getCaptureDeviceGrant:()=>qf,getCaptureFrame:()=>Nf,getCapturePolicy:()=>Mf,getCaptureStorage:()=>jf,getCaptureTimeline:()=>Lf,getCaptureTimelineItems:()=>$f,getCaptureWorkspace:()=>Hf,getChangeRequest:()=>vl,getChangeRequestDiff:()=>Al,getChangeRequestMergePreview:()=>Rl,getChildSessionError:()=>lD,getChildSessionId:()=>Dr,getChildSessionToolParts:()=>uD,getClient:()=>ut,getClientForUrl:()=>Me,getConnectStatus:()=>Vc,getConnectionOAuth2Application:()=>hA,getConnectionOAuth2Status:()=>kA,getConnectionPolicies:()=>vA,getConnectorAppForm:()=>NU,getConnectorCatalog:()=>Bt,getConnectorConfig:()=>Lc,getConnectorPolicies:()=>jc,getConnectorSetupLink:()=>$U,getCostSummary:()=>tC,getCurrentInstanceIdFromPathname:()=>Rx,getCurrentInstanceIdFromWindow:()=>I0,getCurrentProject:()=>pf,getDefaultAccountState:()=>Bu,getDiagnostics:()=>fD,getDirectory:()=>OP,getDiscoverConnector:()=>xs,getDiscoverIntegration:()=>MA,getDriveFileUrl:()=>cm,getEmailInstallation:()=>kp,getEmailMode:()=>vp,getEnterpriseDemo:()=>RT,getFileStatus:()=>Pr,getFileWithDir:()=>iy,getFilename:()=>MP,getFolderAccess:()=>nI,getFullChangelog:()=>jx,getGatewayBreakdown:()=>$p,getGatewayBudgets:()=>Np,getGatewayErrors:()=>Fp,getGatewayKeys:()=>qp,getGatewayLog:()=>jp,getGatewayOverview:()=>Dp,getGatewayRoutingPolicy:()=>Tp,getGatewaySeries:()=>Lp,getGatewaySessions:()=>Up,getGitHubAppStatus:()=>iF,getGitHubInstallation:()=>ha,getGoogleAuthUrl:()=>KT,getGroup:()=>Xp,getHiddenToolParts:()=>sD,getImpersonationSession:()=>Rh,getInvite:()=>sU,getJustavpsServerTypes:()=>SU,getKortixProject:()=>gM,getKortixProjectBySession:()=>mM,getKortixPtyWebSocketUrl:()=>nf,getLatestSandboxVersion:()=>fU,getMaintenanceConfig:()=>VU,getManagedGitBackend:()=>Aa,getManagedGitStatus:()=>Hv,getMarketplaceCatalogItem:()=>Pg,getMarketplaceCatalogItemFile:()=>xg,getMfaRequired:()=>ZC,getMilestone:()=>bM,getMobileClientPolicy:()=>Qf,getModelDefaults:()=>Du,getMyCaptureFrame:()=>Jf,getMyCaptureTimeline:()=>Yf,getNotificationPreferences:()=>hm,getOAuthClient:()=>hd,getOAuthConsentRequest:()=>DU,getOpenCodeConfigInvalidError:()=>D0,getPartText:()=>tD,getPatPolicy:()=>yT,getPermissionForTool:()=>yD,getProject:()=>wt,getProjectActivity:()=>pM,getProjectCommit:()=>Sl,getProjectCommitDiff:()=>Pl,getProjectDetail:()=>Mn,getProjectDrive:()=>am,getProjectFileHistory:()=>xl,getProjectGitConnectionState:()=>eA,getProjectGitToken:()=>oa,getProjectGoalFiles:()=>AI,getProjectLlmCatalog:()=>On,getProjectLlmCatalogProviders:()=>Kv,getProjectModelAccess:()=>sr,getProjectModelPicker:()=>jn,getProjectQuota:()=>Wv,getProjectSandboxHealth:()=>Fn,getProjectSandboxProviderTransition:()=>zv,getProjectSession:()=>Vn,getProjectSessionConfigState:()=>gu,getProjectSessionScope:()=>yu,getProrationPreview:()=>np,getProviders:()=>G0,getProxyBaseUrl:()=>HO,getPublicClientForUrl:()=>KM,getPublicMarketplaceItem:()=>IU,getPublicMarketplaceItemFile:()=>EU,getPublicResponse:()=>WU,getPublicSessionShare:()=>GT,getPublicSessionShareMessages:()=>WT,getPublicShareByToken:()=>GU,getPublicTemplate:()=>eF,getQuestionForTool:()=>hD,getReferralCode:()=>yC,getReferralStats:()=>bC,getRetryInfo:()=>I$,getRetryMessage:()=>E$,getReviewItem:()=>Cd,getReviewSummary:()=>Rd,getRolePermissions:()=>cd,getRoleUsage:()=>ld,getRoom:()=>qd,getRuntimeConfigInvalidError:()=>Jo,getSSHConnection:()=>dU,getSandbox:()=>W0,getSandboxById:()=>V0,getSandboxPortUrl:()=>q0,getSandboxProvisionStatus:()=>vU,getSandboxProvisionStreamUrl:()=>AU,getSandboxUpdateStatus:()=>mU,getSandboxUrl:()=>qy,getSandboxUrlForExternalId:()=>Ie,getSecretSetupLink:()=>KU,getServerHealth:()=>Ao,getServiceLogs:()=>DM,getSessionAudit:()=>eu,getSessionCost:()=>R$,getSessionCostRecord:()=>er,getSessionDrives:()=>L_,getSessionHealth:()=>ff,getSessionLogPage:()=>nu,getSessionMessageAuthors:()=>bu,getSessionModelUsage:()=>Su,getSessionOpenBundle:()=>TR,getSessionOversight:()=>nT,getSessionParticipants:()=>Kl,getSessionPolicy:()=>dT,getSessionPreviewCandidates:()=>Vl,getSessionProviderSecretPool:()=>dc,getSessionTranscript:()=>tu,getSessionTranscriptSync:()=>zn,getSessionTurn:()=>Yn,getSessionWatch:()=>ql,getShellModePart:()=>D$,getSlackChannelFile:()=>Pp,getSlackInstallation:()=>mp,getSlackManifest:()=>bp,getSlackMode:()=>yp,getSsoProvider:()=>sT,getStaticFileHealthPath:()=>TS,getSupabaseAccessToken:()=>ms,getSupabaseAccessTokenWithRetry:()=>Fh,getTask:()=>DE,getTaskStatus:()=>$E,getTelegramInstallation:()=>cC,getTemplate:()=>XT,getTicket:()=>GE,getToolInfo:()=>dD,getToolPrimaryArg:()=>Oo,getTranscriptFilename:()=>uP,getTurnCost:()=>Yo,getTurnError:()=>P$,getTurnErrorDetails:()=>w$,getTurnErrorRawText:()=>x$,getTurnShare:()=>AR,getTurnStatus:()=>Oy,getUsageRollup:()=>up,getUserRolesWithToken:()=>YU,getVersionDiff:()=>wl,getWebPushPublicKey:()=>bm,getWorkingState:()=>b$,goalHealth:()=>$_,grantAccountSecretResource:()=>lc,grantSandboxProjectAccess:()=>nU,grantSecretToAgent:()=>GR,groupMessagesIntoTurns:()=>VD,groupShowSegments:()=>Cy,groupSteps:()=>vy,hasDiffs:()=>M$,hasLocalhostUrls:()=>NO,hasPreviewTarget:()=>RS,hasRetryingAssistantTurn:()=>hy,heartbeatGapEvent:()=>Zb,holdSessionPrompts:()=>cu,humanizeReviewActionPath:()=>Jp,humanizeSearchQuery:()=>Er,humanizeToolName:()=>uy,impersonationHeaders:()=>Ti,importSsoProviderFromMetadata:()=>iT,inboxObservationSupersedes:()=>NF,initialWakeEscalationState:()=>Yy,inputPath:()=>ve,installTemplate:()=>ZT,interruptSessionPrompt:()=>iu,invalidateTokenCache:()=>fs,inviteAccountMember:()=>Gi,inviteProjectMember:()=>ja,inviteRepoCollaborator:()=>ra,isAbortError:()=>Gr,isAdminBypassEnabled:()=>Eh,isAgentPart:()=>Jj,isAppRouteUrl:()=>wS,isAttachment:()=>nD,isAttachmentPartRef:()=>Wx,isAuthFailure:()=>Lt,isBillingError:()=>hi,isCompactionPart:()=>Qj,isConfigured:()=>ts,isContextTool:()=>Vj,isDestructivePhase:()=>gU,isEmptyConversation:()=>ah,isEmptyShowPart:()=>Zs,isErrorOutput:()=>eL,isExternalUrl:()=>ZO,isFeatureDisabledError:()=>fi,isFilePart:()=>ay,isImpersonationSessionLive:()=>vh,isInstanceDetailPath:()=>C0,isInstanceScopedAppPath:()=>vx,isInternalLocalhostUrl:()=>YO,isInvisibleActivityPart:()=>Mm,isInviteSent:()=>nA,isLastUserMessage:()=>_$,isLegacyMigratedSession:()=>rw,isManagedGithubProject:()=>Bv,isNoGroupActivityTool:()=>Em,isOfferedModel:()=>ui,isOpenCodeConfigInvalidError:()=>L0,isPaintableSavedCopy:()=>i_,isPatchPart:()=>Zj,isPersistableQueryKey:()=>dF,isPreviewUrl:()=>zO,isProxiableLocalhostUrl:()=>IS,isQuestionTool:()=>Im,isReasoningPart:()=>we,isRepositoryDisconnectedError:()=>bh,isRetryableTurnError:()=>KP,isRuntimeConfigInvalidError:()=>Tx,isRuntimeNotReadyResponse:()=>Ix,isRuntimeReady:()=>mf,isRuntimeStartingError:()=>B0,isSandboxNotReadyError:()=>Pn,isSelectableAgent:()=>to,isServerReachable:()=>df,isSessionAttachmentRef:()=>cE,isSessionFresh:()=>Dl,isSessionLogRestoreNote:()=>Hw,isSessionStartError:()=>$R,isShellActivityTool:()=>rE,isShellMode:()=>gx,isShortOutput:()=>$$,isShowContentUnavailable:()=>II,isShowPayloadEmpty:()=>lr,isSnapshotPart:()=>Xj,isStandaloneActivityTool:()=>Om,isStepPart:()=>eD,isSubdomainPreviewUrl:()=>zr,isTextPart:()=>Oe,isToolPart:()=>te,isToolPartHidden:()=>oD,isTurnErrorCode:()=>wm,isUnderSandboxRoot:()=>lf,isWebProxyUrl:()=>XO,isWireIdAheadOf:()=>Eb,kortixAppViewerToken:()=>Sk,kortixBinding:()=>Pk,kortixPty:()=>Bb,kortixToken:()=>lh,latestPromptModel:()=>Yk,leaveAccount:()=>ea,linkCaptureDevice:()=>vf,linkGitHubInstallation:()=>wa,linkRepository:()=>fa,listAccountAudit:()=>cg,listAccountAuditWebhooks:()=>dg,listAccountInvites:()=>Wi,listAccountMembers:()=>qi,listAccountResourceGrants:()=>BC,listAccountSecretResources:()=>sc,listAccountSessions:()=>mT,listAccountTokens:()=>Zd,listAccounts:()=>ji,listActions:()=>zC,listAdminSandboxes:()=>LT,listAgentIdentities:()=>id,listAllConnections:()=>hc,listAppAgents:()=>Og,listAppDeployments:()=>Ug,listAppMachines:()=>Wg,listAppVolumeSnapshots:()=>rm,listAppVolumes:()=>Zg,listApps:()=>Ag,listAssignments:()=>xd,listAuditEvents:()=>AT,listAuditWebhooks:()=>xT,listBackups:()=>aU,listBillingTransactions:()=>Gu,listCaptureDevices:()=>wf,listCaptureEnrollmentTokens:()=>Af,listCaptureEnrollments:()=>Tf,listChangeRequests:()=>kl,listChannelBindings:()=>gC,listColumns:()=>ZE,listConnectSections:()=>IA,listConnectToolkits:()=>TA,listConnections:()=>yc,listConnectorAccounts:()=>bs,listConnectorMoves:()=>Bc,listConnectorTools:()=>hs,listConnectors:()=>Tc,listCostByProject:()=>eC,listCredentialEvents:()=>RM,listCredentials:()=>AM,listCustomLlmProviders:()=>ir,listDiscoverConnectors:()=>Ps,listDiscoverIntegrations:()=>EA,listDiscoverSections:()=>Hc,listDriveConflicts:()=>iI,listDriveFiles:()=>cI,listDriveFolder:()=>Ks,listDriveVersions:()=>fI,listEnv:()=>zm,listFeaturedMarketplaces:()=>Sg,listFields:()=>tM,listFiles:()=>an,listFolderPrincipals:()=>oI,listGatewayLogs:()=>Op,listGitHubInstallations:()=>_a,listGitHubRepositories:()=>Sa,listGitHubRepositoryBranches:()=>Pa,listGroupMembers:()=>nd,listGroupProjectGrants:()=>UC,listGroups:()=>Qp,listKortixProjectSessions:()=>fM,listKortixProjects:()=>dM,listKortixPty:()=>Xm,listLinkableGitHubInstallations:()=>ba,listManagedGitRepositories:()=>Ra,listMarketplaceCatalogItems:()=>_g,listMarketplaceSources:()=>wg,listMarketplaces:()=>bg,listMemberGroups:()=>FC,listMemberProjectAccess:()=>NC,listMilestoneEvents:()=>SM,listMilestones:()=>_M,listMyAccountInvites:()=>zi,listNotifications:()=>fm,listOAuthClients:()=>yd,listOAuthGrants:()=>ng,listPendingApprovals:()=>Wa,listPendingProjectInvites:()=>Da,listPermissions:()=>vd,listPipedreamApps:()=>Gc,listPipedreamSections:()=>Wc,listPolicies:()=>KC,listProjectAccess:()=>Ea,listProjectAccessRequests:()=>Ca,listProjectAgentIdentities:()=>ad,listProjectAgents:()=>iM,listProjectAudit:()=>ug,listProjectBranches:()=>_l,listProjectCliTokens:()=>sg,listProjectCommits:()=>bl,listProjectDirectory:()=>ul,listProjectFiles:()=>ll,listProjectGoals:()=>vI,listProjectGroupGrants:()=>Ua,listProjectPolicies:()=>Xc,listProjectProviderOAuth:()=>Xa,listProjectReminders:()=>tr,listProjectResourceGrants:()=>Ka,listProjectSandboxTemplates:()=>el,listProjectSandboxes:()=>cl,listProjectSecrets:()=>za,listProjectSessions:()=>At,listProjectSessionsPage:()=>Nl,listProjectSnapshots:()=>tl,listProjectTriggerEventApps:()=>Eu,listProjectTriggerEventTypes:()=>Iu,listProjectTriggerRuns:()=>Cu,listProjectTriggers:()=>Pu,listProjects:()=>xt,listProjectsForAccount:()=>na,listPublicMarketplaceItems:()=>CU,listPublicMarketplaces:()=>TU,listReferrals:()=>SC,listReviewItems:()=>Ad,listRoles:()=>od,listRoomMessages:()=>Wd,listRoomPeople:()=>Xd,listRooms:()=>Bd,listSandboxProjectMembers:()=>tU,listSandboxShares:()=>Md,listSandboxes:()=>Y0,listScimTokens:()=>JC,listServiceAccountsApi:()=>_T,listServiceTemplates:()=>jM,listServices:()=>OM,listSessionConnectRequests:()=>RA,listSessionCosts:()=>gp,listSessionDrives:()=>_I,listSessionPrompts:()=>ru,listSessionProviderSecretPools:()=>gc,listSessionPublicShares:()=>zl,listSessionReminders:()=>Dd,listSessionsNeedingInput:()=>Ha,listSignedInDevices:()=>zT,listSsoGroupMappings:()=>lT,listTaskEvents:()=>LE,listTasks:()=>jE,listTemplates:()=>rM,listTicketEvents:()=>WE,listTickets:()=>qE,listTriggerRuns:()=>Ru,loadHttpSessionHistory:()=>ok,loadPreviewUrlTemplate:()=>it,looksLikeError:()=>_y,looksLikeHtml:()=>fL,looksLikeJsonPayload:()=>lL,makeDriveFolder:()=>dI,mapApiReviewItem:()=>OC,markInstanceError:()=>wU,markNotificationsRead:()=>ym,markRoomRead:()=>Vd,markSessionFresh:()=>Gn,maxWireIdClock:()=>Gm,memoryRelPath:()=>q$,mergeBurstSteps:()=>Ay,mergeChangeRequest:()=>Tl,messageCreatedAt:()=>e$,messageTime:()=>sx,migrateAdminSandboxProvider:()=>FT,mintWireMessageId:()=>bo,mintWireMessageIdAbove:()=>Wm,mkdir:()=>pn,modelInDefaultView:()=>Vk,modelRefToKey:()=>An,moveConnector:()=>Kc,moveDriveFile:()=>gI,narrateFailedStep:()=>xy,narrateStep:()=>Br,narrationToolName:()=>Nr,narrowChatEvent:()=>eS,newestWireIdClock:()=>Mb,nextConnectorPollDelay:()=>sF,normalizeActivityToolName:()=>fe,normalizeAppPathname:()=>O0,normalizeCaptureAppId:()=>dj,normalizeCaptureDomain:()=>pj,normalizeExternalInput:()=>ej,normalizeName:()=>ee,normalizeToolName:()=>ly,notifyHostSignal:()=>ow,openChangeRequest:()=>Cl,openEventStream:()=>wo,openStressTestStream:()=>XU,paginateConnector:()=>Qc,parseBillingError:()=>Tn,parseEmbeddedFailure:()=>dL,parseFlagOverride:()=>hE,parseJsonFailure:()=>by,parseLocalhostUrl:()=>Tr,parseMemoryView:()=>G$,parseOpenCodeErrorPayload:()=>j0,parsePresentationOutput:()=>V$,parseProxyHop:()=>gf,parseQuestionAnswersFromOutput:()=>Uy,parseReadOutput:()=>z$,parseRuntimeErrorPayload:()=>Ky,parseScrapeInputUrls:()=>WP,parseScrapeOutput:()=>VP,parseSubdomainUrl:()=>hf,parseTaskRows:()=>F$,parseWebProxyUrl:()=>QO,parseWebSearchOutput:()=>Sy,partOutcome:()=>Bo,patchKortixProject:()=>hM,patchVerb:()=>H$,pickerProviderList:()=>Nk,pipedreamConnect:()=>Uc,pipedreamConnectConnection:()=>Rc,pipedreamFinalize:()=>Jc,pipedreamFinalizeConnection:()=>Cc,platformConfig:()=>I,pollConnectionOAuth2DeviceAuthorization:()=>wA,pollProjectProviderOAuth:()=>gs,postRoomMessage:()=>Hd,previewBillingPlan:()=>ip,previewGatewayRoute:()=>Mp,previewMfaRequired:()=>eT,previewSlackIdentity:()=>oC,previewTeamsIdentity:()=>iC,probeEffectivePermission:()=>md,probeEffectivePermissions:()=>fd,probePreviewPort:()=>vF,projectArchiveRequest:()=>ml,projectCompacting:()=>VF,projectConfigAgentsToOpenCodeAgents:()=>Ck,projectConfigAgentsToRuntimeAgents:()=>ph,projectSessionConnection:()=>IF,projectSessionForRuntimeId:()=>dN,projectSessionStartSeed:()=>Ou,projectWorking:()=>KF,provisionProject:()=>ca,provisionProjectStream:()=>Gv,provisionProjectWithToken:()=>Zv,proxyLocalhostUrl:()=>yf,proxyUrlToInternal:()=>VO,purchaseCredits:()=>rp,putConnectionOAuth2Application:()=>yA,putCustomLlmProvider:()=>ar,rawErrorText:()=>Ir,reactivateSandbox:()=>eU,reactivateSubscription:()=>Zu,readBlob:()=>ln,readDriveFile:()=>lm,readFile:()=>cn,readKortixMember:()=>li,readProjectFile:()=>dl,readSavedSessionCopy:()=>hk,reasoningIsRunning:()=>Ho,rebuildProjectSnapshot:()=>nl,reconcileConnection:()=>_c,reconcileMemberConnection:()=>bc,reconcileServices:()=>$M,recordPlatformLogout:()=>jU,recoverLinkResults:()=>Ko,recoverProjectSession:()=>pu,refreshReferralCode:()=>hC,refreshSession:()=>Qt,registerAppArtifact:()=>Ns,registerConnectionOAuth2Client:()=>SA,registerDeviceToken:()=>dm,registerService:()=>UM,registerWebPushSubscription:()=>Sm,rejectProjectAccessRequest:()=>Ia,relativizePath:()=>mD,releaseDeviceToken:()=>mm,reloadProjectSessionConfig:()=>mu,reloadProjectSessionConfigStream:()=>fu,removeAccountAuditWebhook:()=>fg,removeAccountBrandingAsset:()=>Bi,removeAccountMember:()=>Xi,removeGroupMember:()=>sd,removeKortixPty:()=>tf,removeMarketplaceSource:()=>vg,removeProjectSkill:()=>ma,removeQueued:()=>iP,removeRoomPerson:()=>Qd,removeRoomSession:()=>Yd,renameConnection:()=>kc,renameFile:()=>Rr,renameSandbox:()=>z0,reopenChangeRequest:()=>El,reopenMilestone:()=>kM,reorderQueued:()=>cP,replaceColumns:()=>eM,replaceFields:()=>nM,replaceProjectRepository:()=>ya,replaceTemplates:()=>sM,replayTriggerRun:()=>Tu,repositoryDisconnectedReason:()=>Sh,requestAccountDeletion:()=>ET,requestChangesOnChangeRequest:()=>Ml,requestProjectAccess:()=>tA,requestProjectConnector:()=>hg,requestProjectSecret:()=>yg,requestTopUp:()=>YR,requireKortixMember:()=>kk,resendAccountInvite:()=>Vi,resendPendingProjectInvite:()=>$a,resetAccountBranding:()=>Ki,resetClient:()=>BM,resetGatewayRoutingPolicy:()=>Ep,resetPassword:()=>co,resetPublicClient:()=>GM,resetSandboxUpdateStatus:()=>_U,resolveApproval:()=>Va,resolveComposerAgent:()=>Rk,resolveComposerModel:()=>Zk,resolveConnectorStart:()=>rF,resolveModelDefault:()=>zk,resolvePublicShareUrl:()=>kR,resolveScrapeResults:()=>yL,resolveWorkingTurn:()=>Ey,resolvedPlan:()=>HR,restartAppMachine:()=>Yg,restartProjectSession:()=>Qn,restartSandbox:()=>Q0,restoreAppVolume:()=>om,restoreBackup:()=>lU,restoreDriveVersion:()=>yI,restoreProjectSession:()=>du,retryAccountSecretResource:()=>ac,retryFailed:()=>oP,retrySessionPrompt:()=>au,revealCredential:()=>TM,reviewItemTarget:()=>Yp,reviewSegmentForStatus:()=>I_,reviewVerdictAllowed:()=>$C,reviewVerdictForStatus:()=>wC,revokeAccountSecretResourceGrant:()=>uc,revokeAccountSession:()=>fT,revokeAccountToken:()=>tg,revokeAssignment:()=>kd,revokeCaptureDevice:()=>kf,revokeCaptureEnrollmentToken:()=>Cf,revokeConnection:()=>Pc,revokeGatewayKey:()=>Wp,revokeOAuthGrant:()=>rg,revokePendingProjectInvite:()=>La,revokeProjectAccess:()=>Oa,revokeProjectCliToken:()=>ig,revokeSandboxProjectAccess:()=>rU,revokeSandboxShare:()=>jd,revokeScimToken:()=>XC,revokeSessionPublicShare:()=>Jl,rewriteLocalhostUrl:()=>dt,rollbackApp:()=>Gg,rootRuntimeSession:()=>sw,rotateAccountSecretResource:()=>ic,rotateOAuthClientSecret:()=>Sd,runConnector:()=>vs,runGatewayPlayground:()=>Hp,runProjectProviderOAuthFlow:()=>iA,runSessionReminder:()=>$d,runtimeSessionsOf:()=>ti,runtimeSupports:()=>_S,sanitizePtyChunk:()=>Nb,saveGitHubInstallation:()=>xa,savedCopyEmptyRoot:()=>ih,scaleApp:()=>Qg,scheduleDowngrade:()=>ep,searchCapture:()=>Ff,searchConnectorTools:()=>fc,searchMyCapture:()=>zf,searchProjectFiles:()=>pl,segmentTurn:()=>Ry,selectableProjectAgents:()=>bE,sendMagicLink:()=>so,sendReferralEmails:()=>PC,serverCompactionRevalidateAtMs:()=>YF,serviceAction:()=>LM,sessionConnectionLabel:()=>cN,sessionListStatus:()=>aN,sessionLogActivityText:()=>Dw,sessionLogAnsweredQuestionCall:()=>Bw,sessionLogBurstRunning:()=>Uw,sessionLogBurstSteps:()=>jw,sessionLogBurstSummary:()=>Lw,sessionLogBurstWorkLabel:()=>$w,sessionLogCallStatus:()=>Aw,sessionLogFullTextAction:()=>Xw,sessionLogFullTextPlan:()=>Zw,sessionLogHarnessSwitches:()=>Vw,sessionLogOfV1Rows:()=>hw,sessionLogOpenCall:()=>Fw,sessionLogPromptMessage:()=>Rw,sessionLogReferencedTexts:()=>Jw,sessionLogRestoreNotice:()=>zw,sessionLogRetrying:()=>nh,sessionLogShowGroupCall:()=>Nw,sessionLogThreadMetrics:()=>Gw,sessionLogTurnSegments:()=>Mw,sessionLogTurns:()=>si,sessionLogWithFullTexts:()=>ek,sessionModelCandidates:()=>Xk,sessionModelFallback:()=>Jk,sessionModelPin:()=>Zn,sessionParentId:()=>PR,sessionPickStands:()=>Qk,sessionPromptActions:()=>MR,sessionStartKey:()=>FR,setAccountAutomationsPaused:()=>jR,setAccountSecretResourceAccess:()=>pc,setActiveInstanceCookie:()=>E0,setAdminBypass:()=>Ih,setAdminProviderDistribution:()=>$T,setAdminProviderFallback:()=>BT,setAgentScope:()=>Uu,setBillingPlan:()=>ap,setBootstrapAuthToken:()=>cA,setCachedAuthToken:()=>aA,setCaptureEnabled:()=>Vf,setCapturePolicy:()=>Of,setCaptureStorage:()=>Df,setConnectionPolicies:()=>AA,setConnectorAuthorizationStrategy:()=>Mc,setConnectorCredential:()=>zc,setConnectorCredentialMode:()=>Ec,setConnectorName:()=>$c,setConnectorPolicies:()=>Dc,setConnectorSecretBinding:()=>OA,setConnectorSensitive:()=>Oc,setDefaultConnection:()=>wc,setDefaultReasoningEffort:()=>Vv,setEnterpriseDemo:()=>CT,setEnv:()=>Ym,setGatewayBudget:()=>Bp,setGatewayRoutingPolicy:()=>Ip,setGitHubAppFromExisting:()=>cF,setGitHubAppPat:()=>lF,setImpersonationSession:()=>wv,setMaintenanceConfig:()=>zU,setMemberSuperAdmin:()=>YC,setMfaRequired:()=>tT,setModelDefault:()=>Lu,setPersonalProjectSecret:()=>tc,setProjectModelAccess:()=>or,setProjectModelEnablement:()=>NR,setProjectOnboardingComplete:()=>da,setProjectOnboardingProfile:()=>Jv,setProjectPolicies:()=>Zc,setProjectSecretStrategy:()=>Ja,setProjectSessionModel:()=>_u,setProjectSessionScope:()=>hu,setProjectSessionSharing:()=>Bl,setProjectTriggersActivation:()=>vu,setSavedCopyStore:()=>fR,setSessionArchived:()=>Hl,setSessionOversight:()=>rT,setSessionPinned:()=>Wl,setSessionProviderSecretPool:()=>mc,setSessionWatch:()=>Gl,setTelegramAllowedUsers:()=>uC,settleSessionConnection:()=>jF,setupSSH:()=>pU,shareConnection:()=>Ac,shareFolder:()=>rI,shareTurn:()=>RR,shellActivityGroupLabel:()=>sE,shellExitCode:()=>Ny,shouldAttachImpersonation:()=>Ch,shouldHideResponsePart:()=>S$,shouldShowToolPart:()=>mn,shouldSuppressWorkingTurnBusy:()=>p$,showGroupItems:()=>Ty,showTurnBusyIndicator:()=>Iy,signInWithPassword:()=>ro,signInWithProvider:()=>io,signInWithSso:()=>go,signOut:()=>fo,signOutDevice:()=>YT,signUp:()=>no,skillDocumentPath:()=>t0,skillInputDir:()=>X$,sortSessions:()=>HD,splitSessionLogTurnWork:()=>Ow,splitTurnWork:()=>$y,splitUserParts:()=>rD,startApp:()=>Bg,startAppMachine:()=>Vg,startConnectionOAuth2Authorization:()=>PA,startConnectionOAuth2DeviceAuthorization:()=>xA,startConnectorSetupLink:()=>UU,startGitHubAppManifest:()=>aF,startProjectProviderOAuth:()=>ds,startProjectSession:()=>nt,startProjectSessionOrThrow:()=>ju,startSessionWithToken:()=>HU,startTask:()=>NE,stepLabel:()=>hn,stopApp:()=>Kg,stopAppMachine:()=>zg,stopProjectSession:()=>Xn,stopSandbox:()=>X0,storeGitHubUserToken:()=>ka,stripAnsi:()=>cy,stripInstancePrefix:()=>T0,stripTrailingSlashes:()=>le,subAgentCalls:()=>qw,submitAccessRequest:()=>OU,submitConnectorAppForm:()=>BU,submitDemoRequest:()=>JU,submitOAuthConsent:()=>LU,submitReviewItem:()=>Td,submitSecretSetupLink:()=>qU,subscribeToImpersonation:()=>kv,supabaseClient:()=>$v,syncConnectors:()=>Ic,syncSubscription:()=>ZR,systemReload:()=>HM,toDaemonPath:()=>pt,toInstanceAwarePath:()=>M0,toInternalUrl:()=>ES,toSandboxAbsolutePath:()=>on,toToolView:()=>dy,toWorkspaceRelative:()=>uf,toolCallBlock:()=>pr,toolCallError:()=>sb,toolCallMetadata:()=>eb,toolCallRawOutput:()=>rb,toolCallStatus:()=>nb,toolInfo:()=>Do,toolKind:()=>ae,toolViewModel:()=>Px,transferProject:()=>Qv,triggerControlsFrom:()=>DC,triggerSandboxUpdate:()=>hU,triggersRequest:()=>$b,turnEndCause:()=>tw,turnEndNotice:()=>WF,turnHasSteps:()=>XD,turnIsConfirmedActive:()=>m$,turnRendersQueued:()=>f$,turnRetryLabel:()=>uN,unassignTicket:()=>JE,unregisterDeviceToken:()=>gm,unregisterWebPushSubscription:()=>Pm,unshareFolder:()=>sI,unshareTurn:()=>CR,untimedAnchorOf:()=>yy,unwrapError:()=>ye,updateAccountAuditWebhook:()=>mg,updateAccountBranding:()=>Fi,updateAccountMemberRole:()=>Zi,updateAccountName:()=>$i,updateAgentConfig:()=>qR,updateApp:()=>Cg,updateAppAccess:()=>jg,updateAppVolume:()=>tm,updateAuditWebhook:()=>kT,updateChangeRequest:()=>jl,updateChannelBinding:()=>mC,updateConnectionCredential:()=>Sc,updateEmailPolicy:()=>Cp,updateExperimentalFeature:()=>ua,updateFeatureFlag:()=>la,updateGroup:()=>ed,updateKortixPty:()=>ef,updateMilestone:()=>xM,updateNotificationPreferences:()=>_m,updateOAuthClient:()=>bd,updatePassword:()=>lo,updatePatPolicy:()=>hT,updatePolicy:()=>GC,updateProject:()=>Dn,updateProjectAccess:()=>Ma,updateProjectAgent:()=>cM,updateProjectDefaultAgent:()=>Nu,updateProjectGroupGrant:()=>Na,updateProjectSandboxProvider:()=>pa,updateProjectSession:()=>lu,updateProjectTrigger:()=>wu,updateRole:()=>pd,updateRolePermissions:()=>dd,updateRoom:()=>Gd,updateSandboxTemplate:()=>ol,updateSessionPolicy:()=>gT,updateSessionReminder:()=>$s,updateSessionReminders:()=>Ud,updateTask:()=>FE,updateTemplateWarmPool:()=>Yv,updateTicket:()=>VE,updateTicketStatus:()=>zE,updateUserMetadata:()=>po,uploadAccountBrandingAsset:()=>Ni,uploadAppArtifactArchive:()=>Lg,uploadConnectorAttachment:()=>Ss,uploadDriveFile:()=>uI,uploadFile:()=>un,uploadNativeFile:()=>lS,uploadPromptAttachment:()=>qn,uploadSessionAttachment:()=>$m,uploadSlackChannelFile:()=>xp,uploadTimeoutMsForBytes:()=>rn,upsertCredential:()=>CM,upsertProjectGitCredential:()=>ec,upsertProjectSecret:()=>Ya,upsertSsoProvider:()=>oT,validateProjectManifest:()=>sa,validateReferralCode:()=>_C,validateToken:()=>ta,verifyGatewayProvider:()=>fC,verifyKortixToken:()=>Ak,verifyOtp:()=>oo,verifySsoDomain:()=>aT,wakeEscalationAttemptSummary:()=>oN,wakeEscalationNote:()=>rN,wakeProgressFingerprint:()=>ZF,wireIdClock:()=>It,wireIdClockAt:()=>en,wireIdClockDelta:()=>Et,workedForLabel:()=>j$,workingExpiryAtMs:()=>qF,workingTurnDrawsBusyRow:()=>y$,writeActivityGroupLabel:()=>oE,writeFile:()=>Ar,writeProjectFile:()=>fl,wsDomain:()=>Go,wsFavicon:()=>mL,wsRootDomain:()=>gL});var av={backendUrl:"",getToken:async()=>null},gi=null,Zr=null;function cv(e){Zr=e}function lv(){return Zr}function es(e,t){t?.global!==!1&&(gi=e)}function I(){return Zr?.()??gi??av}function ts(){return gi!==null||Zr?.()!==void 0}function uv(e){return new Promise(t=>setTimeout(t,e))}async function ns(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 uv(s)),i=await e(),i)return i;return i}var mi=12e4;function pv(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function hh(e,t,n=mi){let r=e instanceof Request?e.signal:t?.signal;if(pv(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function rs(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var _=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},re=class extends _{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},et=class extends _{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},bt=class extends _{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},dv="ENDPOINT_RETIRED";function N(e,t){let n=t?` ${t}`:"";return new _(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:dv})}var Dt="feature_disabled";function _h(e){if(!(e instanceof _)||e.status!==403||e.code!==Dt)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function fi(e){let t=_h(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function yi(e){let t=_h(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}var Cn="repository_disconnected",gv=new Set(["app_uninstalled","app_suspended","repo_not_accessible"]);function bh(e){return!!e&&typeof e=="object"&&e.code===Cn}function Sh(e){if(e?.status!=="error")return null;let t=e.last_error_code;return t&&gv.has(t)?t:null}function Tn(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new 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 hi(e){return e instanceof et}function Lt(e){if(e instanceof re)return!0;let t=e?.status;return t===401||t===403}function _i(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 ss(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",mv=/^Request exceeded the \d+s server processing deadline$/,xh=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ph||mv.test(n),fv="git_mirror_unavailable",yv=/^git mirror is temporarily unavailable$/,hv=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===fv||yv.test(n),_v="connectors_provider_unavailable",bv=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===_v;async function Sv(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 xh(e,t,n)||hv(e,t,n)||bv(e,t)||e===403&&t?.code===Dt||e===501&&t?.code===bi||e===409&&(t?.code===Si||t?.code===Pi||t?.code===xi||t?.code===Cn)||e===503&&(t?.code===wi||t?.code===ki)}async function wh(e,t,n,r){let{message:s,data:o}=await Sv(e,t),i=new _(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:xh(e.status,o,s)?Ph:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=Tn(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 kh="X-Kortix-Impersonate",Ai="kortix.impersonation",St=null,os=!1,vi=new Set;function Ri(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function vh(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 xv(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 Ah(){for(let e of vi)try{e()}catch{}}function Rh(){return os||(os=!0,St=xv(Ri()?.getItem(Ai)??null)),St&&!vh(St)?(Ci(),null):St}function wv(e){if(os=!0,!e){Ci();return}St=e;try{Ri()?.setItem(Ai,JSON.stringify(e))}catch{}Ah()}function Ci(){os=!0;let e=St!==null;St=null;try{Ri()?.removeItem(Ai)}catch{}e&&Ah()}function kv(e){return vi.add(e),()=>{vi.delete(e)}}var vv=/(^|\/)admin\/(api|analytics)(\/|$)/;function Ch(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!vv.test(t)}function Ti(e){if(e!==void 0&&!Ch(e))return{};let t=Rh();return t?{[kh]:t.grantId}:{}}function Ih(e){}function Eh(){return!1}function Av(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function is(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function In(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function as(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(Av))In(n,s,o);return n}function Ei(e,t,n){let r={...t},s=I().clientVersion?.trim();s&&!is(r,"x-kortix-client-version")&&In(r,"X-Kortix-Client-Version",s);for(let[i,a]of Object.entries(Ti(e)))In(r,i,a);let o=I().credentialHeader?.trim();return o?is(r,o)||In(r,o,n):is(r,"authorization")||In(r,"Authorization",`Bearer ${n}`),r}async function $t(e,t){let n=await cs();if(!n)throw new re;return{headers:new Headers(Ei(e,as(e,{headers:t}),n)),rejected:()=>En(n)}}function Rv(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function Th(e,t,n,r,s){if(t instanceof Request){let l=new Headers(Ei(t.url,as(t,n),r));return e(new Request(t,{headers:l,...s?{signal:s}:{}}))}let o=String(t),i=Ei(o,as(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var Mh=null;async function Mi(e){let t=await ns(()=>I().getToken(),e);return t&&(Mh=t),t}var cs=Mi;function En(e=Mh){e&&I().getToken.invalidate?.(e)}var Ii=new Map;function Cv(e){let t=Ii.get(e);if(t)return t;let n=(async()=>(En(e),cs({attempts:2,baseDelayMs:200})))().finally(()=>Ii.delete(e));return Ii.set(e,n),n}async function Pt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=mi}=n,o=n.fetch??I().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:hh(e,t,s);if(i?.aborted)throw Ae();let a=await(i?Re(cs(),i):cs());if(!a)throw new re;let l=r&&!Rv(t)&&!is(as(e,t),"authorization"),p=l&&e instanceof Request?e.clone():e,d=await Th(o,e,t,a,i);if(d.status!==401||!l)return d;let g=await Cv(a);return!g||g===a?d:Th(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 _(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var Oh=()=>I().backendUrl||"",Tv=new Set([502,503,504]),Iv=e=>Tv.has(e),jh=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Ev=e=>jh(e)||(e??"GET").toUpperCase()==="DELETE",Mv=2,ls=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 Ov(e,i,n,r,s,o,a,l)}finally{i.signal?.removeEventListener("abort",p)}}async function Ov(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 Dv(e,t,l,s,o,i,a);if(p instanceof re)return{error:p,success:!1};if(!p.ok)return await wh(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 Lv(l,e,t.method,n,r,s,a)}finally{us(a)}}function us(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function jv(e,t,n){try{await Re(e.arrayBuffer(),t)}catch(r){if(ls(r))throw r}finally{us(n)}}async function Dv(e,t,n,r,s,o,i){let a=jh(t.method),l=Ev(t.method),p=l?Mv+1:1,d;for(let g=0;g<p;g++){g>0&&await ss(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&&ls(f)&&!t.signal?.aborted&&l&&g<p-1){i.didTimeout=!1;continue}if(ls(f)||g===p-1)throw f;continue}if(!a||!Iv(d.status)||g===p-1)return s||us(i),d;await jv(d,m.signal,i)}return d}function Lv(e,t,n,r,s,o,i){us(i);let a=ls(e);a&&(i.isAborted=!0);let l;if(a){if(!i.didTimeout)return{error:new _("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(Oh(),"")||t;l=new _(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(l=new _(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(Oh(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&I().onError?.(l,s)):(l=new _(String(e)),r&&I().onError?.(l,s));return{error:l,success:!1}}var Ue=()=>I().backendUrl||"",bi="feature_not_supported",Si="model_not_servable",Pi="provision_in_flight",xi="sandbox_state_change_in_progress",wi="analytics_unavailable",ki="accounts_list_unavailable",$v={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new _(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 _(n.message,{name:n.name||"ApiError",stack:n.stack}):new _(String(n));return I().onError?.(r,t),{error:r,success:!1}}}};async function Uv(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 rs();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:Uv};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function Oi(e){return e.replace(/\/v1\/?$/,"")}async function Ut(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=Oi(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 ji(){return u(await c.get("/accounts"))}async function Di(e){return u(await c.post("/accounts",e))}async function Li(e){return u(await c.get(`/accounts/${e}`))}async function $i(e,t){return u(await c.patch(`/accounts/${e}`,{name:t}))}async function Ui(e){return u(await c.get(`/accounts/${e}/branding`))}async function Fi(e,t){return u(await c.put(`/accounts/${e}/branding`,t))}async function Ni(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 Bi(e,t){return u(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function Ki(e){return u(await c.delete(`/accounts/${e}/branding`))}async function qi(e){return u(await c.get(`/accounts/${e}/members`))}async function Gi(e,t){return u(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Wi(e){return u(await c.get(`/accounts/${e}/invites`))}async function Hi(e,t){return u(await c.delete(`/accounts/${e}/invites/${t}`))}async function Vi(e,t){return u(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function zi(){return u(await c.get("/account-invites",{showErrors:!1})).invites}async function Yi(e){return u(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function ps(e){return u(await c.post(`/account-invites/${e}/accept`,{}))}function Dh(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 Ji(e,t){let n=await ps(e);return{accepted:n,landing:Dh(n,t)}}async function Qi(e){return u(await c.post(`/account-invites/${e}/decline`,{}))}async function Xi(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 ea(e){return u(await c.post(`/accounts/${e}/leave`,{}))}async function Fv(e){return Ut(e,"/v1/accounts")}async function ta(){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 Nv=["marketplace","connectors_api_discover","agentmail_email","meta_agent","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","genui","us_region","event_triggers","notification_center","volumes","drives","session_log_restore","connectors_v2","agent_rooms","goals","workspace_volume"];async function xt(){return u(await c.get("/projects"))}async function na(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 ra(e,t,n="write"){return u(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function sa(e,t){return u(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function oa(e){return u(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function Bv(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function Mn(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 On(e,t){return u(await c.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function jn(e,t){return u(await c.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function Kv(e,t){return u(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function ia(e){return u(await c.post("/projects",e))}async function aa(e){return u(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function ca(e,t={}){return u(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var $h="provision_stream_unterminated",Lh=200;function qv(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>jh?`${n.slice(0,jh)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function Kk(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 _(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(`
3
+ `);try{return JSON.parse(n)}catch(r){let s=n.length>Lh?`${n.slice(0,Lh)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function Gv(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 _(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=Bk(g);if(m){if(t(m),m.type==="error")throw new _(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new _("Provision stream ended without a result",{code:Dh});return a}async function qk(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await c.get(`/projects/quota${t}`))}async function Gk(){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 ca(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function la(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function ua(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function Wk(e,t){return u(await c.put(`/projects/${e}/default-reasoning-effort`,{effort:t}))}async function Hk(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function Vk(e,t){throw N("updateTemplateWarmPool")}async function pa(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function zk(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function jn(e){return u(await c.delete(`/projects/${e}`))}async function Yk(e,t){return u(await c.post(`/projects/${e}/transfer`,{account_id:t}))}async function Jk(e,t){return $t(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function Qk(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Mi(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 da(e,t,n){return u(await c.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function ga(e,t,n){return u(await c.post(`/projects/${e}/skills/remove`,t,{showErrors:!1,...n}))}async function Xk(e){return u(await c.get(`/projects/${e}/git/connection`),"Failed to read the Git connection")}async function ma(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function fa(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function ya(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ha(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function _a(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function ba(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 Sa(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 Pa(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function xa(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function wa(e){return u(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function va(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 ka(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function Aa(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 Zk(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Ra(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function Ca(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Ta(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Ia(e){return u(await c.get(`/projects/${e}/access`))}async function Ea(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function Ma(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function eA(e){return"status"in e&&e.status==="invited"}async function Oa(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 ja(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function Da(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function La(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function $a(e){return u(await c.get(`/projects/${e}/group-grants`))}async function Ua(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 Fa(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 Na(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function Ba(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function Ka(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 qa(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function Ga(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Wa(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Ha(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 Va(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function za(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function Ya(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Ja(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Qa(e){return u(await c.get(`/projects/${e}/oauth`)).items??[]}async function ds(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 gs(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Xa(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var tA=2e3,nA=3e3,rA=10*6e4;async function sA(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 ds(t,n,r);if(l())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(tA,p.interval_ms||nA),g=p.expires_at||a()+rA;for(;!l()&&a()<g;){if(await i(d),l())return{status:"cancelled"};let m;try{m=await gs(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 Za(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function Dn(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function ec(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function tc(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var nc=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Ut=(e,t)=>`${nc(e)}/${encodeURIComponent(t)}`,Lh=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function rc(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${nc(e)}${n}`))}async function sc(e,t){return u(await c.post(nc(e),t))}async function oc(e,t,n){return u(await c.put(`${Ut(e,t)}/value`,{value:n}))}async function ic(e,t){return u(await c.post(`${Ut(e,t)}/retry`))}async function ac(e,t){return u(await c.delete(Ut(e,t)))}async function cc(e,t,n,r){return u(await c.put(`${Ut(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function lc(e,t,n,r){return u(await c.delete(`${Ut(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function uc(e,t,n,r){return u(await c.put(`${Ut(e,t)}/access`,{mode:n,user_ids:r}))}async function pc(e,t,n){return u(await c.get(Lh(e,t,n)))}async function dc(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function gc(e,t,n,r){return u(await c.put(Lh(e,t,n),{secret_ids:r}))}async function ms(){return Ei()}async function $h(e){return ns(()=>I().getToken(),e,fs)}function fs(){Tn()}function oA(e){e===null&&Tn()}function iA(e){}async function Ft(){return ms()}async function aA(e){return $h(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 rs();throw r}}function ys(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(`${ys(e,"catalog")}${r}`)).connectors??[]}async function hs(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 mc(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await hs(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 _s(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 cA(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 lA=9e4;async function vt(e,t,n={},r={}){let{connector:s,action:o}=cA(t),i=r.account?.trim(),a=r.approvalContext?.trim(),l=u(await c.post(ys(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??lA,signal:r.signal}));return l.ok&&l.binding!==void 0&&!("output"in l)&&(l.output=l.data),l}async function bs(e,t){let n=await c.get(ys(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function uA(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 pA(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 Ss(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=pA(I().backendUrl),a=ys(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 _(uA(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 dA(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 fc(e){return u(await c.get(`/projects/${e}/connections`))}async function yc(e){return u(await c.get(`/projects/${e}/connections/all`))}async function hc(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function _c(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function bc(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 gA(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function mA(e,t,n){return u(await c.put(Fe(e,t,"application"),n))}async function fA(e,t){return u(await c.get(Fe(e,t,"application")))}async function yA(e,t,n){return u(await c.post(Fe(e,t,"discover"),n))}async function hA(e,t,n={}){return u(await c.post(Fe(e,t,"discover-resource"),n))}async function _A(e,t,n){return u(await c.post(Fe(e,t,"register"),n))}async function bA(e,t,n){return u(await c.post(Fe(e,t,"authorize"),n))}async function SA(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 xA(e,t){return u(await c.get(Fe(e,t,"status")))}async function Sc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Pc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function xc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function wc(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function vc(e,t){return u(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function kc(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Ac(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function Rc(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Cc(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 Tc(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Ic(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Ec(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Mc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function Oc(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function jc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function wA(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function vA(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Dc(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function Lc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Uh(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 $c=Uh;async function kA(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Uc(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function Fc(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function AA(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function Nc(e){return u(await c.get(`/projects/${e}/connector-moves`)).moves}async function Bc(e,t,n={}){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/move`,n.connectionId?{connection_id:n.connectionId}:{}))}async function Kc(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function qc(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 Gc(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 RA(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 CA(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function Ps(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 Wc(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 TA=Ps,IA=xs;async function Hc(){return u(await c.get("/connectors/connect-status"))}async function Vc(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 zc(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function EA(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Fh(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 Yc=Fh;var Ln=class extends _{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds: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}},ws=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)}},vs=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 Nh(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function MA(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function OA(e,t,n){if(!(e instanceof _)||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?Nh(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:MA(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 jA(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 vt(e,`${o}.${i}`,r,s)}catch(l){throw OA(l,o,i)}if(a.status==="pending_approval")throw new ws(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":Nh(l),details:a,data:a,reason:l,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return jA(a)}async function*Jc(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 vs(t,n,i,l);let d=await ks(e,t,n,l,a);yield d,l=o(d,l)}}async function Qc(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function Xc(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Zc(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function el(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 tl(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function nl(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function rl(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function sl(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function ol(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function il(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function al(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 cl(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 ll(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 ul(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 pl(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 DA=10*6e4;async function dl(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:DA},"Failed to download")).blob()}async function gl(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 LA(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()}async function ml(e,t){return u(await c.put(`/projects/${e}/files/content`,t,{showErrors:!1}))}var fl=52428800,$A=104857600,Bh=20;var Rs=e=>`/projects/${encodeURIComponent(e)}/attachments`,Cs={showErrors:!1,deadlineCoversBody:!0},Kh=3e4,UA=12e4,FA=6e4,NA=5*6e4,BA=6e4,KA=6e4;function As(){return new _("Request aborted",{name:"AbortError",code:"ABORTED"})}function Fn(e){if(e?.aborted)throw As()}function qA(e){return!(e instanceof _)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function 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 _&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(qA(o)||i))throw o;r??=Date.now()+(n?NA:FA);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await ss(a,t)}catch{throw Fn(t),o}}}}function GA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function yl(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"&&GA(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 qh(e,t,n,r){return u(await c.post(Rs(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Cs,signal:n,timeout:Kh}),"Failed to start attachment upload")}async function Gh(e,t,n,r){let s=yl({...await Nn(()=>qh(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function Wh(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new _(r,{status:e,details:n,code:String(n?.statusCode??e)})}function WA(e){if(!(e instanceof _))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function HA(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 _("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},BA)},m=()=>{d(As()),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(Wh(i.status,i.responseText))},i.onerror=()=>d(new _("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(As()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function VA(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"?As():new _(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw Wh(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function zA(e,t,n){Fn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?HA(r,e,t,n):VA(e,t,n)}async function YA(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(()=>zA(i,t,r),r.signal)}catch(a){let l=WA(a);if(l!==409){if(o||!(l===400||l===401||l===403))throw a;o=!0,s=await Gh(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return Hh(e,t,s,r)}async function Hh(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${Rs(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,{...Cs,signal:r.signal,timeout:Kh}),"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?yl({...n.resume},t):yl({...await Nn(()=>qh(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()<KA&&(r=await Gh(e,t,r,n)),r=r.upload.kind==="direct"?await YA(e,t,r,n):await Hh(e,t,r,n)),n.onProcessing?.();let s=`${Rs(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Nn(async()=>u(await c.post(`${s}/complete`,{},{...Cs,signal:n.signal,timeout:UA}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof _&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Bt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${Rs(e)}/${encodeURIComponent(t)}`,{...Cs,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function hl(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 _l(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 bl(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Sl(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 Pl(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 xl(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 wl(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 vl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function kl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function Al(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function Rl(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function Cl(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Tl(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Il(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function El(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Ml(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function Ol(e,t,n){return u(await c.patch(`/projects/${e}/change-requests/${t}`,n))}var Kt=new Set,JA=500;function Kn(e){e&&(Kt.add(e),Kt.size>JA&&Kt.delete(Kt.values().next().value))}function jl(e){return!!e&&Kt.has(e)}function QA(e){e&&Kt.delete(e)}var ce="kortix.session/2",_e=1,Vh=["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",Jh=e=>e.schema===ce&&qn(e.v),kt=e=>J(e,z),Dl=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)&&kt(e.variant),XA=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),zh=e=>se(e)&&(e.type==="text"&&z(e.text)||e.type==="attachment"&&z(e.mime)),ZA=e=>se(e)&&Array.isArray(e.content)&&e.content.every(zh)&&J(e.model_content,t=>Array.isArray(t)&&t.every(zh))&&typeof e.is_error=="boolean",Yh={text:e=>z(e.text)&&J(e.bytes,qn)&&kt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>z(e.text),attachment:e=>z(e.mime)&&kt(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,ZA),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 eR(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(Yh,r.type)||!Yh[r.type](r)||!Dl(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function Ll(e){return se(e)&&Jh(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)&&kt(e.native_agent_id)&&kt(e.context_ref)&&Qh(e.model)&&XA(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)&&Dl(e.ext)&&eR(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function $l(e){return se(e)&&Jh(e)&&Te(e.thread_id)&&Be(e.parent_thread_id)&&(e.spawned_by===null||se(e.spawned_by))&&z(e.created_at)}function tR(e){return se(e)&&J(e.schema,t=>t===ce)&&J(e.v,qn)&&kt(e.session_id)&&J(e.title,Be)&&kt(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))&&Dl(e.ext)}function Gt(e){return se(e)&&qn(e.generation)&&typeof e.has_more=="boolean"&&tR(e.session)&&Array.isArray(e.threads)&&e.threads.every($l)&&(e.thread_id===null||Te(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>Ll(t)&&t.thread_id===e.thread_id)}var nR=e=>Gt(e)&&e.messages.length>0;function rR(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 Xh={paintable:nR,fit:rR,capturedAt:()=>0},sR=new WeakMap;function Zh(e,t,n){sR.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 Ts(e){return!!e&&typeof e.then=="function"}function e_(e,t){return Ts(e)?e.then(t):t(e)}function t_(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:s,now:o}=e,i=`${n}index`,a=T=>{try{let b=t.getItem(T);return Ts(b)?b.catch(()=>null):b}catch{return null}},l=async T=>{try{await t.removeItem(T)}catch{}},p=T=>{if(!T)return[];try{let b=JSON.parse(T);return b?.v===1&&Array.isArray(b.entries)?b.entries:[]}catch{return[]}},d=Promise.resolve(),g=T=>{let b=d.then(T,T);return d=b.catch(()=>{}),b},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,b)=>{let S=[...T].sort((y,w)=>y.u-w.u),O=S.reduce((y,w)=>y+w.b,0);for(;S.length>r||O>s;){let y=S.findIndex(x=>x.s!==b);if(y===-1)break;let[w]=S.splice(y,1);O-=w.b,await l(`${n}${w.s}`)}return S},touch:T=>{g(async()=>{let b=await f(),S=b.find(O=>O.s===T);S&&(S.u=o(),await m(b))})},forgetScope:T=>g(async()=>{await l(`${n}${T}`);let b=await f(),S=b.filter(O=>O.s!==T);S.length!==b.length&&await m(S)})}}function s_(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 oR=12,iR=15e5,aR=3e5,cR=336*60*60*1e3,o_="kortix.saved-copy";function lR(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 uR(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var pR={paintable:s_,fit:lR,capturedAt:uR};function dR(e){let t=r_(e,pR),n=r_({...e,namespace:`${e.namespace??o_}.log`},Xh),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 Zh(r,n,t.remove),r}function r_(e,t){let{storage:n,userId:r,maxSessions:s=oR,maxBytes:o=iR,maxEnvelopeBytes:i=aR,maxAgeMs:a=cR,namespace:l=o_,now:p=()=>Date.now()}=e,d=`${l}:${r}:`,g=t_({storage:n,prefix:d,maxSessions:s,maxBytes:o,now:p}),{indexKey:m,safeGet:f,safeRemove:h,enqueue:P,loadIndex:k,saveIndex:T,evict:b,touch:S,forgetScope:O}=g,y=(x,v)=>`${d}${x}/${v}`,w=x=>{try{let v=n.removeItem(x);Ts(v)&&v.catch(()=>{})}catch{}};return{keyFor:y,read(x,v){let C=`${x}/${v}`;return e_(f(y(x,v)),D=>{if(!D)return null;let R;try{R=JSON.parse(D)}catch{return w(y(x,v)),O(C),null}return!R||R.v!==1||R.user!==r||p()-R.at>a||!t.paintable(R.e)?(w(y(x,v)),O(C),null):(S(C),R.e)})},write(x,v,C){let D=`${x}/${v}`;if(!t.paintable(C))return O(D);let R={v:1,user:r,at:p(),e:C},L=t.fit(R,i);if(L===null)return O(D);let pe=t.capturedAt(C);return P(async()=>{let j=await k(),q=j.find(ht=>ht.s===D);if(q&&pe>0&&q.c>pe)return;let W=j.filter(ht=>ht.s!==D),K={s:D,b:L.length,u:p(),c:pe},De=await b([...W,K],D),ui=y(x,v);try{await n.setItem(ui,L)}catch{let ht=De.filter(_t=>_t.s!==D).sort((_t,Xv)=>_t.u-Xv.u)[0];ht&&(await h(`${d}${ht.s}`),De=De.filter(_t=>_t.s!==ht.s));try{await n.setItem(ui,L)}catch{await h(ui),De=De.filter(_t=>_t.s!==D)}}await T(De)})},remove(x,v){return O(`${x}/${v}`)},clear(){return P(async()=>{let x=await k();for(let v of x)await h(`${d}${v.s}`);await h(m)})}}}var i_=null;function gR(e){i_=e}function Ul(){return i_}var mR=new Set;function a_(e){for(let t of mR)try{t(e)}catch{}}var fR=new Set;function c_(e){for(let t of fR)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},yR=40;var hR="session_log_missing";async function _R(e,t,n,r,s){try{let o=await e(t,n,r,s);return Gt(o)?o:null}catch(o){return o?.code===hR?"missing":null}}function l_(e,t,n,r){return _R(e,t,n,{limit:yR},r)}function bR(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 SR=50,u_=200,PR=u_;function p_(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 Fl(e,t){let n=await c.get(`/projects/${e}/sessions${p_(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${p_(t)}`))}async function Nl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Bl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Kl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function ql(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Gl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Wl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function xR(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 wR(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 Hl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function Vl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function zl(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Yl(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 Jl(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 Ql(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 Xl(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 eu(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 vR(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 kR(e){if(e)return e==="interrupt"?"transcript":"composer"}async function zn(e,t,n){let r=n.placement??kR(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 tu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function nu(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function ru(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function su(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function ou(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function iu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function au(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function cu(e,t){let n=u(await c.delete(`/projects/${e}/sessions/${t}`));return Ul()?.remove(e,t),c_(t),n}async function lu(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function uu(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 a_(t),n}async function pu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function AR(e){let t=e.split(`
7
+ `);let m=qv(g);if(m){if(t(m),m.type==="error")throw new _(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new _("Provision stream ended without a result",{code:$h});return a}async function Wv(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await c.get(`/projects/quota${t}`))}async function Hv(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Dn(e,t){return u(await c.patch(`/projects/${e}`,t))}async function la(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function ua(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function pa(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function Vv(e,t){return u(await c.put(`/projects/${e}/default-reasoning-effort`,{effort:t}))}async function zv(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function Yv(e,t){throw N("updateTemplateWarmPool")}async function da(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function Jv(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Ln(e){return u(await c.delete(`/projects/${e}`))}async function Qv(e,t){return u(await c.post(`/projects/${e}/transfer`,{account_id:t}))}async function Xv(e,t){return Ut(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function Zv(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Oi(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 ga(e,t,n){return u(await c.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function ma(e,t,n){return u(await c.post(`/projects/${e}/skills/remove`,t,{showErrors:!1,...n}))}async function eA(e){return u(await c.get(`/projects/${e}/git/connection`),"Failed to read the Git connection")}async function fa(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function ya(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function ha(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function _a(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function ba(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Sa(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 Pa(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 xa(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function wa(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function ka(e){return u(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function va(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 Aa(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function Ra(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 tA(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Ca(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function Ta(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Ia(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Ea(e){return u(await c.get(`/projects/${e}/access`))}async function Ma(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function Oa(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function nA(e){return"status"in e&&e.status==="invited"}async function ja(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 Da(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function La(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function $a(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Ua(e){return u(await c.get(`/projects/${e}/group-grants`))}async function Fa(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 Na(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 Ba(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function Ka(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function qa(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 Ga(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function Wa(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Ha(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Va(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 za(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Ya(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function Ja(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Qa(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Xa(e){return u(await c.get(`/projects/${e}/oauth`)).items??[]}async function ds(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 gs(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 rA=2e3,sA=3e3,oA=10*6e4;async function iA(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 ds(t,n,r);if(l())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(rA,p.interval_ms||sA),g=p.expires_at||a()+oA;for(;!l()&&a()<g;){if(await i(d),l())return{status:"cancelled"};let m;try{m=await gs(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 ec(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function $n(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function tc(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function nc(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var rc=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Ft=(e,t)=>`${rc(e)}/${encodeURIComponent(t)}`,Uh=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function sc(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${rc(e)}${n}`))}async function oc(e,t){return u(await c.post(rc(e),t))}async function ic(e,t,n){return u(await c.put(`${Ft(e,t)}/value`,{value:n}))}async function ac(e,t){return u(await c.post(`${Ft(e,t)}/retry`))}async function cc(e,t){return u(await c.delete(Ft(e,t)))}async function lc(e,t,n,r){return u(await c.put(`${Ft(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function uc(e,t,n,r){return u(await c.delete(`${Ft(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function pc(e,t,n,r){return u(await c.put(`${Ft(e,t)}/access`,{mode:n,user_ids:r}))}async function dc(e,t,n){return u(await c.get(Uh(e,t,n)))}async function gc(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function mc(e,t,n,r){return u(await c.put(Uh(e,t,n),{secret_ids:r}))}async function ms(){return Mi()}async function Fh(e){return ns(()=>I().getToken(),e,fs)}function fs(){En()}function aA(e){e===null&&En()}function cA(e){}async function Nt(){return ms()}async function lA(e){return Fh(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 rs();throw r}}function ys(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Bt(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(`${ys(e,"catalog")}${r}`)).connectors??[]}async function hs(e){let t=[];for(let n of await Bt(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 fc(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await hs(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 _s(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 Bt(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 uA(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 pA=9e4;async function kt(e,t,n={},r={}){let{connector:s,action:o}=uA(t),i=r.account?.trim(),a=r.approvalContext?.trim(),l=u(await c.post(ys(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??pA,signal:r.signal}));return l.ok&&l.binding!==void 0&&!("output"in l)&&(l.output=l.data),l}async function bs(e,t){let n=await c.get(ys(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function dA(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 gA(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 Ss(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=gA(I().backendUrl),a=ys(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 _(dA(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 mA(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 yc(e){return u(await c.get(`/projects/${e}/connections`))}async function hc(e){return u(await c.get(`/projects/${e}/connections/all`))}async function _c(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function bc(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function Sc(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 fA(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function yA(e,t,n){return u(await c.put(Fe(e,t,"application"),n))}async function hA(e,t){return u(await c.get(Fe(e,t,"application")))}async function _A(e,t,n){return u(await c.post(Fe(e,t,"discover"),n))}async function bA(e,t,n={}){return u(await c.post(Fe(e,t,"discover-resource"),n))}async function SA(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 xA(e,t,n){return u(await c.post(Fe(e,t,"device"),n))}async function wA(e,t,n){return u(await c.post(Fe(e,t,`device/${encodeURIComponent(n)}`),{}))}async function kA(e,t){return u(await c.get(Fe(e,t,"status")))}async function Pc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function xc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function wc(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function kc(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function vc(e,t){return u(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function Ac(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Rc(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function Cc(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Tc(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 Ic(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Ec(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Mc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Oc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function jc(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function Dc(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function vA(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function AA(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Lc(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function $c(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Nh(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 Uc=Nh;async function RA(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Fc(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function Nc(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function CA(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function Bc(e){return u(await c.get(`/projects/${e}/connector-moves`)).moves}async function Kc(e,t,n={}){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/move`,n.connectionId?{connection_id:n.connectionId}:{}))}async function qc(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Gc(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 Wc(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 TA(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 IA(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function Ps(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 Hc(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 EA=Ps,MA=xs;async function Vc(){return u(await c.get("/connectors/connect-status"))}async function zc(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 Yc(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function OA(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Bh(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 Jc=Bh;var Un=class extends _{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds: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}},ws=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)}},ks=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 Kh(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function jA(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function DA(e,t,n){if(!(e instanceof _)||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 Un(Ce(r.message)??Ce(r.hint)??s,{status:e.status,code:i===null?Kh(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:jA(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 LA(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 vs(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 DA(l,o,i)}if(a.status==="pending_approval")throw new ws(o,i,a);if(!a.ok||a.upstream_error){let l=a.upstream_error??a.reason??"connector_error";throw new Un(l,{status:200,code:a.upstream_error?"upstream_error":Kh(l),details:a,data:a,reason:l,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return LA(a)}async function*Qc(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 ks(t,n,i,l);let d=await vs(e,t,n,l,a);yield d,l=o(d,l)}}async function Xc(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 el(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function tl(e){return u(await c.get(`/projects/${e}/snapshots`))}async function Fn(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function nl(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function rl(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function sl(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function ol(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function il(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function al(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function cl(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Nn(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 $t(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function ll(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 ul(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 pl(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 dl(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 $A=10*6e4;async function gl(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:$A},"Failed to download")).blob()}async function ml(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Nn(`${I().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function UA(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()}async function fl(e,t){return u(await c.put(`/projects/${e}/files/content`,t,{showErrors:!1}))}var yl=52428800,FA=104857600,qh=20;var Rs=e=>`/projects/${encodeURIComponent(e)}/attachments`,Cs={showErrors:!1,deadlineCoversBody:!0},Gh=3e4,NA=12e4,BA=6e4,KA=5*6e4,qA=6e4,GA=6e4;function As(){return new _("Request aborted",{name:"AbortError",code:"ABORTED"})}function Bn(e){if(e?.aborted)throw As()}function WA(e){return!(e instanceof _)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function Kn(e,t,n=!1){let r;for(let s=0;;s++){Bn(t);try{return await e()}catch(o){let i=n&&o instanceof _&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(WA(o)||i))throw o;r??=Date.now()+(n?KA:BA);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await ss(a,t)}catch{throw Bn(t),o}}}}function HA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function hl(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"&&HA(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 Wh(e,t,n,r){return u(await c.post(Rs(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Cs,signal:n,timeout:Gh}),"Failed to start attachment upload")}async function Hh(e,t,n,r){let s=hl({...await Kn(()=>Wh(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function Vh(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new _(r,{status:e,details:n,code:String(n?.statusCode??e)})}function VA(e){if(!(e instanceof _))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function zA(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 _("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},qA)},m=()=>{d(As()),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(Vh(i.status,i.responseText))},i.onerror=()=>d(new _("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(As()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function YA(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"?As():new _(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw Vh(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function JA(e,t,n){Bn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?zA(r,e,t,n):YA(e,t,n)}async function QA(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 Kn(()=>JA(i,t,r),r.signal)}catch(a){let l=VA(a);if(l!==409){if(o||!(l===400||l===401||l===403))throw a;o=!0,s=await Hh(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return zh(e,t,s,r)}async function zh(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${Rs(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){Bn(r.signal);let a=i.received_bytes,l=Math.min(a+s,t.size),p=t.slice(a,l),d=await Kn(async()=>u(await c.putRaw(`${o}/chunks/${a/s}`,p,{...Cs,signal:r.signal,timeout:Gh}),"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 qn(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");Bn(n.signal);let r=n.resume?hl({...n.resume},t):hl({...await Kn(()=>Wh(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()<GA&&(r=await Hh(e,t,r,n)),r=r.upload.kind==="direct"?await QA(e,t,r,n):await zh(e,t,r,n)),n.onProcessing?.();let s=`${Rs(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await Kn(async()=>u(await c.post(`${s}/complete`,{},{...Cs,signal:n.signal,timeout:NA}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof _&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Kt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${Rs(e)}/${encodeURIComponent(t)}`,{...Cs,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function _l(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 bl(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 Sl(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Pl(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 xl(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 wl(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 kl(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 vl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function Al(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function Rl(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function Cl(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function Tl(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Il(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function El(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Ml(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Ol(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function jl(e,t,n){return u(await c.patch(`/projects/${e}/change-requests/${t}`,n))}var qt=new Set,XA=500;function Gn(e){e&&(qt.add(e),qt.size>XA&&qt.delete(qt.values().next().value))}function Dl(e){return!!e&&qt.has(e)}function ZA(e){e&&qt.delete(e)}var ce="kortix.session/2",_e=1,Yh=["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),Y=e=>typeof e=="string",Te=e=>Y(e)&&e.length>0,Be=e=>e===null||Y(e),Q=(e,t)=>e===void 0||t(e),Ne=(...e)=>t=>e.includes(t),Wn=e=>Number.isInteger(e)&&e>=0,Gt=e=>typeof e=="number",Xh=e=>e.schema===ce&&Wn(e.v),vt=e=>Q(e,Y),Ll=e=>e===void 0||se(e)&&Object.values(e).every(t=>se(t)&&Y(t.version)),Zh=e=>e===null||se(e)&&Y(e.provider)&&Y(e.model)&&vt(e.variant),eR=e=>e===null||se(e)&&Gt(e.input)&&Gt(e.output)&&Gt(e.cache_read)&&Gt(e.cache_write)&&Q(e.reasoning,Gt)&&Q(e.cost,Gt),Jh=e=>se(e)&&(e.type==="text"&&Y(e.text)||e.type==="attachment"&&Y(e.mime)),tR=e=>se(e)&&Array.isArray(e.content)&&e.content.every(Jh)&&Q(e.model_content,t=>Array.isArray(t)&&t.every(Jh))&&typeof e.is_error=="boolean",Qh={text:e=>Y(e.text)&&Q(e.bytes,Wn)&&vt(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>Y(e.text),attachment:e=>Y(e.mime)&&vt(e.ref)&&Q(e.bytes,Wn)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>Y(e.call_id)&&Y(e.name)&&Te(e.kind)&&Ne("pending","running","complete","error")(e.status)&&Q(e.result,tR),compaction:e=>Be(e.summary)&&Be(e.first_kept_message_id),subtask:e=>Y(e.thread_id)&&Y(e.agent)&&Y(e.description),step:e=>Ne("start","finish")(e.phase),harness:e=>Te(e.harness)&&Te(e.kind)&&typeof e.model_visible=="boolean"};function nR(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)||!Ll(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function $l(e){return se(e)&&Xh(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"&&Q(e.hidden_reason,Ne("failed_attempt","aborted","retracted","reverted","superseded"))&&Q(e.origin,Ne("prompt","steer","command","automation","subagent","notification"))&&Q(e.agent,Be)&&Q(e.reply_to,Be)&&Q(e.parent_message_id,Be)&&vt(e.native_agent_id)&&vt(e.context_ref)&&Zh(e.model)&&eR(e.usage)&&Ne("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||se(e.error)&&Te(e.error.code)&&Y(e.error.message))&&Y(e.created_at)&&Be(e.completed_at)&&se(e.producer)&&Te(e.producer.harness)&&Y(e.producer.harness_version)&&Y(e.producer.adapter_version)&&Ll(e.ext)&&nR(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function Ul(e){return se(e)&&Xh(e)&&Te(e.thread_id)&&Be(e.parent_thread_id)&&(e.spawned_by===null||se(e.spawned_by))&&Y(e.created_at)}function rR(e){return se(e)&&Q(e.schema,t=>t===ce)&&Q(e.v,Wn)&&vt(e.session_id)&&Q(e.title,Be)&&vt(e.created_at)&&Q(e.restore_grade,Ne("native","converted","partial"))&&Q(e.todos,Array.isArray)&&Q(e.pending,t=>se(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&Q(e.selection,t=>se(t)&&Q(t.agent,Be)&&Zh(t.model??null))&&Q(e.harness,t=>se(t)&&Y(t.current)&&Array.isArray(t.history))&&Ll(e.ext)}function Wt(e){return se(e)&&Wn(e.generation)&&typeof e.has_more=="boolean"&&rR(e.session)&&Array.isArray(e.threads)&&e.threads.every(Ul)&&(e.thread_id===null||Te(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>$l(t)&&t.thread_id===e.thread_id)}var sR=e=>Wt(e)&&e.messages.length>0;function oR(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 e_={paintable:sR,fit:oR,capturedAt:()=>0},iR=new WeakMap;function t_(e,t,n){iR.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 Ts(e){return!!e&&typeof e.then=="function"}function n_(e,t){return Ts(e)?e.then(t):t(e)}function r_(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:s,now:o}=e,i=`${n}index`,a=T=>{try{let b=t.getItem(T);return Ts(b)?b.catch(()=>null):b}catch{return null}},l=async T=>{try{await t.removeItem(T)}catch{}},p=T=>{if(!T)return[];try{let b=JSON.parse(T);return b?.v===1&&Array.isArray(b.entries)?b.entries:[]}catch{return[]}},d=Promise.resolve(),g=T=>{let b=d.then(T,T);return d=b.catch(()=>{}),b},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,b)=>{let S=[...T].sort((y,w)=>y.u-w.u),O=S.reduce((y,w)=>y+w.b,0);for(;S.length>r||O>s;){let y=S.findIndex(x=>x.s!==b);if(y===-1)break;let[w]=S.splice(y,1);O-=w.b,await l(`${n}${w.s}`)}return S},touch:T=>{g(async()=>{let b=await f(),S=b.find(O=>O.s===T);S&&(S.u=o(),await m(b))})},forgetScope:T=>g(async()=>{await l(`${n}${T}`);let b=await f(),S=b.filter(O=>O.s!==T);S.length!==b.length&&await m(S)})}}function i_(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 aR=12,cR=15e5,lR=3e5,uR=336*60*60*1e3,a_="kortix.saved-copy";function pR(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 dR(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var gR={paintable:i_,fit:pR,capturedAt:dR};function mR(e){let t=o_(e,gR),n=o_({...e,namespace:`${e.namespace??a_}.log`},e_),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 t_(r,n,t.remove),r}function o_(e,t){let{storage:n,userId:r,maxSessions:s=aR,maxBytes:o=cR,maxEnvelopeBytes:i=lR,maxAgeMs:a=uR,namespace:l=a_,now:p=()=>Date.now()}=e,d=`${l}:${r}:`,g=r_({storage:n,prefix:d,maxSessions:s,maxBytes:o,now:p}),{indexKey:m,safeGet:f,safeRemove:h,enqueue:P,loadIndex:v,saveIndex:T,evict:b,touch:S,forgetScope:O}=g,y=(x,k)=>`${d}${x}/${k}`,w=x=>{try{let k=n.removeItem(x);Ts(k)&&k.catch(()=>{})}catch{}};return{keyFor:y,read(x,k){let C=`${x}/${k}`;return n_(f(y(x,k)),D=>{if(!D)return null;let R;try{R=JSON.parse(D)}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):(S(C),R.e)})},write(x,k,C){let D=`${x}/${k}`;if(!t.paintable(C))return O(D);let R={v:1,user:r,at:p(),e:C},L=t.fit(R,i);if(L===null)return O(D);let pe=t.capturedAt(C);return P(async()=>{let j=await v(),q=j.find(ht=>ht.s===D);if(q&&pe>0&&q.c>pe)return;let W=j.filter(ht=>ht.s!==D),K={s:D,b:L.length,u:p(),c:pe},De=await b([...W,K],D),pi=y(x,k);try{await n.setItem(pi,L)}catch{let ht=De.filter(_t=>_t.s!==D).sort((_t,ev)=>_t.u-ev.u)[0];ht&&(await h(`${d}${ht.s}`),De=De.filter(_t=>_t.s!==ht.s));try{await n.setItem(pi,L)}catch{await h(pi),De=De.filter(_t=>_t.s!==D)}}await T(De)})},remove(x,k){return O(`${x}/${k}`)},clear(){return P(async()=>{let x=await v();for(let k of x)await h(`${d}${k.s}`);await h(m)})}}}var c_=null;function fR(e){c_=e}function Fl(){return c_}var yR=new Set;function l_(e){for(let t of yR)try{t(e)}catch{}}var hR=new Set;function u_(e){for(let t of hR)try{t(e)}catch{}}var Hn=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},_R=40;var bR="session_log_missing";async function SR(e,t,n,r,s){try{let o=await e(t,n,r,s);return Wt(o)?o:null}catch(o){return o?.code===bR?"missing":null}}function p_(e,t,n,r){return SR(e,t,n,{limit:_R},r)}function PR(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 xR=50,d_=200,wR=d_;function g_(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return e?.view&&t.set(e.view,"only"),t.size>0?`?${t}`:""}async function Nl(e,t){let n=await c.get(`/projects/${e}/sessions${g_(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${g_(t)}`))}async function Bl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Kl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function ql(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Gl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Wl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Hl(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function kR(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 vR(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 Vl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function zl(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Yl(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Jl(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}function Ql(e,t,n){return`/projects/${e}/sessions/${t}/turns/${encodeURIComponent(n)}/share`}async function AR(e,t,n){return u(await c.get(Ql(e,t,n),{showErrors:!1}))}async function RR(e,t,n,r){return u(await c.put(Ql(e,t,n),{include_prompt:r?.include_prompt===!0},{showErrors:!1}))}async function CR(e,t,n){return u(await c.delete(Ql(e,t,n),{showErrors:!1}))}async function Rt(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return!t?.initial_prompt&&!t?.fork_from_session_id&&Gn(n?.session_id),n}async function Xl(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||Gn(r.session.session_id),r}async function Zl(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Gn(n.session_id),n}async function Vn(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function eu(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 tu(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 zn(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 nu(e,t,n={},r){let s;try{s=await Hn(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!Wt(s))throw new Error("The response is not a session log page");return s}async function Yn(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function TR(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 IR(e){if(e)return e==="interrupt"?"transcript":"composer"}async function Jn(e,t,n){let r=n.placement??IR(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 ru(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function su(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function ou(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function iu(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function au(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function cu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function lu(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function uu(e,t){let n=u(await c.delete(`/projects/${e}/sessions/${t}`));return Fl()?.remove(e,t),u_(t),n}async function pu(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function du(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Qn(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Xn(e,t){let n=u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}));return l_(t),n}async function gu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function ER(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 du(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function gu(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 _(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(`
9
+ `))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function mu(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function fu(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 _(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=AR(f);if(h){if(r(h),h.type==="error")throw new _(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function mu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function fu(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function yu(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 hu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function _u(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function RR(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 bu(e){return u(await c.get(`/projects/${e}/triggers`))}async function Su(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function Pu(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function xu(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function CR(e){return u(await c.get(`/accounts/${e}/automations`))}async function TR(e,t){return u(await c.patch(`/accounts/${e}/automations`,{paused:t},{showErrors:!1}))}async function wu(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function d_(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 vu(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 ku(e,t,n){return u(await c.get(`/projects/${e}/triggers/${t}/runs${d_(n)}`))}async function Au(e,t){return u(await c.get(`/projects/${e}/trigger-runs${d_(t)}`))}async function Ru(e,t,n,r){return u(await c.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function Cu(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 Tu(e){return u(await c.get(`/projects/${e}/triggers/event-apps`))}var tt=new Map;function Iu(e,t){return`${e}::${t}`}function g_(e,t){tt.delete(e),tt.set(e,t)}function m_(e,t){let n=Iu(e,t),r=tt.get(n);return r&&g_(n,r),r}function Is(e,t,n){let r=Iu(e,t);if(!tt.has(r)&&tt.size>=512){let s=tt.keys().next().value;s!==void 0&&tt.delete(s)}g_(r,n)}function f_(e,t){tt.delete(Iu(e,t))}function IR(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Xn(){return IR(I().backendUrl||"http://localhost:8008/v1")}function y_(){let e=I().sandboxId;return e?`${Xn()}/p/${e}/8000`:""}function ER(e,t=8e3){return`${Xn()}/p/${e}/${t}`}function Ie(e,t=8e3){return ER(e,t)}function Eu(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var Es=class extends Error{status;code;terminal;constructor(t,n){super(t),this.name="SessionStartError",this.status=n.status,this.code=n.code,this.terminal=n.terminal}};function MR(e){return e instanceof Error&&e.name==="SessionStartError"}function OR(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Es(s,{status:n,code:r,terminal:!0}):null}function h_(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 h_(e,t,n);if(!r.success||!r.data){let s=OR(r.error);if(s&&!(s.status===404&&jl(t)))throw s;return null}return __(e,t,r.data)}async function Mu(e,t,n){let r=await h_(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return __(e,t,r.data)}function __(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Is(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Ie(r),sandboxId:r}),n}function jR(e,t){return["session-start",e,t]}async function Ou(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function ju(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function Du(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 DR(e,t){return u(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function b_(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function LR(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Ms(e){let t=e.connectors_required?b_(e.connectors_required):void 0,n=e.connectors_personal?b_(e.connectors_personal):void 0;if(t&&n&&!LR(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 Lu(e,t,n){let r=Ms(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function $R(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?$u(n.block):null}}async function UR(e,t,n){let r=$u(n,!0),s=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?$u(s.block):null}}function $u(e,t=!1){let n=Ms(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 FR(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Uu(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}var Os="Use setBillingPlan().",S_="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Fu(){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 NR(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function BR(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??Fu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:NR(r),label:s,sublabel:null,monthlyUsd:null}}function P_(e){return!!e&&e.can_manage_billing!==!1}function KR(e){return e?.subscription?.can_purchase_credits===!0&&P_(e)}async function x_(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?Fu():t.data}function w_(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 Nu(e){return x_(`/billing/account-state${w_(e)}`)}async function Bu(e){return x_(`/billing/account-state/minimal${w_(e)}`)}async function Ku(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await c.get(`/billing/transactions${n?`?${n}`:""}`))}async function qu(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 Gu(){return u(await c.get("/billing/credit-breakdown"))}async function Wu(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function Hu(){return u(await c.get("/billing/tier-configurations"))}async function qR(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return $t(e,`/v1/billing/account-state${t}`)}async function Vu(e){throw N("createCheckoutSession",Os)}async function zu(e,t){throw N("confirmCheckoutSession",Os)}async function Yu(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Ju(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Qu(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Xu(e,t,n){throw N("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function Zu(e){throw N("cancelScheduledChange",S_)}async function ep(e,t){throw N("getProrationPreview",S_)}async function tp(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 np(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 GR(e){return u(await c.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function rp(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 WR(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 sp(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 op(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 ip(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 ap(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 HR(e){throw N("createPerSeatCheckout",Os)}async function VR(e){throw N("claimPerSeatBilling",Os)}async function zR(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function cp(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 up(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function js(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 pp(e={}){let t=new URLSearchParams;return up(t,e),e.ownerId&&t.set("owner_id",e.ownerId),js(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 up(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Ds(n)}`))}async function YR(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),js(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 JR(e={}){let t=new URLSearchParams;return up(t,e),e.sessionId&&t.set("session_id",e.sessionId),js(t,e),u(await c.get(`/usage/cost-summary${Ds(t)}`))}function lp(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)}js(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 QR(e,t={}){let n=lp(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 v_(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function XR(e){return v_("slack",e)}function ZR(e){return v_("teams",e)}async function k_(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function eC(e){return k_("slack",e)}function tC(e){return k_("teams",e)}async function dp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function gp(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var nC={oauth_available:!1,install_url:null};async function mp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?nC:t.data}async function A_(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 fp(e,t){return A_("slack",e,t)}function yp(e,t){return A_("teams",e,t)}async function hp(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function _p(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 rC(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/telegram/installation`,{showErrors:!1});return t.success?t.data??null:null}async function sC(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/telegram/connect`,t,{showErrors:!1}),"Failed to connect Telegram")}async function oC(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 iC(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 bp(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 Sp(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 Pp(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 aC={provider:"agentmail",managed_available:!1};async function xp(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?Pp(r.data):null}async function wp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?aC:t.data}async function vp(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return Pp(n)}async function kp(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 Ap(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 Pp(r)}async function cC(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function lC(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 Rp(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Cp(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Tp(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Ip(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Ep(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 Mp(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Op(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function jp(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Dp(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Lp(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function $p(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Up(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Fp(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Np(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Bp(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Kp(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function qp(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Gp(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 uC(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function pC(){throw N("getReferralCode")}async function dC(){throw N("refreshReferralCode")}async function gC(e){throw N("validateReferralCode")}async function mC(){throw N("getReferralStats")}async function fC(e={}){throw N("listReferrals")}async function yC(e){throw N("sendReferralEmails")}var Wp="call:";function Vp(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Wp)&&e.length>Wp.length?{type:"connector_call",executionId:e.slice(Wp.length)}:{type:"review_item",reviewItemId:e}}function C_(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function hC(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[C_(n.status)]+=1;return t}function _C(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function Hp(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function zp(e){let t=e.indexOf(".");return t<=0?Hp(e):`(${Hp(e.slice(0,t))}) ${Hp(e.slice(t+1))}`}function bC(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,R_=e=>typeof e=="number"?e:0,SC=e=>e.split(`
14
- `).map(t=>t.trim()).filter(Boolean);function PC(e,t){let n=Wt(e.advanced),r=U(e.description),s=Ee(e.whatChanged)??(r?SC(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:R_(n.additions),deletions:R_(n.deletions),files:Ee(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function xC(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}=bC(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?zp(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 wC(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 vC(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:Ee(e.options)??[]}}function kC(e,t){return{note:U(e.note)??t.summary??"",children:Ee(e.children)??[]}}function AC(e){let t=Wt(e.detail);switch(e.kind){case"change":return PC(t,e);case"approval":return xC(t,e);case"output":return wC(t,e);case"decision":return vC(t,e);case"batch":return kC(t,e)}}function RC(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 CC(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"?RC(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?zp(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:AC(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"},TC=[Q.PROJECT_WRITE,Q.PROJECT_TRIGGER_CREATE,Q.PROJECT_TRIGGER_FIRE,Q.PROJECT_TRIGGER_UPDATE,Q.PROJECT_TRIGGER_DELETE];function IC(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 EC=[Q.PROJECT_WRITE,Q.PROJECT_GITOPS_PUSH,Q.PROJECT_GITOPS_MERGE,Q.PROJECT_REVIEW_ACT];function T_(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 MC(e,t,n){let r=Vp(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 T_(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 Yp(e){return A(await F(`/accounts/${e}/iam/groups`)).groups}async function Jp(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}`))}async function Qp(e,t){return A(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Xp(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 ed(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/members`)).members}async function td(e,t,n){return A(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function OC(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function nd(e,t,n){return A(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function jC(e,t){return A(await F(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function DC(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 LC(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 $C(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 UC(e,t){return A(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function FC(e,t,n){return A(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function NC(e,t){return A(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function BC(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function KC(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function rd(e){return A(await F(`/accounts/${e}/iam/roles`)).roles}async function sd(e){return A(await F(`/accounts/${e}/iam/agent-identities`)).agents}async function od(e){return A(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function id(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/permissions`))}async function qC(e){return A(await F(`/accounts/${e}/iam/actions`)).actions}async function ad(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/usage`))}async function cd(e,t){return A(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function ld(e,t,n){return A(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function ud(e,t,n){return A(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function pd(e,t){return A(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function GC(e,t,n){return A(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function WC(e){return A(await F(`/accounts/${e}/iam/scim/tokens`)).tokens}async function HC(e,t){return A(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function VC(e,t){return A(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function zC(e){return A(await F(`/accounts/${e}/iam/mfa-required`))}async function YC(e){return A(await F(`/accounts/${e}/iam/mfa-required/preview`))}async function JC(e,t){return A(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function QC(e){return A(await F(`/accounts/${e}/iam/session-oversight`))}async function XC(e,t){return A(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function ZC(e){return A(await F(`/accounts/${e}/iam/sso/provider`)).provider}async function eT(e,t){return A(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function tT(e,t){return A(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function nT(e){return A(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function rT(e){return A(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function sT(e){return A(await F(`/accounts/${e}/iam/sso/mappings`)).mappings}async function oT(e,t){return A(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function iT(e,t){return A(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function aT(e){return A(await F(`/accounts/${e}/iam/session-policy`))}async function cT(e,t){return A(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function lT(e){return A(await F(`/accounts/${e}/iam/sessions`)).sessions}async function uT(e,t){return A(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function pT(e){return A(await F(`/accounts/${e}/iam/pat-policy`))}async function dT(e,t){return A(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function gT(e){return A(await F(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function mT(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function fT(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function yT(e,t){return A(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function hT(e){return A(await F(`/accounts/${e}/audit/webhooks`)).webhooks}async function _T(e,t){return A(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function bT(e,t,n){return A(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function ST(e,t){return A(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function PT(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 dd(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 gd(e,t,n){return n.length===0?[]:A(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function xT(e){return A(await F(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function wT(e,t){return A(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function md(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function fd(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function yd(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function hd(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function _d(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function bd(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function vT(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 Sd(e,t){return u(await F(`/accounts/${e}/iam/assignments${vT(t)}`)).assignments}async function Pd(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 xd(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function wd(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await F(`/accounts/${e}/iam/permissions${n}`)).permissions}async function kT(){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 AT(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function RT(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function CT(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function TT(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function IT(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function ET(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function MT(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function OT(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function jT(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function DT(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function LT(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var I_="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function $T(e){throw N("getGoogleAuthUrl",I_)}async function UT(e,t){throw N("convertPresentationToGoogleSlides",I_)}async function vd(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 kd(e){return u(await c.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function Ad(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function Rd(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function Cd(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function Td(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}async function Id(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Ed(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 Md(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 Ls=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function E_(e,t=""){return`${Xn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function M_(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 Ls(s,t.status)}return r}async function FT(e){return M_(E_(e))}async function NT(e){return M_(E_(e,"/messages"))}async function Od(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function jd(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function $s(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Us(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}async function Dd(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders/${n}/run`,{}))}var BT=4;async function O_(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(BT,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 Ld(e,t,n){return O_(t,r=>$s(e,r.sessionId,r.reminderId,n))}function $d(e,t){return O_(t,n=>Us(e,n.sessionId,n.reminderId))}async function er(e){return u(await c.get(`/projects/${e}/reminders`))}var xe=e=>`/projects/${e}/rooms`;function Ud(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 Fd(e,t={}){return u(await c.get(`${xe(e)}${Ud({name:t.name,archived:t.archived,mine:t.mine})}`))}async function Nd(e,t){return u(await c.post(xe(e),t))}async function Bd(e,t){return u(await c.get(`${xe(e)}/${t}`))}async function Kd(e,t,n){return u(await c.patch(`${xe(e)}/${t}`,n))}async function qd(e,t,n={}){return u(await c.get(`${xe(e)}/${t}/messages${Ud({after:n.after,before:n.before,limit:n.limit,top:n.top,thread:n.thread})}`))}async function Gd(e,t,n){return u(await c.post(`${xe(e)}/${t}/messages`,n))}async function Wd(e,t,n){return u(await c.post(`${xe(e)}/${t}/read`,n===void 0?{}:{seq:n}))}async function Hd(e,t,n,r={}){return u(await c.put(`${xe(e)}/${t}/members/sessions/${n}`,r))}async function Vd(e,t,n){return u(await c.delete(`${xe(e)}/${t}/members/sessions/${n}`))}async function zd(e,t,n,r={}){return u(await c.put(`${xe(e)}/${t}/members/people/${n}`,r))}async function Yd(e,t,n){return u(await c.delete(`${xe(e)}/${t}/members/people/${n}`))}async function Jd(e,t){return u(await c.get(`${xe(e)}/people${Ud({q:t})}`))}async function Qd(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 KT(e){return u(await c.post("/cli/device/decide",{user_code:e,approve:!0}))}async function Xd(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 eg(){return u(await c.get("/oauth/grants")).grants}async function tg(e){return u(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function qT(){return u(await c.get("/accounts/me/devices")).devices}async function GT(e){return u(await c.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function ng(e){return u(await c.get(`/projects/${e}/cli-token`))}async function rg(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function sg(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 og(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 ig(e,t){let n=Ht(og(t)).toString();return u(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function ag(e,t={}){let n=new URLSearchParams,r={since:t.since,until:t.until,project_id:t.projectId,actor:t.actor,client:t.client,actor_type:t.actorType,credential_kind:t.credentialKind};for(let[o,i]of Object.entries(r))i&&n.set(o,i);let s=n.toString();return u(await c.get(`/accounts/${e}/audit/activity${s?`?${s}`:""}`))}async function cg(e,t){let n=Ht(og({...t,projectId:void 0})).toString();return u(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function lg(e,t){let n=Ht(og(t)).toString();return u(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function ug(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function pg(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function dg(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function gg(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function mg(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 fg(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 WT(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function yg(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 hg(){return u(await c.get("/marketplace/marketplaces"))}async function _g(){return u(await c.get("/marketplace/marketplaces/featured"))}async function bg(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Sg(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Pg(){return u(await c.get("/marketplace/sources"))}async function xg(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function wg(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function HT(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function VT(e){throw N("getTemplate")}async function zT(e,t){throw N("installTemplate")}async function vg(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function kg(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Fs(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Ag(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Rg(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Cg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function Tg(e,t){let n=await Fs(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 Ig(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Eg(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 Mg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Og(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Ns(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Bs(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function YT(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function JT(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 jg(e,t,n={}){let r=await YT(t),s=n.mediaType??"application/gzip",o=await Ns(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),Bs(e,o.artifact.artifact_id,{sha256:await JT(r),size_bytes:r.byteLength})}async function Dg(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Lg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function $g(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Ug(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 Fg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Ng(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Bg(e,t,n){return u(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Kg(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 qg(e,t){return u(await c.get(`${be(e,t)}/machines`),"Failed to list machines").machines}async function Gg(e,t,n,r){return u(await c.post(`${be(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Wg=(e,t,n)=>Gg(e,t,n,"start"),Hg=(e,t,n)=>Gg(e,t,n,"stop"),Vg=(e,t,n)=>Gg(e,t,n,"restart");async function zg(e,t,n){return u(await c.delete(`${be(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Yg(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 Jg(e,t,n){return u(await c.post(`${be(e,t)}/exec`,n),"Failed to run the command")}async function Qg(e,t){return u(await c.get(`${be(e,t)}/volumes`),"Failed to list volumes").volumes}async function Xg(e,t,n){return u(await c.post(`${be(e,t)}/volumes`,n),"Failed to create the volume")}async function Zg(e,t,n,r){return u(await c.patch(`${be(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function em(e,t,n,r){u(await c.delete(`${be(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function tm(e,t,n){return u(await c.get(`${be(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function nm(e,t,n){return u(await c.post(`${be(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function rm(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 sm(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 om(e){let t=u(await c.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new _("Files not found",{status:404});return t[0]}async function QT(e,t){return u(await c.get(`${ge(e)}/access?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load sharing")}async function XT(e,t){return u(await c.put(`${ge(e)}/access`,t),"Failed to share folder")}async function ZT(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 eI(e){return u(await c.get(`${ge(e)}/principals`),"Failed to load people")}async function tI(e){return u(await c.get(`${ge(e)}/conflicts`),"Failed to load conflicts").conflicts}async function nI(e,t){u(await c.post(`${ge(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function rI(e,t="/"){return(await Ks(e,t)).entries}async function Ks(e,t="/"){return u(await c.get(`${ge(e)}/files?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load files")}function im(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 sI(e,t,n){let r=await $(im(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new _(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function am(e,t,n){let r=await $(im(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new _(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function oI(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 iI(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 iI(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 _("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((P,k)=>g.setRequestHeader(k,P)),g.upload.onprogress=P=>s(P.loaded,n.size),g.onload=()=>{h();let P=null;try{P=g.responseText?JSON.parse(g.responseText):null}catch{P=null}if(g.status>=200&&g.status<300)return p(P);g.status===401&&l(),d(new _(P?.message||"Failed to upload file",{status:g.status,code:P?.code,url:i}))},g.onerror=()=>{h(),d(new _("Network error while uploading",{name:"TypeError",url:i}))},g.onabort=()=>{h(),d(m())},g.send(n)})}async function aI(e,t){return u(await c.post(`${ge(e)}/files/mkdir`,{path:t},{showErrors:!1}),"Failed to create folder")}async function cI(e,t,n){return u(await c.post(`${ge(e)}/files/move`,{from:t,to:n},{showErrors:!1}),"Failed to move")}async function lI(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 uI(e){return u(await c.get(`${ge(e)}/versions`),"Failed to load versions").versions}async function pI(e,t){u(await c.post(`${ge(e)}/restore`,{versionId:t}),"Failed to restore version")}var dI=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function gI(e,t){return(await j_(e,t)).drives}async function j_(e,t){return u(await c.get(dI(e,t)),"Failed to load session files")}var mI=new Set(["done","abandoned"]),fI=15*6e4,yI=24*36e5;function D_(e,t,n=Date.now()){if(!e)return{state:"attention",issues:["unreadable"]};if(mI.has(e.status))return{state:"closed",issues:[]};let r=[];if(!t||t.state==="done"?r.push("no_heartbeat"):t.state==="paused"?r.push("heartbeat_paused"):t.last_status==="failed"?r.push("heartbeat_failed"):t.next_fire_at&&Date.parse(t.next_fire_at)<n-fI&&r.push("missed_wake"),(e.items??[]).some(s=>s.kind==="ask"&&s.status==="open"&&s.due&&Date.parse(s.due)<n)&&r.push("ask_overdue"),e.status==="verifying"){let s=[...e.transitions??[]].reverse().find(o=>o.to==="verifying")?.at;s&&Date.parse(s)<n-yI&&r.push("verification_stalled")}return{state:r.length?"attention":"healthy",issues:r}}async function hI(e,t){try{let{entries:n}=await Ks(e,t);return n.filter(r=>r.type==="dir").map(r=>r.path)}catch(n){if(n instanceof _&&n.status===404)return[];throw n}}async function qs(e,t){try{return await(await am(e,t)).blob.text()}catch(n){if(n instanceof _&&n.status===404)return null;throw n}}function _I(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||typeof t!="object"||typeof t.objective!="string")return null;let n=r=>Array.isArray(r)?r.filter(s=>s&&typeof s=="object"):[];return{...t,success_criteria:n(t.success_criteria),items:n(t.items),sessions:n(t.sessions),transitions:n(t.transitions)}}catch{return null}}function bI(e,t,n,r){let s=e.filter(a=>a.state!=="done"),o=t?.reminder_id?s.find(a=>a.id===t.reminder_id):void 0;if(o)return o;let i=`/drives/${n==="company"?"company":"me"}/Goals/${r}`;return s.find(a=>new RegExp(`${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-])`).test(a.prompt))??null}async function SI(e,t){let n=await om(e).catch(l=>{if(l instanceof _&&l.status===404)return null;throw l});if(!n)return[];let r=[{scope:"company",path:"/Company/Goals"}];n.personalFolder&&r.push({scope:"personal",path:`${n.personalFolder}/Goals`});let s=(await Promise.all(r.map(async l=>(await hI(n.driveId,l.path)).sort().map(p=>({...l,folder:p}))))).flat();if(s.length===0)return[];let[{reminders:o},i]=await Promise.all([er(e),Promise.all(s.map(l=>qs(n.driveId,`${l.folder}/goal.json`).then(_I)))]),a=t?.now??Date.now();return s.map((l,p)=>{let d=i[p]??null,g=l.folder.split("/").at(-1)??l.folder,m=bI(o,d,l.scope,g),f=[...d?.sessions??[]].reverse().find(h=>h.role==="coordinator");return{slug:g,scope:l.scope,driveId:n.driveId,folder:l.folder,goal:d,heartbeat:m,coordinatorSessionId:f?.id??m?.session_id??null,health:D_(d,m,a)}})}async function PI(e,t){let[n,r,s]=await Promise.all([qs(e,`${t}/log.md`),qs(e,`${t}/notes.md`),qs(e,`${t}/evidence/verification.md`)]);return{log:n,notes:r,verification:s}}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 tr(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=tr(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return tr(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function xI(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 Gs(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:xI(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 cm(){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:Gs(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 lm(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 Ws(e){let t=await lm(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await nr(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function nr(e){let t=await cm();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 um(e){return u(await c.post("/notifications/device-token",e))}async function pm(e,t){return u(await c.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}async function dm(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 _(`Device token release failed (HTTP ${s.status})`,{status:s.status,response:s});return{ok:!0}}var wI=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered","message"];async function gm(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 mm(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 vI={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 fm(){return u(await c.get("/notifications/preferences",{showErrors:!1}))}async function ym(e){return u(await c.put("/notifications/preferences",e))}async function hm(){return u(await c.get("/notifications/web-push/key",{showErrors:!1}))}async function _m(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 bm(e,t){return u(await c.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function rr(e){return u(await c.get(`/projects/${e}/model-access`))}async function sr(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}async function or(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/custom-providers`)).providers}async function ir(e,t,n){return u(await c.put(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,n))}var L_=e=>e?.status===404;async function ar(e,t){let n=await c.delete(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,{showErrors:!1});if(!n.success&&!L_(n.error))throw n.error??new Error("Failed to delete the custom provider");let r=`CUSTOM_${t.toUpperCase().replace(/-/g,"_")}_API_KEY`;await Dn(e,r).catch(s=>{if(!L_(s))throw s})}function kI(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 Sm(e){return typeof e=="string"&&e.trim().length>0}function $_(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Sm(t)||Sm(n)||Sm(r)}function AI(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 cr(e){if(!e)return!0;let t=AI(e.items);return t?!t.some($_):!$_(e)}var ve="kortix.transcript.v1",U_=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function Pm(e){return typeof e=="string"&&U_.includes(e)}var RI=["once","always","reject"],CI=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var B_="kortix-v1-import",TI={harness:B_,harness_version:ve,adapter_version:"1"},xm={schema:ce,v:1},II={opencode:"[Tool execution was interrupted]",pi:"No result provided"},EI="[Old tool result content cleared]",MI="The following tool was executed by the user",OI=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"})),jI=e=>OI.get(e)??(e.includes("_")?"mcp":"other"),DI=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),LI=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,Ys=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,K_=(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 wm(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)=>wm(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=>wm(e[r],Ys(t,r)))}function Vs(e,t){if(wm(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=Vs(Ys(e,r),Ys(t,r));s&&K_(n,r,s)}return{sub:n}}function zs(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=zs(Ys(n,r),s);o===void 0?delete n[r]:K_(n,r,o)}return n}var lr=e=>Object.values(e??{}).find(t=>t.version===ve),Js=(e,t)=>({[e]:{version:ve,...t}}),q_=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},F_=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),$I=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),UI=e=>{if(B(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==ve&&B(n.data?.details));return t?t.data.details:{}};function FI(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:F_(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,...q_(d,t)}]:[]),p=zt(r?.cleared_at);return{status:"completed",...s,output:F_(r?.content),title:e.title??"",metadata:{...UI(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...l.length&&{attachments:l}}}function G_(e,t){let n=$I(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},...q_(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:FI(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 NI(e){return Pm(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function W_(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:LI.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:NI(e.error)},...n}}function H_(e,t){return e.role==="assistant"?W_(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 V_(e,t,n){let r=`${e.message_id}-summary`;return{info:W_({...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 BI(e,t,n){let r=n||e.producer.harness===B_;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=lr(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=G_(d,i);return g===void 0?[]:[zs(g,lr(d.ext)?.data)]}),l=[{runtime_session_id:o,info:zs(H_(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=zs(V_(e,p,i),s?.summary);l.push({runtime_session_id:o,info:d.info,parts:d.parts})}return l}var vm=e=>Ge(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,Hs=e=>String(B(e.info)?e.info.id:""),z_=(e,t)=>vm(e)-vm(t)||(Hs(e)<Hs(t)?-1:Hs(e)>Hs(t)?1:0),N_=e=>{let t=lr(e.ext);return t?t.native_id??null:e.thread_id};function Qs(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=>BI(a,N_(i),lr(i.ext)!==void 0))),s=lr(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?N_(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(z_)}}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 qI(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 GI=e=>({code:X(e.code)||X(e.name)||"UnknownError",message:X(B(e.data)?e.data.message:void 0)??""});function Y_(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 WI(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:P,...k}=Y_(h,n,r);return{type:"attachment",...k}}),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:EI}],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=II[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:jI(e.tool),input:p,status:a,...l&&{result:l},...X(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function HI(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,...Y_(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)?WI(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 VI(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 zI(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,P=o.live?"streaming":"interrupted",k=g?m?f?"aborted":"error":h?"complete":P:l?P:"complete",T=Vt(B(i.time)?i.time.created:void 0)??"",b=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(R=>B(R)&&R.type==="text"&&typeof R.text=="string"?[R.text]:[]).join(""):null,S={tool_input:0,cut_point:0,attachment:0},O=VI(a),y=a.map((R,L)=>HI(R,O[L],l,b,o,S)),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?k==="complete":!m||f&&w),v=o.live&&x&&k!=="streaming"&&y.some(R=>R.type==="tool_call"&&(R.status==="pending"||R.status==="running"))?"streaming":k,C=s?"superseded":x||!m?void 0:f?"aborted":"failed_attempt";return l&&B(l)&&X(l.tail_start_id)===void 0&&S.cut_point++,{m:{...xm,message_id:X(i.id)??"",thread_id:n,seq:r,role:d,kind:l?"compaction":"turn",status:v,in_context:x,...C&&{hidden_reason:C},agent:X(i.agent)??null,...d==="assistant"&&{reply_to:X(i.parentID)??null},model:KI(i),usage:g?qI(g):null,finish:!g||l?null:f?"aborted":m?"error":DI.get(i.finish)??null,error:m?GI(m):null,created_at:T,completed_at:g||l?h:T||null,producer:TI,blocks:y},lost:S}}function YI(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=Vs(t.parts[d],G_(p,i));g&&(p.ext=Js(s,{data:g}))}):o.parts=t.parts;let a=Vs(t.info,H_(e,i));a&&(o.info=a);let l=e.blocks.find(p=>p.type==="compaction");if(n&&l){let p=Vs({info:n.info,parts:n.parts},V_(e,l,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Js(s,{data:o}))}function JI(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 Xs(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(z_),s=new Map;for(let S of r){let O=s.get(S.runtime_session_id);O?O.push(S):s.set(S.runtime_session_id,[S])}let o=e.root_id,i=s.has(o),a=new Map,l=S=>a.get(S)??(a.set(S,JSON.stringify(S)),a.get(S)),p=new Map;for(let S of s.keys()){let O=i&&S===o?void 0:JI(r,S,l);O&&p.set(S,O)}let d=[...r].reverse().find(S=>S.runtime_session_id===null||!p.has(S.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=S=>S!==null&&p.has(S)?S:m,h=Vt(r.map(vm).find(Number.isFinite))??"",P=[];for(let[S,O]of s){if(S!==g&&(S===null||!p.has(S)))continue;let y=S===g,w=y?r.filter(j=>j.runtime_session_id!==g&&f(j.runtime_session_id)===m):[],x=[...w,...O],v=new Set(w),C=new Map,D=new Set;for(let j of x){let q=B(j.info)?j.info:{};if(q.role!=="user"||!Array.isArray(j.parts)||!j.parts.some(K=>B(K)&&K.type==="compaction"))continue;let W=x.find(K=>!D.has(K)&&K.runtime_session_id===j.runtime_session_id&&B(K.info)&&K.info.role==="assistant"&&K.info.summary===!0&&K.info.parentID===q.id);W&&(C.set(j,W),D.add(W))}let R=[];for(let j of x){if(D.has(j))continue;let q=C.get(j),{m:W,lost:K}=zI(j,q,y?m:S,R.length+1,v.has(j),n);if(YI(W,j,q,S,n.h),W.in_context)for(let De of["tool_input","cut_point","attachment"])n.counts[De]+=K[De];R.push(W)}let L=S===null?void 0:p.get(S),pe=R.find(j=>j.role==="user"&&j.kind==="turn");P.push({...xm,thread_id:y?m:S,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:Js(n.h,S===null?{}:{native_id:S})})}P.sort((S,O)=>S.parent_thread_id===null?-1:O.parent_thread_id===null?1:b(S)-b(O));let k=P[0]?.messages.filter(S=>S.role==="user"&&S.kind==="turn").at(-1),T=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...xm,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:k?.agent??null,model:k?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:P,...g!==o&&{ext:Js(n.h,{data:{root_id:o}})}};function b(S){return r.findIndex(O=>O.runtime_session_id===S.thread_id)}}var km={schema:ce,v:1},QI=Object.freeze({}),J_=new WeakMap;function ur(e){let t=J_.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=Xs({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return J_.set(e,{state:e.state,block:o}),o}var Am=new WeakMap;function Rm(e){if(Am.has(e))return Am.get(e);let t={...km,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:ve}},messages:[{...km,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}=Qs({...km,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 Am.set(e,r),r}function oe(e){return Rm(e)}var me=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",We=e=>me(e)?oe(e):e;function X_(e){let t=oe(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:QI}var Z_=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function eb(e){return e.status==="complete"?"completed":e.status}var Q_=new WeakMap;function tb(e){if(e.status!=="complete")return"";let t=Q_.get(e);return t===void 0&&Q_.set(e,t=Z_(e)),t}function nb(e){return e.status==="error"?e.result?.error?.message||Z_(e):void 0}function fe(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function XI(e){return fe(e)==="bash"}function Cm(e){let t=fe(e);return t==="question"||t==="ask"}function ZI(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var rb=new Set(["show","show_user"]);function Tm(e){return rb.has(fe(e))}function eE(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Im(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Zs(e))}function Zs(e){let t=me(e)?oe(e):e,n=fe(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:cr(t.state?.input)}var sb=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Em(e){return sb.has(fe(e))}var tE=50*1024*1024,Mm="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",nE=new RegExp(`^kortix-attachment://(${Mm})/(${Mm})/(${Mm})$`);function jm(e){if(typeof e!="string")return null;let t=nE.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function rE(e){return jm(e)!==null}var Om=new WeakMap;async function Dm(e,t,n,r={}){if(n.size>tE)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:Om.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=Om.get(n)??new Map;l.set(s,i),Om.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 Lm(e,t){let n=jm(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 _("Could not load attachment",{status:s.status});return s.blob()}var sE=new Set(["show","show_user"]);function oE(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),pr=e=>typeof e=="string"&&e.length>0?e:null,ob=e=>typeof e=="string"?pr(e.split("/").pop()):null;function eo(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function iE(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 aE(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 cE(e,t){for(let n of oE(e))t(eo(n,"attachment"),eo(n,"filename")??ob(eo(n,"path")),eo(n,"mime"))}function lE(e,t){for(let n of[e,...iE(e.items)])He(n)&&t(n.attachment,ob(n.path),null)}function uE(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=He(r)&&Array.isArray(r.blocks)?aE(r):r;if(!He(s)||!He(s.info)||!Array.isArray(s.parts))continue;let o=pr(s.info.id);if(!o)continue;let i=pr(s.info.role)??"unknown",a=(l,p,d)=>{let g=jm(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,pr(l.filename),pr(l.mime)):l.type==="text"&&typeof l.text=="string"?cE(l.text,a):l.type==="tool"&&typeof l.tool=="string"&&sE.has(fe(l.tool))&&He(l.state)&&He(l.state.input)&&lE(l.state.input,a))}return t}function pE(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 dE(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 $m(e,t,n){return e!==void 0?e:pE(st(t),n)}var Um={get disableMobileAdvertising(){return $m(I().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return $m(I().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return $m(I().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var gE=new Set(["project-manager"]);function to(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Um.enableProjects||!gE.has(e.name)}function mE(e){let t=e.agents.filter(to),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function ib(){return{projects:{list:xt,listForAccount:ta,get:wt,detail:In,create:oa,createRepo:ia,provision:aa,update:On,archive:jn,llmCatalog:En,modelPicker:Mn,modelAccess:rr,setModelAccess:sr,customLlmProviders:or,setCustomLlmProvider:ir,deleteCustomLlmProvider:ar,sandboxHealth:$n,sandboxTemplates:Zc,sessions:At,createSession:Rt},github:{linkRepository:ma,replaceProjectRepository:fa,getInstallation:ya,listInstallations:ha,listLinkableInstallations:_a,listRepositories:ba,listRepositoryBranches:Sa,linkInstallation:xa,saveInstallation:Pa,deleteInstallation:va,storeUserToken:wa},gitBackend:{get:ka,repositories:Aa},connectStatus:Hc,marketplace:{items:o=>yg(o),item:o=>bg(o),itemFile:(o,i)=>Sg(o,i),marketplaces:()=>hg(),featured:()=>_g(),sources:{list:()=>Pg(),add:o=>xg(o),remove:o=>wg(o)}}}}function ab(){return{billing:{accountState:Nu,accountStateMinimal:Bu,transactions:Ku,transactionsSummary:qu,creditBreakdown:Gu,usageHistory:Wu,usageRollup:cp,sessionCosts:{list:pp,get:Zn},tierConfigurations:Hu,setPlan:op,previewPlan:sp,acceptEnterpriseOffer:ip,contactSales:ap,checkout:{createSession:n=>Vu(n),confirmSession:(n,r)=>zu(n,r)},subscription:{createPortalSession:(n,r)=>Yu(n,r),cancel:(n,r)=>Ju(n,r),reactivate:n=>Qu(n),scheduleDowngrade:(n,r,s)=>Xu(n,r,s),cancelScheduledChange:n=>Zu(n),prorationPreview:(n,r)=>ep(n,r)},credits:{purchase:n=>tp(n),autoTopupSettings:n=>np(n),configureAutoTopup:n=>rp(n)}},sandboxShares:{list:Id,create:Ed,revoke:Md}}}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 no(e,t){return ie("/auth/signup",{body:e},t)}function ro(e,t){return ie("/auth/sign-in/password",{body:e},t)}function so(e,t){return ie("/auth/sign-in/magic-link",{body:e},t)}function oo(e,t){return ie("/auth/verify-otp",{body:e},t)}function io(e,t){return ie("/auth/sign-in/oauth",{body:e},t)}function ao(e,t){return ie("/auth/oauth/exchange",{body:e},t)}function Jt(e,t){return ie("/auth/refresh",{body:e},t)}function co(e,t){return ie("/auth/password/reset",{body:e},t)}function lo(e,t,n){return ie("/auth/password/update",{body:e,bearer:t},n)}function uo(e,t){return ie("/auth/user",{bearer:e},t)}function po(e,t,n){return ie("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function go(e,t){return ie("/auth/sign-in/sso",{body:e},t)}var mo={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 fo(e,t={},n){return ie("/auth/sign-out",{body:t,bearer:e},n)}function yo(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=P=>(P.expires_at??0)*1e3,g=P=>d(P)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let P of[...p])try{P(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let P=l,k=(async()=>{let T=await e.storage.get();if(P===l&&T)try{let b=JSON.parse(T);b.session?.access_token&&b.session?.refresh_token&&(r=b.session,s=b.user??null)}catch{r=null}return o=!0,r})();i=k,k.then(()=>{i===k&&(i=null)},()=>{i===k&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let P=r.refresh_token,k=l,T=Jt({refresh_token:P},e.request).then(async b=>(k!==l||(r=b.session,b.user&&(s=b.user),await m()),r)).catch(async b=>{if(k!==l)return r;let S=b&&typeof b=="object"&&"status"in b?b.status:0;if(S>=400&&S<500)return r=null,s=null,await m(),null;throw b}).finally(()=>{a===T&&(a=null)});a=T}return a}return{subscribe(P){return p.add(P),()=>{p.delete(P)}},current:()=>r,user:()=>s,load:f,async set(P,k){await f(),l+=1,a=null,r=P,k!==void 0&&(s=k),P||(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 cb(){return{list:Oi,get:Di,create:ji,secretResources:{list:rc,create:sc,rotate:oc,retry:ic,remove:ac,grant:cc,revoke:lc,setAccess:uc},updateName:Li,branding:{get:$i,update:Ui,uploadAsset:Fi,removeAsset:Ni,reset:Bi},leave:Zi,members:Ki,invite:qi,removeMember:Qi,updateMemberRole:Xi,invites:Gi,cancelInvite:Wi,resendInvite:Hi,tokens:{list:Qd,create:Xd,revoke:Zd},connectedApps:{list:eg,revoke:tg},audit:{log:ig,export:lg,activity:ag,webhooks:{list:ug,create:pg,update:dg,remove:gg}}}}function lb(){return{assignments:{list:Sd,create:Pd,revoke:xd},permissions:{list:wd,forRole:id},roles:{list:rd,create:cd,update:ld,setPermissions:ud,remove:pd,usage:ad},groups:{list:Yp,get:Jp,create:Qp,update:Xp,remove:Zp,members:{list:ed,add:td,remove:nd}},agentIdentities:sd,oauthClients:{list:md,get:fd,create:yd,update:hd,rotateSecret:_d,remove:bd},can:dd,canBatch:gd}}function ub(){let e={signUp:no,signInWithPassword:ro,sendMagicLink:so,verifyOtp:oo,signInWithProvider:io,exchangeCode:ao,refresh:Jt,resetPassword:co,updatePassword:lo,updateUserMetadata:po,signInWithSso:go,mfa:mo,user:uo,signOut:fo,session:yo},t=cb(),n=lb();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Vi,describe:zi,accept:ps,acceptAndLand:Yi,decline:Ji}}}var dr=new Map,Fm=new Map;function Nm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function pb(e){return dr.get(Nm(e))??null}function db(){return[...dr.values()].filter(e=>typeof e=="string")}function gb(e){return dr.has(Nm(e))}async function it(e){let t=Nm(e),n=dr.get(t);if(n!==void 0)return n;let r=Fm.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 dr.set(t,i),i}catch{return null}finally{Fm.delete(t)}})();return Fm.set(t,s),s}function mb(e){let{apiBaseUrl:t}=e;return gb(t)||it(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:pb(t)}}function fb(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 _(`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),mb({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function yb(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},yE=new Set;function ho(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 yE)r()}}function hb(){return Qt.url}var gr=new Map;function _b(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var 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 bb(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 _(_b(i),{code:"RUNTIME_UNAVAILABLE"});let l=i.sandbox.external_id;if(!l)throw new _("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ie(l);return ho(p,l),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:l}}return n}function Sb(e,t,n){let r=null;function s(){if(r)return r;let p=m_(e,t);return p&&(r=p),r}let o=bb(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?Eu(p.session):null,h=f?.sandbox?.external_id,P=f?.runtime_session_id;if(h&&P){let S=Ie(h);return ho(S,h),r={runtimeSessionId:P,opencodeSessionId:P,runtimeUrl:S,sandboxId:h},Is(e,t,r),await m,r}let k=`${e}
15
- ${t}`,T=gr.get(k);if(T)return r=await T,await m,r;let b=o(g);gr.set(k,b);try{return r=await b,await m,r}finally{gr.get(k)===b&&gr.delete(k)}}function a(p){let d=s();if(!d)throw new Ct(p);return d}function l(){r=null,f_(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:l}}var G=["directory","workspace"],Pb=["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}),hE={"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,Pb),"session.promptAsync":E("POST","/session/{sessionID}/prompt_async",G,Pb),"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 _E(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 bE(e,t,n={},r={}){let s=hE[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}${_E(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 PE(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 Bm(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,`
13
+ `);let h=ER(f);if(h){if(r(h),h.type==="error")throw new _(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function yu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function hu(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function _u(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Zn(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function bu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function Su(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function MR(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 Pu(e){return u(await c.get(`/projects/${e}/triggers`))}async function xu(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function wu(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function ku(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function OR(e){return u(await c.get(`/accounts/${e}/automations`))}async function jR(e,t){return u(await c.patch(`/accounts/${e}/automations`,{paused:t},{showErrors:!1}))}async function vu(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function m_(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 Au(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 Ru(e,t,n){return u(await c.get(`/projects/${e}/triggers/${t}/runs${m_(n)}`))}async function Cu(e,t){return u(await c.get(`/projects/${e}/trigger-runs${m_(t)}`))}async function Tu(e,t,n,r){return u(await c.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function Iu(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 Eu(e){return u(await c.get(`/projects/${e}/triggers/event-apps`))}var tt=new Map;function Mu(e,t){return`${e}::${t}`}function f_(e,t){tt.delete(e),tt.set(e,t)}function y_(e,t){let n=Mu(e,t),r=tt.get(n);return r&&f_(n,r),r}function Is(e,t,n){let r=Mu(e,t);if(!tt.has(r)&&tt.size>=512){let s=tt.keys().next().value;s!==void 0&&tt.delete(s)}f_(r,n)}function h_(e,t){tt.delete(Mu(e,t))}function DR(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Ct(){return DR(I().backendUrl||"http://localhost:8008/v1")}function __(){let e=I().sandboxId;return e?`${Ct()}/p/${e}/8000`:""}function LR(e,t=8e3){return`${Ct()}/p/${e}/${t}`}function Ie(e,t=8e3){return LR(e,t)}function Ou(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var Es=class extends Error{status;code;terminal;constructor(t,n){super(t),this.name="SessionStartError",this.status=n.status,this.code=n.code,this.terminal=n.terminal}};function $R(e){return e instanceof Error&&e.name==="SessionStartError"}function UR(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Es(s,{status:n,code:r,terminal:!0}):null}function b_(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 b_(e,t,n);if(!r.success||!r.data){let s=UR(r.error);if(s&&!(s.status===404&&Dl(t)))throw s;return null}return S_(e,t,r.data)}async function ju(e,t,n){let r=await b_(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return S_(e,t,r.data)}function S_(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Is(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Ie(r),sandboxId:r}),n}function FR(e,t){return["session-start",e,t]}async function Du(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function Lu(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function $u(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await c.delete(`/projects/${e}/model-defaults?${n}`))}async function NR(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 BR(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Ms(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&&!BR(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 Uu(e,t,n){let r=Ms(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function KR(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Fu(n.block):null}}async function qR(e,t,n){let r=Fu(n,!0),s=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Fu(s.block):null}}function Fu(e,t=!1){let n=Ms(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 GR(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Nu(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}var Os="Use setBillingPlan().",x_="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Bu(){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 WR(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function HR(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??Bu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:WR(r),label:s,sublabel:null,monthlyUsd:null}}function w_(e){return!!e&&e.can_manage_billing!==!1}function VR(e){return e?.subscription?.can_purchase_credits===!0&&w_(e)}async function k_(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?Bu():t.data}function v_(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 Ku(e){return k_(`/billing/account-state${v_(e)}`)}async function qu(e){return k_(`/billing/account-state/minimal${v_(e)}`)}async function Gu(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 Wu(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 Hu(){return u(await c.get("/billing/credit-breakdown"))}async function Vu(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function zu(){return u(await c.get("/billing/tier-configurations"))}async function zR(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Ut(e,`/v1/billing/account-state${t}`)}async function Yu(e){throw N("createCheckoutSession",Os)}async function Ju(e,t){throw N("confirmCheckoutSession",Os)}async function Qu(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Xu(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Zu(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function ep(e,t,n){throw N("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function tp(e){throw N("cancelScheduledChange",x_)}async function np(e,t){throw N("getProrationPreview",x_)}async function rp(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 sp(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 YR(e){return u(await c.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function op(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 JR(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 ip(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 ap(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 cp(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 lp(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 QR(e){throw N("createPerSeatCheckout",Os)}async function XR(e){throw N("claimPerSeatBilling",Os)}async function ZR(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function up(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 dp(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function js(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 gp(e={}){let t=new URLSearchParams;return dp(t,e),e.ownerId&&t.set("owner_id",e.ownerId),js(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 er(e,t={}){let n=new URLSearchParams;return dp(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Ds(n)}`))}async function eC(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),js(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 tC(e={}){let t=new URLSearchParams;return dp(t,e),e.sessionId&&t.set("session_id",e.sessionId),js(t,e),u(await c.get(`/usage/cost-summary${Ds(t)}`))}function pp(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)}js(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 nC(e,t={}){let n=pp(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 A_(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function rC(e){return A_("slack",e)}function sC(e){return A_("teams",e)}async function R_(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function oC(e){return R_("slack",e)}function iC(e){return R_("teams",e)}async function mp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function fp(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var aC={oauth_available:!1,install_url:null};async function yp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?aC:t.data}async function C_(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 hp(e,t){return C_("slack",e,t)}function _p(e,t){return C_("teams",e,t)}async function bp(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Sp(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 cC(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/telegram/installation`,{showErrors:!1});return t.success?t.data??null:null}async function lC(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/telegram/connect`,t,{showErrors:!1}),"Failed to connect Telegram")}async function uC(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 pC(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 Pp(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 xp(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 wp(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 dC={provider:"agentmail",managed_available:!1};async function kp(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?wp(r.data):null}async function vp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?dC:t.data}async function Ap(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return wp(n)}async function Rp(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 Cp(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 wp(r)}async function gC(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function mC(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 Tp(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Ip(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Ep(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Mp(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Op(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 jp(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Dp(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Lp(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function $p(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Up(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Fp(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Np(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Bp(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Kp(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function qp(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Gp(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Wp(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Hp(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 fC(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function yC(){throw N("getReferralCode")}async function hC(){throw N("refreshReferralCode")}async function _C(e){throw N("validateReferralCode")}async function bC(){throw N("getReferralStats")}async function SC(e={}){throw N("listReferrals")}async function PC(e){throw N("sendReferralEmails")}var Vp="call:";function Yp(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Vp)&&e.length>Vp.length?{type:"connector_call",executionId:e.slice(Vp.length)}:{type:"review_item",reviewItemId:e}}function I_(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function xC(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[I_(n.status)]+=1;return t}function wC(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 zp(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Jp(e){let t=e.indexOf(".");return t<=0?zp(e):`(${zp(e.slice(0,t))}) ${zp(e.slice(t+1))}`}function kC(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Ht=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,T_=e=>typeof e=="number"?e:0,vC=e=>e.split(`
14
+ `).map(t=>t.trim()).filter(Boolean);function AC(e,t){let n=Ht(e.advanced),r=U(e.description),s=Ee(e.whatChanged)??(r?vC(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:T_(n.additions),deletions:T_(n.deletions),files:Ee(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function RC(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}=kC(r),i=Ht(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?Jp(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(Ht(e.resolved_preview)).length>0?{resolvedPreview:Ht(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 CC(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 TC(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:Ee(e.options)??[]}}function IC(e,t){return{note:U(e.note)??t.summary??"",children:Ee(e.children)??[]}}function EC(e){let t=Ht(e.detail);switch(e.kind){case"change":return AC(t,e);case"approval":return RC(t,e);case"output":return CC(t,e);case"decision":return TC(t,e);case"batch":return IC(t,e)}}function MC(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 OC(e,t={}){let n=Ht(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"?MC(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?Jp(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:EC(e)}}var X={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"},jC=[X.PROJECT_WRITE,X.PROJECT_TRIGGER_CREATE,X.PROJECT_TRIGGER_FIRE,X.PROJECT_TRIGGER_UPDATE,X.PROJECT_TRIGGER_DELETE];function DC(e){let t=r=>e[r]?.allowed===!0,n=t(X.PROJECT_WRITE);return{canCreate:n&&t(X.PROJECT_TRIGGER_CREATE),canFire:t(X.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(X.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(X.PROJECT_TRIGGER_DELETE)}}var LC=[X.PROJECT_WRITE,X.PROJECT_GITOPS_PUSH,X.PROJECT_GITOPS_MERGE,X.PROJECT_REVIEW_ACT];function E_(e){let t=r=>e[r]?.allowed===!0,n=t(X.PROJECT_WRITE);return{canOpen:n&&t(X.PROJECT_GITOPS_PUSH),canMerge:n&&t(X.PROJECT_GITOPS_MERGE),canClose:n}}function $C(e,t,n){let r=Yp(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 E_(n).canMerge}return n[X.PROJECT_WRITE]?.allowed===!0&&n[X.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 Qp(e){return A(await F(`/accounts/${e}/iam/groups`)).groups}async function Xp(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}`))}async function Zp(e,t){return A(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function ed(e,t,n){return A(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function td(e,t){return A(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function nd(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/members`)).members}async function rd(e,t,n){return A(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function UC(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function sd(e,t,n){return A(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function FC(e,t){return A(await F(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function NC(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 BC(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 KC(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 qC(e,t){return A(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function GC(e,t,n){return A(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function WC(e,t){return A(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function HC(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function VC(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function od(e){return A(await F(`/accounts/${e}/iam/roles`)).roles}async function id(e){return A(await F(`/accounts/${e}/iam/agent-identities`)).agents}async function ad(e){return A(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function cd(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/permissions`))}async function zC(e){return A(await F(`/accounts/${e}/iam/actions`)).actions}async function ld(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/usage`))}async function ud(e,t){return A(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function pd(e,t,n){return A(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function dd(e,t,n){return A(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function gd(e,t){return A(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function YC(e,t,n){return A(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function JC(e){return A(await F(`/accounts/${e}/iam/scim/tokens`)).tokens}async function QC(e,t){return A(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function XC(e,t){return A(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function ZC(e){return A(await F(`/accounts/${e}/iam/mfa-required`))}async function eT(e){return A(await F(`/accounts/${e}/iam/mfa-required/preview`))}async function tT(e,t){return A(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function nT(e){return A(await F(`/accounts/${e}/iam/session-oversight`))}async function rT(e,t){return A(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function sT(e){return A(await F(`/accounts/${e}/iam/sso/provider`)).provider}async function oT(e,t){return A(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function iT(e,t){return A(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function aT(e){return A(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function cT(e){return A(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function lT(e){return A(await F(`/accounts/${e}/iam/sso/mappings`)).mappings}async function uT(e,t){return A(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function pT(e,t){return A(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function dT(e){return A(await F(`/accounts/${e}/iam/session-policy`))}async function gT(e,t){return A(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function mT(e){return A(await F(`/accounts/${e}/iam/sessions`)).sessions}async function fT(e,t){return A(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function yT(e){return A(await F(`/accounts/${e}/iam/pat-policy`))}async function hT(e,t){return A(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function _T(e){return A(await F(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function bT(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 PT(e,t){return A(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function xT(e){return A(await F(`/accounts/${e}/audit/webhooks`)).webhooks}async function wT(e,t){return A(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function kT(e,t,n){return A(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function vT(e,t){return A(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function AT(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 md(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 fd(e,t,n){return n.length===0?[]:A(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function RT(e){return A(await F(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function CT(e,t){return A(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function yd(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function hd(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function _d(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function bd(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function Sd(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Pd(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function TT(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 xd(e,t){return u(await F(`/accounts/${e}/iam/assignments${TT(t)}`)).assignments}async function wd(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 kd(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function vd(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await F(`/accounts/${e}/iam/permissions${n}`)).permissions}async function IT(){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 ET(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function MT(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function OT(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function jT(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function DT(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function LT(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function $T(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function UT(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function FT(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function NT(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function BT(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var M_="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function KT(e){throw N("getGoogleAuthUrl",M_)}async function qT(e,t){throw N("convertPresentationToGoogleSlides",M_)}async function Ad(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 Rd(e){return u(await c.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function Cd(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function Td(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function Id(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function Ed(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}async function Md(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Od(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 jd(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 Ls=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function O_(e,t=""){return`${Ct()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function j_(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 Ls(s,t.status)}return r}async function GT(e){return j_(O_(e))}async function WT(e){return j_(O_(e,"/messages"))}async function Dd(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function Ld(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function $s(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Us(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}async function $d(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders/${n}/run`,{}))}var HT=4;async function D_(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(HT,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 Ud(e,t,n){return D_(t,r=>$s(e,r.sessionId,r.reminderId,n))}function Fd(e,t){return D_(t,n=>Us(e,n.sessionId,n.reminderId))}async function tr(e){return u(await c.get(`/projects/${e}/reminders`))}var xe=e=>`/projects/${e}/rooms`;function Nd(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 Bd(e,t={}){return u(await c.get(`${xe(e)}${Nd({name:t.name,archived:t.archived,mine:t.mine})}`))}async function Kd(e,t){return u(await c.post(xe(e),t))}async function qd(e,t){return u(await c.get(`${xe(e)}/${t}`))}async function Gd(e,t,n){return u(await c.patch(`${xe(e)}/${t}`,n))}async function Wd(e,t,n={}){return u(await c.get(`${xe(e)}/${t}/messages${Nd({after:n.after,before:n.before,limit:n.limit,top:n.top,thread:n.thread})}`))}async function Hd(e,t,n){return u(await c.post(`${xe(e)}/${t}/messages`,n))}async function Vd(e,t,n){return u(await c.post(`${xe(e)}/${t}/read`,n===void 0?{}:{seq:n}))}async function zd(e,t,n,r={}){return u(await c.put(`${xe(e)}/${t}/members/sessions/${n}`,r))}async function Yd(e,t,n){return u(await c.delete(`${xe(e)}/${t}/members/sessions/${n}`))}async function Jd(e,t,n,r={}){return u(await c.put(`${xe(e)}/${t}/members/people/${n}`,r))}async function Qd(e,t,n){return u(await c.delete(`${xe(e)}/${t}/members/people/${n}`))}async function Xd(e,t){return u(await c.get(`${xe(e)}/people${Nd({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 VT(e){return u(await c.post("/cli/device/decide",{user_code:e,approve:!0}))}async function eg(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 tg(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 ng(){return u(await c.get("/oauth/grants")).grants}async function rg(e){return u(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function zT(){return u(await c.get("/accounts/me/devices")).devices}async function YT(e){return u(await c.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function sg(e){return u(await c.get(`/projects/${e}/cli-token`))}async function og(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function ig(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}function Vt(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 ag(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 cg(e,t){let n=Vt(ag(t)).toString();return u(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function lg(e,t={}){let n=new URLSearchParams,r={since:t.since,until:t.until,project_id:t.projectId,actor:t.actor,client:t.client,actor_type:t.actorType,credential_kind:t.credentialKind};for(let[o,i]of Object.entries(r))i&&n.set(o,i);let s=n.toString();return u(await c.get(`/accounts/${e}/audit/activity${s?`?${s}`:""}`))}async function ug(e,t){let n=Vt(ag({...t,projectId:void 0})).toString();return u(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function pg(e,t){let n=Vt(ag(t)).toString();return u(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function dg(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function gg(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function mg(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function fg(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function yg(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 hg(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 _g(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 bg(){return u(await c.get("/marketplace/marketplaces"))}async function Sg(){return u(await c.get("/marketplace/marketplaces/featured"))}async function Pg(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function xg(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function wg(){return u(await c.get("/marketplace/sources"))}async function kg(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function vg(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function QT(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function XT(e){throw N("getTemplate")}async function ZT(e,t){throw N("installTemplate")}async function Ag(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Rg(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Fs(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Cg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Tg(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Ig(e,t){return u(await c.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function Eg(e,t){let n=await Fs(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 Mg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Og(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 jg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Dg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Ns(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Bs(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function eI(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function tI(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 Lg(e,t,n={}){let r=await eI(t),s=n.mediaType??"application/gzip",o=await Ns(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),Bs(e,o.artifact.artifact_id,{sha256:await tI(r),size_bytes:r.byteLength})}async function $g(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Ug(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Fg(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Ng(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 Bg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Kg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function qg(e,t,n){return u(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Gg(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 Wg(e,t){return u(await c.get(`${be(e,t)}/machines`),"Failed to list machines").machines}async function Hg(e,t,n,r){return u(await c.post(`${be(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Vg=(e,t,n)=>Hg(e,t,n,"start"),zg=(e,t,n)=>Hg(e,t,n,"stop"),Yg=(e,t,n)=>Hg(e,t,n,"restart");async function Jg(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 Xg(e,t,n){return u(await c.post(`${be(e,t)}/exec`,n),"Failed to run the command")}async function Zg(e,t){return u(await c.get(`${be(e,t)}/volumes`),"Failed to list volumes").volumes}async function em(e,t,n){return u(await c.post(`${be(e,t)}/volumes`,n),"Failed to create the volume")}async function tm(e,t,n,r){return u(await c.patch(`${be(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function nm(e,t,n,r){u(await c.delete(`${be(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function rm(e,t,n){return u(await c.get(`${be(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function sm(e,t,n){return u(await c.post(`${be(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function om(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 im(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 am(e){let t=u(await c.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new _("Files not found",{status:404});return t[0]}async function nI(e,t){return u(await c.get(`${ge(e)}/access?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load sharing")}async function rI(e,t){return u(await c.put(`${ge(e)}/access`,t),"Failed to share folder")}async function sI(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 oI(e){return u(await c.get(`${ge(e)}/principals`),"Failed to load people")}async function iI(e){return u(await c.get(`${ge(e)}/conflicts`),"Failed to load conflicts").conflicts}async function aI(e,t){u(await c.post(`${ge(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function cI(e,t="/"){return(await Ks(e,t)).entries}async function Ks(e,t="/"){return u(await c.get(`${ge(e)}/files?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load files")}function cm(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 lI(e,t,n){let r=await $(cm(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new _(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function lm(e,t,n){let r=await $(cm(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new _(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function uI(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 pI(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 pI(e,t,n,r,s,o){let i=`${le(I().backendUrl)}${t}`,{headers:a,rejected:l}=await $t(i,{"Content-Type":"application/octet-stream",...r});return new Promise((p,d)=>{let g=new e,m=()=>new _("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((P,v)=>g.setRequestHeader(v,P)),g.upload.onprogress=P=>s(P.loaded,n.size),g.onload=()=>{h();let P=null;try{P=g.responseText?JSON.parse(g.responseText):null}catch{P=null}if(g.status>=200&&g.status<300)return p(P);g.status===401&&l(),d(new _(P?.message||"Failed to upload file",{status:g.status,code:P?.code,url:i}))},g.onerror=()=>{h(),d(new _("Network error while uploading",{name:"TypeError",url:i}))},g.onabort=()=>{h(),d(m())},g.send(n)})}async function dI(e,t){return u(await c.post(`${ge(e)}/files/mkdir`,{path:t},{showErrors:!1}),"Failed to create folder")}async function gI(e,t,n){return u(await c.post(`${ge(e)}/files/move`,{from:t,to:n},{showErrors:!1}),"Failed to move")}async function mI(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 fI(e){return u(await c.get(`${ge(e)}/versions`),"Failed to load versions").versions}async function yI(e,t){u(await c.post(`${ge(e)}/restore`,{versionId:t}),"Failed to restore version")}var hI=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function _I(e,t){return(await L_(e,t)).drives}async function L_(e,t){return u(await c.get(hI(e,t)),"Failed to load session files")}var bI=new Set(["done","abandoned"]),SI=15*6e4,PI=24*36e5;function $_(e,t,n=Date.now()){if(!e)return{state:"attention",issues:["unreadable"]};if(bI.has(e.status))return{state:"closed",issues:[]};let r=[];if(!t||t.state==="done"?r.push("no_heartbeat"):t.state==="paused"?r.push("heartbeat_paused"):t.last_status==="failed"?r.push("heartbeat_failed"):t.next_fire_at&&Date.parse(t.next_fire_at)<n-SI&&r.push("missed_wake"),(e.items??[]).some(s=>s.kind==="ask"&&s.status==="open"&&s.due&&Date.parse(s.due)<n)&&r.push("ask_overdue"),e.status==="verifying"){let s=[...e.transitions??[]].reverse().find(o=>o.to==="verifying")?.at;s&&Date.parse(s)<n-PI&&r.push("verification_stalled")}return{state:r.length?"attention":"healthy",issues:r}}async function xI(e,t){try{let{entries:n}=await Ks(e,t);return n.filter(r=>r.type==="dir").map(r=>r.path)}catch(n){if(n instanceof _&&n.status===404)return[];throw n}}async function qs(e,t){try{return await(await lm(e,t)).blob.text()}catch(n){if(n instanceof _&&n.status===404)return null;throw n}}function wI(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||typeof t!="object"||typeof t.objective!="string")return null;let n=r=>Array.isArray(r)?r.filter(s=>s&&typeof s=="object"):[];return{...t,success_criteria:n(t.success_criteria),items:n(t.items),sessions:n(t.sessions),transitions:n(t.transitions)}}catch{return null}}function kI(e,t,n,r){let s=e.filter(a=>a.state!=="done"),o=t?.reminder_id?s.find(a=>a.id===t.reminder_id):void 0;if(o)return o;let i=`/drives/${n==="company"?"company":"me"}/Goals/${r}`;return s.find(a=>new RegExp(`${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-])`).test(a.prompt))??null}async function vI(e,t){let n=await am(e).catch(l=>{if(l instanceof _&&l.status===404)return null;throw l});if(!n)return[];let r=[{scope:"company",path:"/Company/Goals"}];n.personalFolder&&r.push({scope:"personal",path:`${n.personalFolder}/Goals`});let s=(await Promise.all(r.map(async l=>(await xI(n.driveId,l.path)).sort().map(p=>({...l,folder:p}))))).flat();if(s.length===0)return[];let[{reminders:o},i]=await Promise.all([tr(e),Promise.all(s.map(l=>qs(n.driveId,`${l.folder}/goal.json`).then(wI)))]),a=t?.now??Date.now();return s.map((l,p)=>{let d=i[p]??null,g=l.folder.split("/").at(-1)??l.folder,m=kI(o,d,l.scope,g),f=[...d?.sessions??[]].reverse().find(h=>h.role==="coordinator");return{slug:g,scope:l.scope,driveId:n.driveId,folder:l.folder,goal:d,heartbeat:m,coordinatorSessionId:f?.id??m?.session_id??null,health:$_(d,m,a)}})}async function AI(e,t){let[n,r,s]=await Promise.all([qs(e,`${t}/log.md`),qs(e,`${t}/notes.md`),qs(e,`${t}/evidence/verification.md`)]);return{log:n,notes:r,verification:s}}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 nr(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=nr(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return nr(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function RI(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 Gs(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:RI(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 um(){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:Gs(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 pm(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 Ws(e){let t=await pm(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await rr(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function rr(e){let t=await um();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 dm(e){return u(await c.post("/notifications/device-token",e))}async function gm(e,t){return u(await c.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}async function mm(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 _(`Device token release failed (HTTP ${s.status})`,{status:s.status,response:s});return{ok:!0}}var CI=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered","message"];async function fm(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 ym(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 TI={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 hm(){return u(await c.get("/notifications/preferences",{showErrors:!1}))}async function _m(e){return u(await c.put("/notifications/preferences",e))}async function bm(){return u(await c.get("/notifications/web-push/key",{showErrors:!1}))}async function Sm(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 sr(e){return u(await c.get(`/projects/${e}/model-access`))}async function or(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}async function ir(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/custom-providers`)).providers}async function ar(e,t,n){return u(await c.put(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,n))}var U_=e=>e?.status===404;async function cr(e,t){let n=await c.delete(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,{showErrors:!1});if(!n.success&&!U_(n.error))throw n.error??new Error("Failed to delete the custom provider");let r=`CUSTOM_${t.toUpperCase().replace(/-/g,"_")}_API_KEY`;await $n(e,r).catch(s=>{if(!U_(s))throw s})}function II(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 xm(e){return typeof e=="string"&&e.trim().length>0}function F_(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return xm(t)||xm(n)||xm(r)}function EI(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 lr(e){if(!e)return!0;let t=EI(e.items);return t?!t.some(F_):!F_(e)}var ke="kortix.transcript.v1",N_=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function wm(e){return typeof e=="string"&&N_.includes(e)}var MI=["once","always","reject"],OI=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var q_="kortix-v1-import",jI={harness:q_,harness_version:ke,adapter_version:"1"},km={schema:ce,v:1},DI={opencode:"[Tool execution was interrupted]",pi:"No result provided"},LI="[Old tool result content cleared]",$I="The following tool was executed by the user",UI=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"})),FI=e=>UI.get(e)??(e.includes("_")?"mcp":"other"),NI=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),BI=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Z=e=>typeof e=="string"?e:void 0,Ge=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ys=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,G_=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),zt=e=>Ge(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Yt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function vm(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)=>vm(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=>vm(e[r],Ys(t,r)))}function Vs(e,t){if(vm(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=Vs(Ys(e,r),Ys(t,r));s&&G_(n,r,s)}return{sub:n}}function zs(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=zs(Ys(n,r),s);o===void 0?delete n[r]:G_(n,r,o)}return n}var ur=e=>Object.values(e??{}).find(t=>t.version===ke),Js=(e,t)=>({[e]:{version:ke,...t}}),W_=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},B_=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),KI=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),qI=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 GI(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=Yt(e.started_at)??t.created,i=Yt(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:B_(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,...W_(d,t)}]:[]),p=Yt(r?.cleared_at);return{status:"completed",...s,output:B_(r?.content),title:e.title??"",metadata:{...qI(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...l.length&&{attachments:l}}}function H_(e,t){let n=KI(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},...W_(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:GI(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 WI(e){return wm(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function V_(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:BI.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:Yt(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:WI(e.error)},...n}}function z_(e,t){return e.role==="assistant"?V_(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 Y_(e,t,n){let r=`${e.message_id}-summary`;return{info:V_({...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 HI(e,t,n){let r=n||e.producer.harness===q_;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=ur(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:Yt(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=H_(d,i);return g===void 0?[]:[zs(g,ur(d.ext)?.data)]}),l=[{runtime_session_id:o,info:zs(z_(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=zs(Y_(e,p,i),s?.summary);l.push({runtime_session_id:o,info:d.info,parts:d.parts})}return l}var Am=e=>Ge(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,Hs=e=>String(B(e.info)?e.info.id:""),J_=(e,t)=>Am(e)-Am(t)||(Hs(e)<Hs(t)?-1:Hs(e)>Hs(t)?1:0),K_=e=>{let t=ur(e.ext);return t?t.native_id??null:e.thread_id};function Qs(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=>HI(a,K_(i),ur(i.ext)!==void 0))),s=ur(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?K_(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(J_)}}function VI(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=Z(t.p),r=Z(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...Z(t.v)!==void 0&&{variant:t.v}}}function zI(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 YI=e=>({code:Z(e.code)||Z(e.name)||"UnknownError",message:Z(B(e.data)?e.data.message:void 0)??""});function Q_(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:Z(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...Z(e.url)!==void 0&&{url:e.url}}}function JI(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:P,...v}=Q_(h,n,r);return{type:"attachment",...v}}),f=zt(o.compacted);a="complete",l={content:[...Z(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:LI}],cleared_at:f}}}else if(s.status==="error"){let m=Z(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"&&Z(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=zt(o.start),g=zt(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:FI(e.tool),input:p,status:a,...l&&{result:l},...Z(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function QI(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:$I}});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),...Z(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&B(e.state)?JI(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:Z(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(Z(e.type)||"unknown")}}function XI(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 ZI(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)?zt(g.time.completed):null,P=o.live?"streaming":"interrupted",v=g?m?f?"aborted":"error":h?"complete":P:l?P:"complete",T=zt(B(i.time)?i.time.created:void 0)??"",b=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(R=>B(R)&&R.type==="text"&&typeof R.text=="string"?[R.text]:[]).join(""):null,S={tool_input:0,cut_point:0,attachment:0},O=XI(a),y=a.map((R,L)=>QI(R,O[L],l,b,o,S)),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)&&Z(l.tail_start_id)===void 0&&S.cut_point++,{m:{...km,message_id:Z(i.id)??"",thread_id:n,seq:r,role:d,kind:l?"compaction":"turn",status:k,in_context:x,...C&&{hidden_reason:C},agent:Z(i.agent)??null,...d==="assistant"&&{reply_to:Z(i.parentID)??null},model:VI(i),usage:g?zI(g):null,finish:!g||l?null:f?"aborted":m?"error":NI.get(i.finish)??null,error:m?YI(m):null,created_at:T,completed_at:g||l?h:T||null,producer:jI,blocks:y},lost:S}}function eE(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:Yt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=Vs(t.parts[d],H_(p,i));g&&(p.ext=Js(s,{data:g}))}):o.parts=t.parts;let a=Vs(t.info,z_(e,i));a&&(o.info=a);let l=e.blocks.find(p=>p.type==="compaction");if(n&&l){let p=Vs({info:n.info,parts:n.parts},Y_(e,l,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=Js(s,{data:o}))}function tE(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 Xs(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(J_),s=new Map;for(let S of r){let O=s.get(S.runtime_session_id);O?O.push(S):s.set(S.runtime_session_id,[S])}let o=e.root_id,i=s.has(o),a=new Map,l=S=>a.get(S)??(a.set(S,JSON.stringify(S)),a.get(S)),p=new Map;for(let S of s.keys()){let O=i&&S===o?void 0:tE(r,S,l);O&&p.set(S,O)}let d=[...r].reverse().find(S=>S.runtime_session_id===null||!p.has(S.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=S=>S!==null&&p.has(S)?S:m,h=zt(r.map(Am).find(Number.isFinite))??"",P=[];for(let[S,O]of s){if(S!==g&&(S===null||!p.has(S)))continue;let y=S===g,w=y?r.filter(j=>j.runtime_session_id!==g&&f(j.runtime_session_id)===m):[],x=[...w,...O],k=new Set(w),C=new Map,D=new Set;for(let j of x){let q=B(j.info)?j.info:{};if(q.role!=="user"||!Array.isArray(j.parts)||!j.parts.some(K=>B(K)&&K.type==="compaction"))continue;let W=x.find(K=>!D.has(K)&&K.runtime_session_id===j.runtime_session_id&&B(K.info)&&K.info.role==="assistant"&&K.info.summary===!0&&K.info.parentID===q.id);W&&(C.set(j,W),D.add(W))}let R=[];for(let j of x){if(D.has(j))continue;let q=C.get(j),{m:W,lost:K}=ZI(j,q,y?m:S,R.length+1,k.has(j),n);if(eE(W,j,q,S,n.h),W.in_context)for(let De of["tool_input","cut_point","attachment"])n.counts[De]+=K[De];R.push(W)}let L=S===null?void 0:p.get(S),pe=R.find(j=>j.role==="user"&&j.kind==="turn");P.push({...km,thread_id:y?m:S,parent_thread_id:L?f(L.row.runtime_session_id):null,spawned_by:L&&typeof L.part.callID=="string"?{message_id:Z(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:Js(n.h,S===null?{}:{native_id:S})})}P.sort((S,O)=>S.parent_thread_id===null?-1:O.parent_thread_id===null?1:b(S)-b(O));let v=P[0]?.messages.filter(S=>S.role==="user"&&S.kind==="turn").at(-1),T=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...km,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:P,...g!==o&&{ext:Js(n.h,{data:{root_id:o}})}};function b(S){return r.findIndex(O=>O.runtime_session_id===S.thread_id)}}var Rm={schema:ce,v:1},nE=Object.freeze({}),X_=new WeakMap;function pr(e){let t=X_.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=Xs({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return X_.set(e,{state:e.state,block:o}),o}var Cm=new WeakMap;function Tm(e){if(Cm.has(e))return Cm.get(e);let t={...Rm,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:ke}},messages:[{...Rm,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}=Qs({...Rm,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 Cm.set(e,r),r}function oe(e){return Tm(e)}var me=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",We=e=>me(e)?oe(e):e;function eb(e){let t=oe(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:nE}var tb=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function nb(e){return e.status==="complete"?"completed":e.status}var Z_=new WeakMap;function rb(e){if(e.status!=="complete")return"";let t=Z_.get(e);return t===void 0&&Z_.set(e,t=tb(e)),t}function sb(e){return e.status==="error"?e.result?.error?.message||tb(e):void 0}function fe(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function rE(e){return fe(e)==="bash"}function Im(e){let t=fe(e);return t==="question"||t==="ask"}function sE(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var ob=new Set(["show","show_user"]);function Em(e){return ob.has(fe(e))}function oE(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Mm(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||Zs(e))}function Zs(e){let t=me(e)?oe(e):e,n=fe(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:lr(t.state?.input)}var ib=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Om(e){return ib.has(fe(e))}var iE=50*1024*1024,jm="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",aE=new RegExp(`^kortix-attachment://(${jm})/(${jm})/(${jm})$`);function Lm(e){if(typeof e!="string")return null;let t=aE.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function cE(e){return Lm(e)!==null}var Dm=new WeakMap;async function $m(e,t,n,r={}){if(n.size>iE)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:Dm.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=Dm.get(n)??new Map;l.set(s,i),Dm.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 Um(e,t){let n=Lm(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 _("Could not load attachment",{status:s.status});return s.blob()}var lE=new Set(["show","show_user"]);function uE(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),dr=e=>typeof e=="string"&&e.length>0?e:null,ab=e=>typeof e=="string"?dr(e.split("/").pop()):null;function eo(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function pE(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 dE(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 gE(e,t){for(let n of uE(e))t(eo(n,"attachment"),eo(n,"filename")??ab(eo(n,"path")),eo(n,"mime"))}function mE(e,t){for(let n of[e,...pE(e.items)])He(n)&&t(n.attachment,ab(n.path),null)}function fE(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=He(r)&&Array.isArray(r.blocks)?dE(r):r;if(!He(s)||!He(s.info)||!Array.isArray(s.parts))continue;let o=dr(s.info.id);if(!o)continue;let i=dr(s.info.role)??"unknown",a=(l,p,d)=>{let g=Lm(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,dr(l.filename),dr(l.mime)):l.type==="text"&&typeof l.text=="string"?gE(l.text,a):l.type==="tool"&&typeof l.tool=="string"&&lE.has(fe(l.tool))&&He(l.state)&&He(l.state.input)&&mE(l.state.input,a))}return t}function yE(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 hE(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 Fm(e,t,n){return e!==void 0?e:yE(st(t),n)}var Nm={get disableMobileAdvertising(){return Fm(I().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Fm(I().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Fm(I().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var _E=new Set(["project-manager"]);function to(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Nm.enableProjects||!_E.has(e.name)}function bE(e){let t=e.agents.filter(to),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 cb(){return{projects:{list:xt,listForAccount:na,get:wt,detail:Mn,create:ia,createRepo:aa,provision:ca,update:Dn,archive:Ln,llmCatalog:On,modelPicker:jn,modelAccess:sr,setModelAccess:or,customLlmProviders:ir,setCustomLlmProvider:ar,deleteCustomLlmProvider:cr,sandboxHealth:Fn,sandboxTemplates:el,sessions:At,createSession:Rt},github:{linkRepository:fa,replaceProjectRepository:ya,getInstallation:ha,listInstallations:_a,listLinkableInstallations:ba,listRepositories:Sa,listRepositoryBranches:Pa,linkInstallation:wa,saveInstallation:xa,deleteInstallation:va,storeUserToken:ka},gitBackend:{get:Aa,repositories:Ra},connectStatus:Vc,marketplace:{items:o=>_g(o),item:o=>Pg(o),itemFile:(o,i)=>xg(o,i),marketplaces:()=>bg(),featured:()=>Sg(),sources:{list:()=>wg(),add:o=>kg(o),remove:o=>vg(o)}}}}function lb(){return{billing:{accountState:Ku,accountStateMinimal:qu,transactions:Gu,transactionsSummary:Wu,creditBreakdown:Hu,usageHistory:Vu,usageRollup:up,sessionCosts:{list:gp,get:er},tierConfigurations:zu,setPlan:ap,previewPlan:ip,acceptEnterpriseOffer:cp,contactSales:lp,checkout:{createSession:n=>Yu(n),confirmSession:(n,r)=>Ju(n,r)},subscription:{createPortalSession:(n,r)=>Qu(n,r),cancel:(n,r)=>Xu(n,r),reactivate:n=>Zu(n),scheduleDowngrade:(n,r,s)=>ep(n,r,s),cancelScheduledChange:n=>tp(n),prorationPreview:(n,r)=>np(n,r)},credits:{purchase:n=>rp(n),autoTopupSettings:n=>sp(n),configureAutoTopup:n=>op(n)}},sandboxShares:{list:Md,create:Od,revoke:jd}}}var Jt=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 Jt("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 Jt(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 no(e,t){return ie("/auth/signup",{body:e},t)}function ro(e,t){return ie("/auth/sign-in/password",{body:e},t)}function so(e,t){return ie("/auth/sign-in/magic-link",{body:e},t)}function oo(e,t){return ie("/auth/verify-otp",{body:e},t)}function io(e,t){return ie("/auth/sign-in/oauth",{body:e},t)}function ao(e,t){return ie("/auth/oauth/exchange",{body:e},t)}function Qt(e,t){return ie("/auth/refresh",{body:e},t)}function co(e,t){return ie("/auth/password/reset",{body:e},t)}function lo(e,t,n){return ie("/auth/password/update",{body:e,bearer:t},n)}function uo(e,t){return ie("/auth/user",{bearer:e},t)}function po(e,t,n){return ie("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function go(e,t){return ie("/auth/sign-in/sso",{body:e},t)}var mo={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 fo(e,t={},n){return ie("/auth/sign-out",{body:t,bearer:e},n)}function yo(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=P=>(P.expires_at??0)*1e3,g=P=>d(P)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let P of[...p])try{P(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let P=l,v=(async()=>{let T=await e.storage.get();if(P===l&&T)try{let b=JSON.parse(T);b.session?.access_token&&b.session?.refresh_token&&(r=b.session,s=b.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 P=r.refresh_token,v=l,T=Qt({refresh_token:P},e.request).then(async b=>(v!==l||(r=b.session,b.user&&(s=b.user),await m()),r)).catch(async b=>{if(v!==l)return r;let S=b&&typeof b=="object"&&"status"in b?b.status:0;if(S>=400&&S<500)return r=null,s=null,await m(),null;throw b}).finally(()=>{a===T&&(a=null)});a=T}return a}return{subscribe(P){return p.add(P),()=>{p.delete(P)}},current:()=>r,user:()=>s,load:f,async set(P,v){await f(),l+=1,a=null,r=P,v!==void 0&&(s=v),P||(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 ub(){return{list:ji,get:Li,create:Di,secretResources:{list:sc,create:oc,rotate:ic,retry:ac,remove:cc,grant:lc,revoke:uc,setAccess:pc},updateName:$i,branding:{get:Ui,update:Fi,uploadAsset:Ni,removeAsset:Bi,reset:Ki},leave:ea,members:qi,invite:Gi,removeMember:Xi,updateMemberRole:Zi,invites:Wi,cancelInvite:Hi,resendInvite:Vi,tokens:{list:Zd,create:eg,revoke:tg},connectedApps:{list:ng,revoke:rg},audit:{log:cg,export:pg,activity:lg,webhooks:{list:dg,create:gg,update:mg,remove:fg}}}}function pb(){return{assignments:{list:xd,create:wd,revoke:kd},permissions:{list:vd,forRole:cd},roles:{list:od,create:ud,update:pd,setPermissions:dd,remove:gd,usage:ld},groups:{list:Qp,get:Xp,create:Zp,update:ed,remove:td,members:{list:nd,add:rd,remove:sd}},agentIdentities:id,oauthClients:{list:yd,get:hd,create:_d,update:bd,rotateSecret:Sd,remove:Pd},can:md,canBatch:fd}}function db(){let e={signUp:no,signInWithPassword:ro,sendMagicLink:so,verifyOtp:oo,signInWithProvider:io,exchangeCode:ao,refresh:Qt,resetPassword:co,updatePassword:lo,updateUserMetadata:po,signInWithSso:go,mfa:mo,user:uo,signOut:fo,session:yo},t=ub(),n=pb();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:zi,describe:Yi,accept:ps,acceptAndLand:Ji,decline:Qi}}}var gr=new Map,Bm=new Map;function Km(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function gb(e){return gr.get(Km(e))??null}function mb(){return[...gr.values()].filter(e=>typeof e=="string")}function fb(e){return gr.has(Km(e))}async function it(e){let t=Km(e),n=gr.get(t);if(n!==void 0)return n;let r=Bm.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 gr.set(t,i),i}catch{return null}finally{Bm.delete(t)}})();return Bm.set(t,s),s}function yb(e){let{apiBaseUrl:t}=e;return fb(t)||it(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:gb(t)}}function hb(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 _(`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),yb({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function _b(e,t){let n=null;async function r(){n||(n=Vn(e,t,{showErrors:!1}).then(s=>{let o=Zn(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 Xt={url:null,sandboxId:null,dbSandboxId:null,version:0},PE=new Set;function ho(e,t=null,n=null){if(!(Xt.url===e&&Xt.sandboxId===t&&Xt.dbSandboxId===n)){Xt={url:e,sandboxId:t,dbSandboxId:n,version:Xt.version+1};for(let r of PE)r()}}function bb(){return Xt.url}var mr=new Map;function Sb(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 Tt=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 _(Sb(i),{code:"RUNTIME_UNAVAILABLE"});let l=i.sandbox.external_id;if(!l)throw new _("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Ie(l);return ho(p,l),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:l}}return n}function xb(e,t,n){let r=null;function s(){if(r)return r;let p=y_(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?Ou(p.session):null,h=f?.sandbox?.external_id,P=f?.runtime_session_id;if(h&&P){let S=Ie(h);return ho(S,h),r={runtimeSessionId:P,opencodeSessionId:P,runtimeUrl:S,sandboxId:h},Is(e,t,r),await m,r}let v=`${e}
15
+ ${t}`,T=mr.get(v);if(T)return r=await T,await m,r;let b=o(g);mr.set(v,b);try{return r=await b,await m,r}finally{mr.get(v)===b&&mr.delete(v)}}function a(p){let d=s();if(!d)throw new Tt(p);return d}function l(){r=null,h_(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:l}}var G=["directory","workspace"],wb=["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}),xE={"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,wb),"session.promptAsync":E("POST","/session/{sessionID}/prompt_async",G,wb),"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 wE(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 kE(e,t,n={},r={}){let s=xE[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}${wE(s,n)}`,{method:s.method,headers:l,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function vE(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 AE(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=vE(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 qm(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 P=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(P)||(m.retry=P)}f.length&&(m.data=f.join(`
21
- `)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*xE(e,t,n){let r=e.eventTransport??Bm(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 mr(e){let t=s=>(o,i)=>PE(e,bE(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:xE(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 xb=200;async function wE(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function at(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new _(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function wb(e){let t=e.runtimeUrl.replace(/\/$/,""),n=mr({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=P=>e.fetch(new Request(`${t}${P}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new _(`Reading the session transcript failed: ${await wE(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,xb),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,xb),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 l=await n.global.config.get().then(g=>g.error===void 0?g.data:null),p=typeof l?.model=="string"?l.model:"",d=p.indexOf("/");d>0&&d<p.length-1&&(s={providerID:p.slice(0,d),modelID:p.slice(d+1)})}if(!s)throw new _("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 _("This session is busy. Wait for the current turn to finish, then run compact again.",{code:"SESSION_BUSY",status:409});let a=await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID});if(a.error&&typeof a.error=="object"&&"code"in a.error&&a.error.code==="LONG_TURN_PROXY_TIMEOUT")throw new _("Compaction has not finished. Check the session status before trying again.",{code:"LONG_TURN_PROXY_TIMEOUT",status:a.response?.status});return at(a,"Compacting the session failed"),s}}}function vb(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return wb({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 kb(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await yu(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Xt=BigInt(4096),Ve=BigInt(0xffffffffffff),Ab=Ve+BigInt(1),vE=Ab/BigInt(2),ct=BigInt(3600*1e3)*Xt,_o=120*1e3,Rb=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,kE=/^msg_([0-9a-f]{12})/,Cb="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Tt(e){let t=kE.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>=vE&&(n-=Ab),n}function Km(e){let t=null;for(let n of e)n!=null&&(t===null||It(n,t)>BigInt(0))&&(t=n);return t}function Tb(e,t){let n=Tt(e);return n===null?!1:It(n,Zt(t))>ct}function Ib(e,t){let n=t===void 0?null:Zt(t);return Eb(e,r=>n===null||It(r,n)<=ct)}function Eb(e,t){let n=[];for(let r of e){let s=Tt(r);s!==null&&t(s)&&n.push(s)}return Km(n)}function AE(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Cb[n%62])}return e}function qm(e){let t=e.random,n=Zt(e.nowMs-(e.backdateMs??_o)),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+=Cb[Math.min(61,Math.floor(t()*62))];else s=AE();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function bo(e={}){let t=e.nowMs??Date.now(),n=Zt(t-_o),r=Eb(e.after??[],s=>{let o=It(s,n);return o>=BigInt(0)&&o<=ct});return qm({nowMs:t,newestKnownTime:r}).id}function Mb(e){return{scope:()=>mu(e.projectId,e.sessionId),providerSecretPool:{list:()=>dc(e.projectId,e.sessionId),get:t=>pc(e.projectId,e.sessionId,t),set:(t,n)=>gc(e.projectId,e.sessionId,t,n)},rescope:t=>fu(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=bo(),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 _("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var Ob=async function*(e){let t=I().eventStreamTransport;if(!t){yield*Bm(((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=hb();return e||(I().billingEnabled??!1?"":y_())}async function Gm(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Wm(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function Hm(e){let t=Wm(e),n=await $(`${t}/env`);if(!n.ok)throw new Error(await Gm(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Vm(e,t,n){let r=Wm(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 Gm(s,"Failed to save secret"))}async function zm(e,t){let n=Wm(e),r=await $(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Gm(r,"Failed to delete secret"))}var jb={list:Hm,set:Vm,delete:zm};async function Db(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 So(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function fr(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return le(e)}async function Jm(e){let t=fr(e),n=await $(`${t}/kortix/pty`);if(!n.ok)throw new Error(await So(n,"Failed to list terminals"));return n.json()}async function Qm(e,t){let n=fr(e),r=await $(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await So(r,"Failed to create terminal"));return r.json()}async function Xm(e,t,n){let r=fr(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 So(s,"Failed to update terminal"));return s.json()}async function Zm(e,t){let n=fr(e),r=await $(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await So(r,"Failed to remove terminal"))}async function ef(e,t,n){let r=fr(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 Lb(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",$b="\x07",RE="\0",Ym=`(?:${$b}|${lt}\\\\)`,CE=[new RegExp(`${lt}\\]697;[^${$b}${lt}]*${Ym}`,"g"),new RegExp(`${RE}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${lt}\\][0-9]+;rgb:[0-9a-fA-F/]+${Ym}`,"g"),new RegExp(`${lt}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Ym}`,"g"),new RegExp(`${lt}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${lt}\\[\\d+;\\d+R`,"g"),new RegExp(`${lt}\\[\\?[0-9;]*c`,"g")];function Ub(e){let t=e;for(let n of CE)t=t.replace(n,"");return t}var Fb={list:Jm,create:Qm,update:Xm,remove:Zm,webSocketUrl:ef};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 TE(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 IE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function EE(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 OE(e,t){return M(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function jE(e,t,n){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function DE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function LE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function $E(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function UE(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return M(e,`/kortix/tickets${n}`)}async function FE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function NE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function BE(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 qE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function GE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function WE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function HE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function VE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function zE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function YE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function JE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function QE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function XE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function ZE(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function eM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function tM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function nM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function rM(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function sM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function oM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function iM(e,t,n=200){return M(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function aM(e){return M(e,"/kortix/projects")}async function cM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function lM(e,t){return M(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function uM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function pM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function dM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function gM(e,t,n="all"){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function mM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function fM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function yM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function hM(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function _M(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function bM(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 PM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function xM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function wM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function vM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function kM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var AM=1e4,RM={retryOnAuthError:!1};function en(e,t,n){return M(e,t,{signal:AbortSignal.timeout(AM),...n},RM)}async function CM(e,t=!1){return(await en(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function TM(e){return(await en(e,"/kortix/services/templates")).templates??[]}async function IM(e,t){return(await en(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function EM(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 OM(e,t){return en(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Ye=new Map,jM=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(!ts())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=mr({baseUrl:e,fetch:$,eventTransport:Ob});return Ye.set(e,n),Ye.size>jM&&Ye.delete(Ye.keys().next().value),n}function DM(e){Ye.delete(e)}function LM(){Ye.clear()}var Po=new Map;function $M(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=Po.get(e);if(t)return t;let n=mr({baseUrl:e,fetch});return Po.set(e,n),n}function UM(e){Po.delete(e)}function FM(){Po.clear()}async function NM(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 BM(e){let t=ze();if(!t)throw new _("[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 _(`System reload failed (${r.status}): ${await NM(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new _(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(l){throw new _(`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 Nb="frontend";function xo(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Nb}] ${t}`,...n?[n]:[]);try{ut().app.log({service:Nb,level:e,message:t,extra:n})}catch{}}var Je={debug:(e,t)=>xo("debug",e,t),info:(e,t)=>xo("info",e,t),warn:(e,t)=>xo("warn",e,t),error:(e,t)=>xo("error",e,t)};var KM=16,qM=8,Bb=6e4,GM=250,WM=1e3,HM=3e4,VM=5,zM=.5,YM=3e3,JM=3e4,Kb=2e4,QM=2e3,qb=8;function XM(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function ZM(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 Gb(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=ZM(n[n.length-1]?.event,l);if(p)n[n.length-1]={type:p.type,event:p};else{let d=XM(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 Wb(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 tf(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 eO(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:YM,sseMaxRetryDelay:JM,sseMaxRetryAttempts:1}).then(l=>{i||(i=!0,t.clearTimeout(a),s(l))},l=>{i||(i=!0,t.clearTimeout(a),o(l))})})}async function tO(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=Wb(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<qM)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return o}function Hb(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<QM)}function Vb(e,t,n){Je.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),tf(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function zb(e,t,n){let r=t?GM:Math.min(WM*2**Math.min(e-1,VM),HM);return Math.round(r*(1+zM*(n.random?.()??0)))}function Yb(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 Jb(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 P=Wb(o);P.promise.then(()=>h.abort());try{let{stream:k}=await eO(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 tO(k,n,h.signal,p,()=>{a("open"),T()}),g=d}catch(k){if(f=k,o.aborted)return{streamHadWork:d,stableConnection:g,error:f};let T=String(k),b=Dt(k)||Dt(k?.cause);if(Je.error("SSE event stream error",{error:T,retryCount:i,isAuthError:b}),b)try{fs(),await ms(),Je.info("SSE: refreshed auth token after auth error")}catch(S){Je.error("SSE: failed to refresh auth token",{error:String(S)})}}finally{n.clearTimeout(m),h.abort(),P.cleanup(),p.flush()}return{streamHadWork:d,stableConnection:g,error:f}}function Qb(e){return{type:"heartbeat-gap",gapMs:e}}function Xb(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 nO={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},rO=5e3,sO=1e4,oO=4,yr=new WeakMap;function iO(e,t,n){let r=t.timers??nO,s=t.connectTimeoutMs??Kb,o=t.heartbeatTimeoutMs??Bb,i=t.maxConsecutiveHardFailures??qb,a=new AbortController,l=(k,...T)=>tf(n,k,...T),p=null,d=!1,g=k=>{p!==k&&(p=k,k&&l(T=>T.onConnectionChange,k))},m=r.now(),f=null,h=Gb(r,k=>{m=r.now(),l(T=>T.onEvent,k)}),P={client:e,t:r,connectTimeoutMs:s,heartbeatTimeoutMs:o,outerSignal:a.signal,setConnectionState:g,onConnected:()=>{if(f){let k=r.now()-f.lastActivityAt,T=f.eventful;f=null,(T||k>rO)&&l(b=>b.onGapRehydrate,k)}m=r.now()},coalescer:h};return(async()=>{let k=0,T=0,b=0;for(;!a.signal.aborted;){let S=r.now(),O=await Jb({...P,retryCount:k});if(a.signal.aborted)break;let y=O.error,{streamHadWork:w,stableConnection:x}=O,v=r.now()-S;if(T=Hb(w,y,v)?T+1:0,T>=i){Vb(n,T,y),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||w},b=x&&v<sO?b+1:0;let R=x&&b<=oO;R?k=0:(k++,k>1&&Je.warn("SSE event stream reconnecting",{retryCount:k})),await Yb(r,a.signal,zb(k,R,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),h.clearTimer()}}}function wo(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=yr.get(i);if(l?.isParked()&&(yr.delete(i),l=void 0),!l)l=iO(i,e,new Set([a])),yr.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(),yr.get(i)===p&&yr.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function Zb(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 wo({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function tS(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new _(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function sf(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 br(e,t){let n=await $(`${ue(t)}${e}`);if(!n.ok)throw new _(await sf(n),{status:n.status,response:n});return n.json()}async function of(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 _(`${r} failed (${o.status}): ${await sf(o)}`,{status:o.status,response:o});return o.json()}var ko=["/workspace","/tmp","/home","/opt"],aO=ko.filter(e=>e!=="/workspace");function af(e){return ko.some(t=>e===t||e.startsWith(`${t}/`))}function sn(e){return af(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(aO.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var cf=pt;async function on(e,t){let n=ue(t),r=pt(e)||".";return(await br(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function an(e,t){let n=pt(e);return br(`/file/content?path=${encodeURIComponent(n)}`,t)}async function cO(e,t,n){let r=ue(n),s=pt(e),o=await $(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new _(await sf(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new _("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var lO=8,vo=0,nS=[];async function uO(){if(vo<lO){vo++;return}await new Promise(e=>nS.push(e)),vo++}function pO(){vo--,nS.shift()?.()}function rS(e,t){let n=ue(t);return Un(`${n}/file/raw?path=${encodeURIComponent(pt(e))}`)}async function cn(e,t){await uO();try{let n=ue(t);try{return await cO(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{pO()}}async function Sr(e){return br("/file/status",ue(e))}async function Pr(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)),br(`/find/file?${s.toString()}`,r)}async function xr(e,t){let n=ue(t);return(await br(`/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 hr=[400,1200],dO=e=>e===408||e===429||e===502||e===503||e===504,eS=e=>new Promise(t=>setTimeout(t,e));function gO(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var nf=3e4,sS=15*6e4,mO=256;function nn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return nf;let t=nf+e/mO;return Math.min(sS,Math.max(nf,Math.round(t)))}async function fO(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 _r(e,t){let n;for(let s=0;s<=hr.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,gO(a)||s===hr.length)break;await eS(hr[s]);continue}if(o.ok)return o.json();let i=await fO(o);if(n=new _(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!dO(o.status)||s===hr.length)throw n;await eS(hr[s])}if(n instanceof _)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new _(`Upload failed: ${r}`)}var rf=8*1024*1024;function yO(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new _(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function oS(e,t){try{e?.onProgress?.(t)}catch{}}function iS(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 hO(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<=rf){let d=await _r(()=>iS(e,t,p),g=>$(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:l}));return yO(d[0],e.size),oS(i,{loadedBytes:e.size,totalBytes:e.size}),d}return _O(e,t,p,a,i)}async function _O(e,t,n,r,s){let i=(await _r(()=>iS(new Blob([],{type:e.type}),t,n),l=>$(`${r}/file/upload`,{method:"POST",body:l},{timeoutMs:nn(0)})))[0]?.path;if(!i)throw new _("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=hO(i);if(!a.name)throw new _(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let l=0;l<e.size;l+=rf){let p=Math.min(e.size,l+rf),d=e.slice(l,p,e.type),g=await _r(()=>{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 _(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});oS(s,{loadedBytes:p,totalBytes:e.size})}}catch(l){throw await Et(i,r).catch(()=>{}),l}return[{path:i,size:e.size}]}function aS(e,t,n){let r=ue(n);return _r(()=>{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:bO}))}var bO=sS;function SO(e,t,n){let r=ue(n),s=nn(t.size);return _r(()=>{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 _{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 wr(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(cS(l),n)}catch(g){if(!(g instanceof _&&g.status===404))throw g}if(p.some(g=>g.name===lS(l)))throw new rn(l);let d=await uS(l,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function vr(e,t,n){let r=ue(n);return SO(t,await cn(e,r),r)}function PO(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function cS(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function lS(e){return e.slice(e.lastIndexOf("/")+1)}function xO(){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(PO(e.trim()));return uS(s,t,r,{overwrite:!0})}async function uS(e,t,n,r){let s=lS(e);if(!s)throw new _(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=cS(e);await un(o,n).catch(()=>{});let i=xO(),a=await ln(t,o,`.${s}.kortix-write-${i}`,n),l=a[0]?.path;if(!l)throw new _(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=sn(l);try{await pS(p,e,n,r.overwrite)}catch(g){throw await Et(p,n).catch(()=>{}),!r.overwrite&&g instanceof _&&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 of("/file","DELETE",{path:e},"Delete",t)}async function un(e,t){return of("/file/mkdir","POST",{path:e},"Mkdir",t)}async function Ar(e,t,n){return pS(e,t,ue(n),!0)}async function pS(e,t,n,r){return of("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function lf(){return tS(await ut().project.current())}async function Ao(){return tS(await ut().global.health())}async function uf(){try{return(await Ao()).healthy===!0}catch{return!1}}var dS={list:on,read:an,readBlob:cn,status:Sr,findFiles:Pr,findText:xr,upload:ln,write:kr,create:wr,copy:vr,remove:Et,mkdir:un,rename:Ar,currentProject:lf,health:Ao,isReachable:uf,toDaemonPath:pt,toSandboxAbsolutePath:sn,toWorkspaceRelative:cf};function gS(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()=>Sr((await e()).runtimeUrl),findFiles:async(t,n)=>Pr(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=>wr(t,(await e()).runtimeUrl),copy:async(t,n)=>vr(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)=>Ar(t,n,(await e()).runtimeUrl)}}function mS(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=>au(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),cu(e.projectId,e.sessionId)),restore:()=>uu(e.projectId,e.sessionId),recover:()=>lu(e.projectId,e.sessionId),start:(...t)=>nt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Mu(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Yn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Jn(e.projectId,e.sessionId)),configState:()=>pu(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),du(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),gu(e.projectId,e.sessionId,...t)),setSharing:t=>Nl(e.projectId,e.sessionId,t),previews:()=>Hl(e.projectId,e.sessionId),participants:()=>Bl(e.projectId,e.sessionId),watch:()=>Kl(e.projectId,e.sessionId),setWatch:t=>ql(e.projectId,e.sessionId,t),setPinned:t=>Gl(e.projectId,e.sessionId,t),setArchived:t=>Wl(e.projectId,e.sessionId,t),commit:t=>Ml(e.projectId,e.sessionId,t),publicShares:{list:()=>Vl(e.projectId,e.sessionId),create:(...t)=>zl(e.projectId,e.sessionId,...t),revoke:(...t)=>Yl(e.projectId,e.sessionId,...t)}}}function fS(e){return{reminders:{list:()=>Od(e.projectId,e.sessionId),create:t=>jd(e.projectId,e.sessionId,t),update:(t,n)=>$s(e.projectId,e.sessionId,t,n),remove:t=>Us(e.projectId,e.sessionId,t),run:t=>Dd(e.projectId,e.sessionId,t)},audit:(t,n)=>Xl(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Dm(e.projectId,e.sessionId,t,n),read:(t,n)=>Lm(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Zl(e.projectId,e.sessionId,t),messageAuthors:()=>hu(e.projectId,e.sessionId),modelUsage:()=>_u(e.projectId,e.sessionId),transcriptSync:t=>Hn(e.projectId,e.sessionId,t),log:t=>eu(e.projectId,e.sessionId,t),turn:()=>Vn(e.projectId,e.sessionId),prompts:{create:t=>zn(e.projectId,e.sessionId,t),list:()=>tu(e.projectId,e.sessionId),remove:t=>nu(e.projectId,e.sessionId,t),retry:t=>ou(e.projectId,e.sessionId,t),edit:(t,n)=>ru(e.projectId,e.sessionId,t,n),interrupt:t=>su(e.projectId,e.sessionId,t),hold:t=>iu(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function yS(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var vO=["control_plane","provider_ingress","daemon","upstream_port"];function pf(e){return typeof e=="string"&&vO.includes(e)?e:null}function df(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 gf(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=pf(r.headers.get("X-Kortix-Proxy-Hop"))??pf(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 hS=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,_S=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,bS=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,SS=new Set([22,4096,parseInt(Ke.KORTIX_MASTER,10)]);function kO(e){return _S.test(e)}function Ro(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 AO(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var RO=new Set(["'",'"',"`","<","(","["]),CO=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function TO(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&&RO.has(e[t]);)t++;for(;n>t&&CO.has(e[n-1]);)n--;return e.slice(t,n)}function IO(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var EO=/^\/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 PS(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 Cr(e){if(!e)return null;let t=TO(AO(e.trim())),n=ff(t);if(n){let r=Ro(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(EO);if(l){let p=parseInt(l[1],10);if(p>=1&&p<=65535)return s=p,o=Ro(`${l[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=Ro(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=IO(e);return r&&r!==e?Cr(r):null}}function OO(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 jO(e,t){return t.some(([n,r])=>e>=n&&e<r)}function xS(e){let t=[],n=new Set,r=OO(e);hS.lastIndex=0;let s;for(;(s=hS.exec(e))!==null;){let o=Cr(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:l}=o;a<1||a>65535||SS.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:jO(s.index,r)}))}return t}function DO(e){return xS(e).length>0}function LO(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function wS(e){return e.trim().toLowerCase().split("_").join("-")}function vS(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function $O(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(wS(n.sandboxId));return`${vS(s)}${t}`}function kS(e){return e.sandboxId.trim().length>0}function dt(e,t,n){let r=Ro(t);if(!kS(n))return TS(e,r);let s=$O(e,r,n);return s||(LO(n.apiBaseUrl)?`http://p${e}-${wS(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${vS(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function UO(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 AS(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function FO(e){return`http://localhost:3211${AS(e)}`}function RS(){return"/health"}function NO(e){return dt(3211,RS(),e)}function BO(e,t){return dt(e,"/",t)}function CS(e){let t=Cr(e);return!(!t||SS.has(t.port)||PS(e))}function mf(e,t){if(!e)return e;let n=Cr(e);return n?CS(n.originalUrl)?dt(n.port,n.path,t):n.originalUrl:e}function TS(e,t="/"){return`http://localhost:${e}${t}`}var IS=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function ff(e){let t=e.match(_S);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(bS);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(IS);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=ff(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function qO(e){return kO(e)||bS.test(e)||IS.test(e)}function GO(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Rr="/web-proxy/";function WO(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Rr}${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 HO(e){try{let t=new URL(e),n=t.pathname.indexOf(Rr);if(n===-1)return null;let s=t.pathname.slice(n+Rr.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 VO(e){try{return new URL(e).pathname.includes(Rr)}catch{return e.includes(Rr)}}function zO(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 YO(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 ES(e){return{health:t=>gf(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>dt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>mf(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ie(e.requireReady("sandboxPortUrl").sandboxId,t)}}function yf(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=yb(e,t),{ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g}=Sb(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{...mS(m),...fS(m),...ES(m),...kb(m),...Mb(m),...Zb(m),files:gS(l),...vb(m),get runtime(){return Me(d("runtime").runtimeUrl)}}}function MS(e){return{apps:{list:()=>vg(e),create:t=>kg(e,t),get:t=>Fs(e,t),update:(...t)=>Ag(e,...t),access:{get:(...t)=>Ig(e,...t),update:(...t)=>Mg(e,...t),session:(...t)=>Og(e,...t),agents:t=>Eg(e,t)},remove:t=>Rg(e,t),token:t=>Cg(e,t),authEnv:t=>Tg(e,t),artifacts:{register:t=>Ns(e,t),uploadArchive:(...t)=>jg(e,...t),finalize:(...t)=>Bs(e,...t)},deployments:{create:(...t)=>Dg(e,...t),list:t=>Lg(e,t),get:(...t)=>$g(e,...t),logs:(...t)=>Ug(e,...t),remove:(...t)=>Bg(e,...t)},start:t=>Fg(e,t),stop:t=>Ng(e,t),rollback:(...t)=>Kg(e,...t),machines:{list:t=>qg(e,t),start:(t,n)=>Wg(e,t,n),stop:(t,n)=>Hg(e,t,n),restart:(t,n)=>Vg(e,t,n),destroy:(t,n)=>zg(e,t,n)},scale:(...t)=>Yg(e,...t),exec:(...t)=>Jg(e,...t),volumes:{list:t=>Qg(e,t),create:(...t)=>Xg(e,...t),update:(...t)=>Zg(e,...t),destroy:(...t)=>em(e,...t),snapshots:(...t)=>tm(e,...t),snapshot:(...t)=>nm(e,...t),restore:(...t)=>rm(e,...t),fork:(...t)=>sm(e,...t)}}}}function OS(e){return{list:()=>Ia(e),invite:(...t)=>Oa(e,...t),update:(...t)=>Ea(e,...t),revoke:t=>Ma(e,t),pendingInvites:()=>ja(e),resendInvite:(...t)=>La(e,...t),revokeInvite:(...t)=>Da(e,...t),requests:()=>Ra(e),approveRequest:(...t)=>Ca(e,...t),rejectRequest:(...t)=>Ta(e,...t),groupGrants:()=>$a(e),attachGroupGrant:(...t)=>Ua(e,...t),updateGroupGrant:(...t)=>Fa(e,...t),detachGroupGrant:t=>Na(e,t),resourceGrants:{list:()=>Ba(e),create:t=>Ka(e,t),remove:t=>qa(e,t)}}}function jS(e){return{tokens:{list:()=>ng(e),create:t=>rg(e,t),revoke:t=>sg(e,t)},setupLinks:{requestSecret:t=>mg(e,t),requestConnector:t=>fg(e,t)},validateManifest:t=>ra(e,t),gitToken:()=>sa(e),agentIdentities:()=>od(e),secrets:{list:()=>Va(e),upsert:t=>za(e,t),setStrategy:(...t)=>Ya(e,...t),broker:(...t)=>Ja(e,...t),remove:t=>Dn(e,t),setPersonal:(...t)=>ec(e,...t),removePersonal:t=>tc(e,t),setGitCredential:t=>Za(e,t),listProviderOAuth:()=>Qa(e),startProviderOAuth:(...t)=>ds(e,...t),pollProviderOAuth:(...t)=>gs(e,...t),removeProviderOAuth:t=>Xa(e,t)},access:OS(e)}}function DS(e){return{list:()=>fc(e),listAll:()=>yc(e),reconcile:(...t)=>hc(e,...t),reconcileMember:(...t)=>_c(e,...t),updateCredential:(...t)=>bc(e,...t),revoke:(...t)=>Sc(e,...t),activate:(...t)=>Pc(e,...t),setDefault:(...t)=>xc(e,...t),rename:(...t)=>wc(e,...t),share:(...t)=>kc(e,...t),addComputer:(...t)=>vc(e,...t),pipedreamConnect:(...t)=>Ac(e,...t),pipedreamFinalize:(...t)=>Rc(e,...t)}}function Co(e){return{catalog:t=>Nt(e,t),tools:()=>hs(e),search:(...t)=>mc(e,...t),describe:(...t)=>_s(e,...t),call:(...t)=>vt(e,...t),callAction:(t,n,r,s)=>vt(e,`${t}.${n}`,r,s),accounts:(...t)=>bs(e,...t),uploadAttachment:(...t)=>Ss(e,...t)}}function hf(e,t){return{slug:t,run:(r,s,o)=>ks(e,t,r,s,o),call:(r,s,o)=>vt(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?_s(e,`${t}.${r}`):(await Nt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>bs(e,t),paginate:(r,s,o)=>Jc(e,t,r,s,o),uploadAttachment:(r,s)=>Ss(e,r,{...s,connector:t})}}var JO=100,LS=0,QO=new Set(["attachment_size_mismatch","attachment_failed"]),$S=()=>new _("Attachment expired. Attach the file again.",{code:"attachment_expired"});function _f(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 XO(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+JO-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 bf(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,v)=>x!==p.attachments[v]))&&(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:$S()});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(v=>!Number.isSafeInteger(v)||v<=0||v>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(w.reduce((v,C)=>v+C.item.size,0)+y.reduce((v,C)=>v+C,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function P(y,w,x){let v=++y.generation,C=new AbortController;y.abort=C,y.item={...y.item,status:"uploading",error:void 0};let D=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===v,R=XO(y,D,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=>{D()&&(y.item={...y.item,status:"ready",attachment:_f(L),receivedBytes:L.size})}).catch(L=>{L instanceof _&&QO.has(L.code??"")&&(y.upload=void 0),D()&&(y.item={...y.item,status:L instanceof _&&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 k(){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++,P(y,w,()=>{i--,m(),k()})}m()}function T(y){h(y.map(x=>x.size));let w=y.map(x=>{let v=`attachment-${++LS}`;return r.set(v,{generation:0,item:{id:v,file:x,filename:x.name,mime:x.type||"application/octet-stream",size:x.size,status:"pending",receivedBytes:0}}),v});return m(),k(),w}function b(y){let w=y.map(({attachment:v,file:C})=>{try{return{attachment:_f(v),file:C}}catch{return}});h(w.flatMap(v=>v?[v.attachment.size]:[]));let x=w.map(v=>{if(!v)return;let C=`attachment-${++LS}`,{attachment:D,file:R}=v;return r.set(C,{generation:0,item:{id:C,...R?{file:R}:{},filename:D.filename,mime:D.mime,size:D.size,status:"ready",receivedBytes:D.size,attachment:D}}),C});return m(),x}function S(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((v,C)=>{let D=()=>{o.delete(pe),w?.removeEventListener("abort",L)},R=j=>{D(),C(j)},L=()=>R(Ae()),pe=()=>{let j=!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"&&(j=!0)}if(j)return;let q;try{q=x.map(W=>{let K=_f(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)))}D(),v(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:b,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 $S();w.item={...w.item,status:"pending",error:void 0},k()}},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(),k(),x&&g(w,x)},abort:S,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(),k()},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 US(e){return{attachments:{upload:(...t)=>Bn(e,...t),delete:(...t)=>Bt(e,...t),createController:t=>bf(e,t)},get:t=>wt(e,t),detail:()=>In(e),skills:{remove:(...t)=>ga(e,...t),create:(...t)=>da(e,...t)},audit:t=>cg(e,t),update:t=>On(e,t),archive:()=>jn(e),llmCatalog:()=>En(e),modelPicker:()=>Mn(e),modelAccess:()=>rr(e),setModelAccess:t=>sr(e,t),customLlmProviders:()=>or(e),setCustomLlmProvider:(t,n)=>ir(e,t,n),deleteCustomLlmProvider:t=>ar(e,t),sandboxHealth:()=>$n(e),onboardingComplete:(...t)=>pa(e,...t)}}function FS(e){return{sessions:{list:t=>At(e,t),listPage:t=>Fl(e,t),create:t=>Rt(e,t),ensureWarm:()=>Jl(e),claimWarm:t=>Ql(e,t)},review:{list:t=>vd(e,t),summary:()=>kd(e),get:t=>Ad(e,t),submit:t=>Rd(e,t),act:(...t)=>Cd(e,...t),bulkAct:t=>Td(e,t)},approvals:{list:t=>Ga(e,t),resolve:(...t)=>Ha(e,...t),sessionsNeedingInput:t=>Wa(e,t)}}}function NS(e){return{files:{write:t=>ml(e,t),list:t=>cl(e,t),listDirectory:t=>ll(e,t),read:(t,n)=>pl(e,t,n),search:(...t)=>ul(e,...t),archive:(...t)=>dl(e,...t),archiveRequest:(...t)=>gl(e,...t),history:(...t)=>Pl(e,...t)},git:{commits:()=>_l(e),commit:t=>bl(e,t),commitDiff:t=>Sl(e,t),branches:()=>hl(e),versionDiff:(...t)=>xl(e,...t),inviteCollaborator:(...t)=>na(e,...t)},changeRequests:{list:(...t)=>wl(e,...t),get:t=>vl(e,t),update:(...t)=>Ol(e,...t),diff:t=>kl(e,t),mergePreview:t=>Al(e,t),open:(...t)=>Rl(e,...t),merge:(...t)=>Cl(e,...t),close:(...t)=>Tl(e,...t),reopen:(...t)=>Il(e,...t),requestChanges:(...t)=>El(e,...t)},...FS(e)}}function BS(e){return{policies:{list:()=>Qc(e),set:(...t)=>Xc(e,...t)},reminders:{list:()=>er(e),updateMany:(...t)=>Ld(e,...t),removeMany:(...t)=>$d(e,...t)},rooms:{list:(...t)=>Fd(e,...t),create:(...t)=>Nd(e,...t),get:(...t)=>Bd(e,...t),update:(...t)=>Kd(e,...t),messages:(...t)=>qd(e,...t),post:(...t)=>Gd(e,...t),markRead:(...t)=>Wd(e,...t),addSession:(...t)=>Hd(e,...t),removeSession:(...t)=>Vd(e,...t),addPerson:(...t)=>zd(e,...t),removePerson:(...t)=>Yd(e,...t),people:(...t)=>Jd(e,...t)},triggers:{list:()=>bu(e),eventApps:()=>Tu(e),eventTypes:(...t)=>Cu(e,...t),create:(...t)=>Su(e,...t),update:(...t)=>Pu(e,...t),remove:(...t)=>xu(e,...t),fire:((t,n)=>vu(e,t,n)),runs:(...t)=>ku(e,...t),projectRuns:(...t)=>Au(e,...t),replay:(...t)=>Ru(e,...t),setActivation:(...t)=>wu(e,...t)},...NS(e)}}function KS(e,t){return{connectors:{...Co(e),list:()=>Cc(e),config:(...n)=>Dc(e,...n),create:(...n)=>Uc(e,...n),remove:(...n)=>Kc(e,...n),sync:()=>Tc(e),auth:{discover:(...n)=>Fc(e,...n)},setName:(...n)=>Lc(e,...n),setCredentialMode:(...n)=>Ic(e,...n),setAuthorizationStrategy:(...n)=>Ec(e,...n),setCredential:(...n)=>Vc(e,...n),deleteCredential:(...n)=>zc(e,...n),setSensitive:(...n)=>Mc(e,...n),connections:t,policies:{get:(...n)=>Oc(e,...n),set:(...n)=>jc(e,...n)},listMoves:()=>Nc(e),move:(...n)=>Bc(e,...n),pipedream:{listApps:(...n)=>qc(e,...n),listSections:(...n)=>Gc(e,...n),connect:(...n)=>$c(e,...n),finalize:(...n)=>Yc(e,...n)},discover:{list:(...n)=>Ps(e,...n),sections:(...n)=>Wc(e,...n),detail:(...n)=>xs(e,...n)}},...BS(e)}}function qS(e){return{gateway:{logs:t=>Ep(e,t),log:t=>Mp(e,t),overview:t=>Op(e,t),series:t=>jp(e,t),breakdown:t=>Dp(e,t),sessions:t=>Lp(e,t),errors:t=>$p(e,t),budgets:()=>Up(e),setBudget:t=>Fp(e,t),deleteBudget:t=>Np(e,t),keys:()=>Bp(e),createKey:t=>Kp(e,t),revokeKey:t=>qp(e,t),routing:{get:()=>Rp(e),set:t=>Cp(e,t),reset:()=>Tp(e),preview:t=>Ip(e,t)},playground:(t,n,r)=>Gp(e,t,n,r)}}}function GS(e){return{modelDefaults:{get:()=>Ou(e),set:t=>ju(e,t),clear:t=>Du(e,t)},setDefaultAgent:t=>Uu(e,t),sandbox:{list:()=>al(e),snapshots:()=>el(e),rebuildSnapshot:t=>tl(e,t),fixWithAgent:()=>nl(e),createTemplate:t=>rl(e,t),updateTemplate:(...t)=>sl(e,...t),removeTemplate:t=>ol(e,t),buildTemplate:t=>il(e,t),setProvider:t=>ua(e,t)},setAgentScope:(...t)=>Lu(e,...t)}}function WS(e){return{channels:{slack:{installation:()=>dp(e),connect:t=>gp(e,t),mode:()=>mp(e),completeInstall:t=>fp(e,t),manifest:()=>hp(e),disconnect:()=>_p(e),getFile:t=>bp(e,t),uploadFile:t=>Sp(e,t)},teams:{completeInstall:t=>yp(e,t)},email:{installation:t=>xp(e,t),mode:()=>wp(e),connect:t=>vp(e,t),disconnect:t=>kp(e,t),updatePolicy:(...t)=>Ap(e,...t)}},updateFeatureFlag:(...t)=>ca(e,...t),updateExperimentalFeature:(...t)=>la(e,...t),...GS(e)}}var ZO=["screen","actions","audio"],ej=["password_managers","messaging","banking"],tj={localHours:8760,remoteDays:3650},nj=[500,1e3,2e3,5e3,1e4],rj=[720,1080,1440,2160],sj={intervalMs:2e3,maxHeight:1440},oj=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function ij(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(/\.$/,""),oj.test(n)?n:null}function aj(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 cj(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 HS=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}),Sf=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function Pf(e,t={}){return u(await c.get(`${Y(e)}/devices${Qe({user_id:t.userId,scope:t.scope})}`))}async function xf(e,t){return u(await c.delete(`${Y(e)}/devices/${t}`))}async function wf(e,t,n){return u(await c.put(`${Y(e)}/devices/${t}/link`,{user_id:n}))}async function vf(e){return u(await c.get(`${Y(e)}/enrollment-tokens`))}async function kf(e,t){return u(await c.post(`${Y(e)}/enrollment-tokens`,t))}async function Af(e,t){return u(await c.delete(`${Y(e)}/enrollment-tokens/${t}`))}async function Rf(e,t={}){return u(await c.get(`${Y(e)}/enrollments${Qe({status:t.status})}`))}async function Cf(e,t,n){return u(await c.post(`${Y(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function Tf(e,t){return u(await c.post(`${Y(e)}/enrollments/${t}/deny`,{}))}async function If(e){return u(await c.get(`${Y(e)}/policy`))}async function Ef(e,t){return u(await c.put(`${Y(e)}/policy`,{policy:t}))}async function Mf(e){return u(await c.get(`${Y(e)}/storage`))}async function Of(e,t){return u(await c.put(`${Y(e)}/storage`,t))}async function jf(e,t={}){return u(await c.get(`${Y(e)}/timeline${Qe(Sf(t))}`))}async function Df(e,t={}){return u(await c.get(`${Y(e)}/timeline/items${Qe(Sf(t))}`))}async function Lf(e,t={}){return u(await c.get(`${Y(e)}/days${Qe({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function $f(e,t){return u(await c.get(`${Y(e)}/search${HS(t)}`))}async function Uf(e,t,n={}){return u(await c.get(`${Y(e)}/frames/${t}${Qe({user_id:n.userId,device_id:n.deviceId})}`))}async function Ff(e,t,n={}){return u(await c.get(`${Y(e)}/chunks/${t}/media${Qe({user_id:n.userId,device_id:n.deviceId})}`))}async function Nf(e,t,n){return u(await c.get(`${Y(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function Bf(e){return u(await c.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function Kf(e,t){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function qf(e){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function Gf(e){return u(await c.get(Y(e)))}async function Wf(e,t){return u(await c.patch(Y(e),{enabled:t}))}async function Hf(e){return u(await c.get(`/capture/me/search${HS(e)}`))}async function Vf(e={}){return u(await c.get(`/capture/me/timeline${Qe(Sf(e))}`))}async function zf(e){return u(await c.get(`/capture/me/frames/${e}`))}function uj(e){return{workspace:{get:()=>Gf(e),setEnabled:t=>Wf(e,t)},devices:{list:t=>Pf(e,t),revoke:t=>xf(e,t),link:(t,n)=>wf(e,t,n),assetUrl:(t,n)=>Nf(e,t,n)},enrollment:{tokens:{list:()=>vf(e),create:t=>kf(e,t),revoke:t=>Af(e,t)},list:t=>Rf(e,t),approve:(t,n)=>Cf(e,t,n),deny:t=>Tf(e,t)},policy:{get:()=>If(e),set:t=>Ef(e,t)},storage:{get:()=>Mf(e),set:t=>Of(e,t)},timeline:{get:t=>jf(e,t),items:t=>Df(e,t),days:t=>Lf(e,t)},search:t=>$f(e,t),frame:(t,n)=>Uf(e,t,n),media:(t,n)=>Ff(e,t,n)}}var VS={account:e=>uj(e),deviceGrant:Bf,approveDevice:Kf,denyDevice:qf,me:{search:Hf,timeline:Vf,frame:zf}};async function Yf(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 _(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var pj=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function dj(e,t){let n=o=>{let i=pj.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 gj(){return ut()}var zS=null,YS=!1;function mj(e){let t=zS;zS=e,!(YS||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(YS=!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 JS(e,t){t?.global!==!1&&mj(e),es(e,t);let n=fb(e),{auth:r,accounts:s,iam:o,accountInvites:i}=ub(),{billing:a,sandboxShares:l}=ab(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=ib();function h(P){let k=DS(P);return{...US(P),...MS(P),...jS(P),...KS(P,k),...qS(P),...WS(P),connector:T=>hf(P,T),session:T=>yf(P,T,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:Co(),connector:P=>hf(void 0,P),project:h,session:(P,k)=>yf(P,k,e,n),github:d,gitBackend:g,billing:a,sandboxShares:l,connectStatus:m,marketplace:f,capture:VS,notifications:{registerDeviceToken:um,unregisterDeviceToken:pm,releaseDeviceToken:dm,list:gm,markRead:mm,preferences:fm,updatePreferences:ym,webPushPublicKey:hm,registerWebPushSubscription:_m,unregisterWebPushSubscription:bm},mobileClientPolicy:Yf,validateToken:ea,runtime:gj}}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 XS(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function pn(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function ZS(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function eP(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 tP(e){let t=pn(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function nP(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 rP(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 sP(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 oP(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 iP(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 Jf={thinking:!1,toolDetails:!0,assistantMetadata:!0};function fj(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function yj(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 hj(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
21
+ `)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*RE(e,t,n){let r=e.eventTransport??qm(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 fr(e){let t=s=>(o,i)=>AE(e,kE(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:RE(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 kb=200;async function CE(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function at(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new _(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function vb(e){let t=e.runtimeUrl.replace(/\/$/,""),n=fr({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=P=>e.fetch(new Request(`${t}${P}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new _(`Reading the session transcript failed: ${await CE(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,kb),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,kb),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 l=await n.global.config.get().then(g=>g.error===void 0?g.data:null),p=typeof l?.model=="string"?l.model:"",d=p.indexOf("/");d>0&&d<p.length-1&&(s={providerID:p.slice(0,d),modelID:p.slice(d+1)})}if(!s)throw new _("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 _("This session is busy. Wait for the current turn to finish, then run compact again.",{code:"SESSION_BUSY",status:409});let a=await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID});if(a.error&&typeof a.error=="object"&&"code"in a.error&&a.error.code==="LONG_TURN_PROXY_TIMEOUT")throw new _("Compaction has not finished. Check the session status before trying again.",{code:"LONG_TURN_PROXY_TIMEOUT",status:a.response?.status});return at(a,"Compacting the session failed"),s}}}function Ab(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return vb({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 Rb(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await _u(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Zt=BigInt(4096),Ve=BigInt(0xffffffffffff),Cb=Ve+BigInt(1),TE=Cb/BigInt(2),ct=BigInt(3600*1e3)*Zt,_o=120*1e3,Tb=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,IE=/^msg_([0-9a-f]{12})/,Ib="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function It(e){let t=IE.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function en(e){return BigInt(Math.trunc(e))*Zt&Ve}function Et(e,t){let n=e-t&Ve;return n>=TE&&(n-=Cb),n}function Gm(e){let t=null;for(let n of e)n!=null&&(t===null||Et(n,t)>BigInt(0))&&(t=n);return t}function Eb(e,t){let n=It(e);return n===null?!1:Et(n,en(t))>ct}function Mb(e,t){let n=t===void 0?null:en(t);return Ob(e,r=>n===null||Et(r,n)<=ct)}function Ob(e,t){let n=[];for(let r of e){let s=It(r);s!==null&&t(s)&&n.push(s)}return Gm(n)}function EE(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=Ib[n%62])}return e}function Wm(e){let t=e.random,n=en(e.nowMs-(e.backdateMs??_o)),r=e.newestKnownTime??null;if(r!==null){let o=Et(r,n);o>=BigInt(0)&&o<=ct&&(n=r+BigInt(1)&Ve)}let s="";if(t)for(let o=0;o<14;o++)s+=Ib[Math.min(61,Math.floor(t()*62))];else s=EE();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function bo(e={}){let t=e.nowMs??Date.now(),n=en(t-_o),r=Ob(e.after??[],s=>{let o=Et(s,n);return o>=BigInt(0)&&o<=ct});return Wm({nowMs:t,newestKnownTime:r}).id}function jb(e){return{scope:()=>yu(e.projectId,e.sessionId),providerSecretPool:{list:()=>gc(e.projectId,e.sessionId),get:t=>dc(e.projectId,e.sessionId,t),set:(t,n)=>mc(e.projectId,e.sessionId,t,n)},rescope:t=>hu(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=bo(),p=await Jn(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 _("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var Db=async function*(e){let t=I().eventStreamTransport;if(!t){yield*qm(((s,o)=>$(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await $t(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function ze(){let e=bb();return e||(I().billingEnabled??!1?"":__())}async function Hm(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Vm(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function zm(e){let t=Vm(e),n=await $(`${t}/env`);if(!n.ok)throw new Error(await Hm(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Ym(e,t,n){let r=Vm(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 Hm(s,"Failed to save secret"))}async function Jm(e,t){let n=Vm(e),r=await $(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Hm(r,"Failed to delete secret"))}var Lb={list:zm,set:Ym,delete:Jm};async function $b(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 So(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function yr(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return le(e)}async function Xm(e){let t=yr(e),n=await $(`${t}/kortix/pty`);if(!n.ok)throw new Error(await So(n,"Failed to list terminals"));return n.json()}async function Zm(e,t){let n=yr(e),r=await $(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await So(r,"Failed to create terminal"));return r.json()}async function ef(e,t,n){let r=yr(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 So(s,"Failed to update terminal"));return s.json()}async function tf(e,t){let n=yr(e),r=await $(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await So(r,"Failed to remove terminal"))}async function nf(e,t,n){let r=yr(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 Nt();a&&i.set("token",a),n?.wake&&i.set("wake","1");let l=i.toString();return l?`${o}${o.includes("?")?"&":"?"}${l}`:o}function Ub(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",Fb="\x07",ME="\0",Qm=`(?:${Fb}|${lt}\\\\)`,OE=[new RegExp(`${lt}\\]697;[^${Fb}${lt}]*${Qm}`,"g"),new RegExp(`${ME}?\\{"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 Nb(e){let t=e;for(let n of OE)t=t.replace(n,"");return t}var Bb={list:Xm,create:Zm,update:ef,remove:tf,webSocketUrl:nf};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 jE(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 LE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function $E(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function UE(e,t){return M(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function FE(e,t,n){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function NE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function BE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function KE(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function qE(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return M(e,`/kortix/tickets${n}`)}async function GE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function WE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function HE(e,t){return M(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function VE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function zE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function YE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function JE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function QE(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function XE(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function ZE(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function eM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function tM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function nM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function rM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function sM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function oM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function iM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function aM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function cM(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function lM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function uM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function pM(e,t,n=200){return M(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function dM(e){return M(e,"/kortix/projects")}async function gM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function mM(e,t){return M(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function fM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function yM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function hM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function _M(e,t,n="all"){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function bM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function SM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function PM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function xM(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function wM(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function kM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function vM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function AM(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function RM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function CM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function TM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function IM(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var EM=1e4,MM={retryOnAuthError:!1};function tn(e,t,n){return M(e,t,{signal:AbortSignal.timeout(EM),...n},MM)}async function OM(e,t=!1){return(await tn(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function jM(e){return(await tn(e,"/kortix/services/templates")).templates??[]}async function DM(e,t){return(await tn(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function LM(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return tn(e,s,{method:r?"DELETE":"POST"})}async function $M(e,t){return tn(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function UM(e,t){return tn(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Ye=new Map,FM=256,nn=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 nn;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(!ts())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=fr({baseUrl:e,fetch:$,eventTransport:Db});return Ye.set(e,n),Ye.size>FM&&Ye.delete(Ye.keys().next().value),n}function NM(e){Ye.delete(e)}function BM(){Ye.clear()}var Po=new Map;function KM(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=Po.get(e);if(t)return t;let n=fr({baseUrl:e,fetch});return Po.set(e,n),n}function qM(e){Po.delete(e)}function GM(){Po.clear()}async function WM(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 HM(e){let t=ze();if(!t)throw new _("[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 _(`System reload failed (${r.status}): ${await WM(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new _(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(l){throw new _(`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 Kb="frontend";function xo(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Kb}] ${t}`,...n?[n]:[]);try{ut().app.log({service:Kb,level:e,message:t,extra:n})}catch{}}var Je={debug:(e,t)=>xo("debug",e,t),info:(e,t)=>xo("info",e,t),warn:(e,t)=>xo("warn",e,t),error:(e,t)=>xo("error",e,t)};var VM=16,zM=8,qb=6e4,YM=250,JM=1e3,QM=3e4,XM=5,ZM=.5,eO=3e3,tO=3e4,Gb=2e4,nO=2e3,Wb=8;function rO(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function sO(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 Hb(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,VM-l))};return{push(l){let p=sO(n[n.length-1]?.event,l);if(p)n[n.length-1]={type:p.type,event:p};else{let d=rO(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 Vb(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 rf(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 oO(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:eO,sseMaxRetryDelay:tO,sseMaxRetryAttempts:1}).then(l=>{i||(i=!0,t.clearTimeout(a),s(l))},l=>{i||(i=!0,t.clearTimeout(a),o(l))})})}async function iO(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=Vb(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<zM)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return o}function zb(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<nO)}function Yb(e,t,n){Je.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),rf(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function Jb(e,t,n){let r=t?YM:Math.min(JM*2**Math.min(e-1,XM),QM);return Math.round(r*(1+ZM*(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 Xb(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 P=Vb(o);P.promise.then(()=>h.abort());try{let{stream:v}=await oO(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 iO(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),b=Lt(v)||Lt(v?.cause);if(Je.error("SSE event stream error",{error:T,retryCount:i,isAuthError:b}),b)try{fs(),await ms(),Je.info("SSE: refreshed auth token after auth error")}catch(S){Je.error("SSE: failed to refresh auth token",{error:String(S)})}}finally{n.clearTimeout(m),h.abort(),P.cleanup(),p.flush()}return{streamHadWork:d,stableConnection:g,error:f}}function Zb(e){return{type:"heartbeat-gap",gapMs:e}}function eS(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 aO={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},cO=5e3,lO=1e4,uO=4,hr=new WeakMap;function pO(e,t,n){let r=t.timers??aO,s=t.connectTimeoutMs??Gb,o=t.heartbeatTimeoutMs??qb,i=t.maxConsecutiveHardFailures??Wb,a=new AbortController,l=(v,...T)=>rf(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=Hb(r,v=>{m=r.now(),l(T=>T.onEvent,v)}),P={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>cO)&&l(b=>b.onGapRehydrate,v)}m=r.now()},coalescer:h};return(async()=>{let v=0,T=0,b=0;for(;!a.signal.aborted;){let S=r.now(),O=await Xb({...P,retryCount:v});if(a.signal.aborted)break;let y=O.error,{streamHadWork:w,stableConnection:x}=O,k=r.now()-S;if(T=zb(w,y,k)?T+1:0,T>=i){Yb(n,T,y),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||w},b=x&&k<lO?b+1:0;let R=x&&b<=uO;R?v=0:(v++,v>1&&Je.warn("SSE event stream reconnecting",{retryCount:v})),await Qb(r,a.signal,Jb(v,R,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),h.clearTimer()}}}function wo(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=hr.get(i);if(l?.isParked()&&(hr.delete(i),l=void 0),!l)l=pO(i,e,new Set([a])),hr.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(),hr.get(i)===p&&hr.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function tS(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 wo({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function rS(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new _(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function af(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 nn;return t}async function Sr(e,t){let n=await $(`${ue(t)}${e}`);if(!n.ok)throw new _(await af(n),{status:n.status,response:n});return n.json()}async function cf(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 _(`${r} failed (${o.status}): ${await af(o)}`,{status:o.status,response:o});return o.json()}var vo=["/workspace","/tmp","/home","/opt"],dO=vo.filter(e=>e!=="/workspace");function lf(e){return vo.some(t=>e===t||e.startsWith(`${t}/`))}function on(e){return lf(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(dO.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var uf=pt;async function an(e,t){let n=ue(t),r=pt(e)||".";return(await Sr(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function cn(e,t){let n=pt(e);return Sr(`/file/content?path=${encodeURIComponent(n)}`,t)}async function gO(e,t,n){let r=ue(n),s=pt(e),o=await $(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new _(await af(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new _("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var mO=8,ko=0,sS=[];async function fO(){if(ko<mO){ko++;return}await new Promise(e=>sS.push(e)),ko++}function yO(){ko--,sS.shift()?.()}function oS(e,t){let n=ue(t);return Nn(`${n}/file/raw?path=${encodeURIComponent(pt(e))}`)}async function ln(e,t){await fO();try{let n=ue(t);try{return await gO(e,void 0,n)}catch{}let r=await cn(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{yO()}}async function Pr(e){return Sr("/file/status",ue(e))}async function xr(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)),Sr(`/find/file?${s.toString()}`,r)}async function wr(e,t){let n=ue(t);return(await Sr(`/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 _r=[400,1200],hO=e=>e===408||e===429||e===502||e===503||e===504,nS=e=>new Promise(t=>setTimeout(t,e));function _O(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var sf=3e4,iS=15*6e4,bO=256;function rn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return sf;let t=sf+e/bO;return Math.min(iS,Math.max(sf,Math.round(t)))}async function SO(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 br(e,t){let n;for(let s=0;s<=_r.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,_O(a)||s===_r.length)break;await nS(_r[s]);continue}if(o.ok)return o.json();let i=await SO(o);if(n=new _(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!hO(o.status)||s===_r.length)throw n;await nS(_r[s])}if(n instanceof _)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new _(`Upload failed: ${r}`)}var of=8*1024*1024;function PO(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new _(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function aS(e,t){try{e?.onProgress?.(t)}catch{}}function cS(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 xO(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function un(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=ue(o),l=rn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=of){let d=await br(()=>cS(e,t,p),g=>$(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:l}));return PO(d[0],e.size),aS(i,{loadedBytes:e.size,totalBytes:e.size}),d}return wO(e,t,p,a,i)}async function wO(e,t,n,r,s){let i=(await br(()=>cS(new Blob([],{type:e.type}),t,n),l=>$(`${r}/file/upload`,{method:"POST",body:l},{timeoutMs:rn(0)})))[0]?.path;if(!i)throw new _("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=xO(i);if(!a.name)throw new _(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let l=0;l<e.size;l+=of){let p=Math.min(e.size,l+of),d=e.slice(l,p,e.type),g=await br(()=>{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:rn(d.size)}));if(g.path!==i||g.size!==p)throw new _(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});aS(s,{loadedBytes:p,totalBytes:e.size})}}catch(l){throw await Mt(i,r).catch(()=>{}),l}return[{path:i,size:e.size}]}function lS(e,t,n){let r=ue(n);return br(()=>{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:kO}))}var kO=iS;function vO(e,t,n){let r=ue(n),s=rn(t.size);return br(()=>{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 sn=class extends _{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function kr(e,t){let n=ue(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",l=on(`${a}/${i}`),p=[];try{p=await an(uS(l),n)}catch(g){if(!(g instanceof _&&g.status===404))throw g}if(p.some(g=>g.name===pS(l)))throw new sn(l);let d=await dS(l,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function vr(e,t,n){let r=ue(n);return vO(t,await ln(e,r),r)}function AO(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function uS(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function pS(e){return e.slice(e.lastIndexOf("/")+1)}function RO(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function Ar(e,t,n){let r=ue(n),s=on(AO(e.trim()));return dS(s,t,r,{overwrite:!0})}async function dS(e,t,n,r){let s=pS(e);if(!s)throw new _(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=uS(e);await pn(o,n).catch(()=>{});let i=RO(),a=await un(t,o,`.${s}.kortix-write-${i}`,n),l=a[0]?.path;if(!l)throw new _(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=on(l);try{await gS(p,e,n,r.overwrite)}catch(g){throw await Mt(p,n).catch(()=>{}),!r.overwrite&&g instanceof _&&g.status===409?new sn(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Mt(e,t){return cf("/file","DELETE",{path:e},"Delete",t)}async function pn(e,t){return cf("/file/mkdir","POST",{path:e},"Mkdir",t)}async function Rr(e,t,n){return gS(e,t,ue(n),!0)}async function gS(e,t,n,r){return cf("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function pf(){return rS(await ut().project.current())}async function Ao(){return rS(await ut().global.health())}async function df(){try{return(await Ao()).healthy===!0}catch{return!1}}var mS={list:an,read:cn,readBlob:ln,status:Pr,findFiles:xr,findText:wr,upload:un,write:Ar,create:kr,copy:vr,remove:Mt,mkdir:pn,rename:Rr,currentProject:pf,health:Ao,isReachable:df,toDaemonPath:pt,toSandboxAbsolutePath:on,toWorkspaceRelative:uf};function fS(e){return{list:async t=>an(t,(await e()).runtimeUrl),read:async t=>cn(t,(await e()).runtimeUrl),readBlob:async t=>ln(t,(await e()).runtimeUrl),status:async()=>Pr((await e()).runtimeUrl),findFiles:async(t,n)=>xr(t,n,(await e()).runtimeUrl),findText:async t=>wr(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>un(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>Ar(t,n,(await e()).runtimeUrl),create:async t=>kr(t,(await e()).runtimeUrl),copy:async(t,n)=>vr(t,n,(await e()).runtimeUrl),remove:async t=>Mt(t,(await e()).runtimeUrl),mkdir:async t=>pn(t,(await e()).runtimeUrl),rename:async(t,n)=>Rr(t,n,(await e()).runtimeUrl)}}function yS(e){return{get:t=>Vn(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:()=>er(e.sessionId,{projectId:e.projectId}),update:t=>lu(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),uu(e.projectId,e.sessionId)),restore:()=>du(e.projectId,e.sessionId),recover:()=>pu(e.projectId,e.sessionId),start:(...t)=>nt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>ju(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Qn(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Xn(e.projectId,e.sessionId)),configState:()=>gu(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),mu(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),fu(e.projectId,e.sessionId,...t)),setSharing:t=>Bl(e.projectId,e.sessionId,t),previews:()=>Vl(e.projectId,e.sessionId),participants:()=>Kl(e.projectId,e.sessionId),watch:()=>ql(e.projectId,e.sessionId),setWatch:t=>Gl(e.projectId,e.sessionId,t),setPinned:t=>Wl(e.projectId,e.sessionId,t),setArchived:t=>Hl(e.projectId,e.sessionId,t),commit:t=>Ol(e.projectId,e.sessionId,t),publicShares:{list:()=>zl(e.projectId,e.sessionId),create:(...t)=>Yl(e.projectId,e.sessionId,...t),revoke:(...t)=>Jl(e.projectId,e.sessionId,...t)}}}function hS(e){return{reminders:{list:()=>Dd(e.projectId,e.sessionId),create:t=>Ld(e.projectId,e.sessionId,t),update:(t,n)=>$s(e.projectId,e.sessionId,t,n),remove:t=>Us(e.projectId,e.sessionId,t),run:t=>$d(e.projectId,e.sessionId,t)},audit:(t,n)=>eu(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>$m(e.projectId,e.sessionId,t,n),read:(t,n)=>Um(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>tu(e.projectId,e.sessionId,t),messageAuthors:()=>bu(e.projectId,e.sessionId),modelUsage:()=>Su(e.projectId,e.sessionId),transcriptSync:t=>zn(e.projectId,e.sessionId,t),log:t=>nu(e.projectId,e.sessionId,t),turn:()=>Yn(e.projectId,e.sessionId),prompts:{create:t=>Jn(e.projectId,e.sessionId,t),list:()=>ru(e.projectId,e.sessionId),remove:t=>su(e.projectId,e.sessionId,t),retry:t=>au(e.projectId,e.sessionId,t),edit:(t,n)=>ou(e.projectId,e.sessionId,t,n),interrupt:t=>iu(e.projectId,e.sessionId,t),hold:t=>cu(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function _S(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var TO=["control_plane","provider_ingress","daemon","upstream_port"];function gf(e){return typeof e=="string"&&TO.includes(e)?e:null}function mf(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 ff(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=gf(r.headers.get("X-Kortix-Proxy-Hop"))??gf(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 bS=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,SS=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,PS=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,xS=new Set([22,4096,parseInt(Ke.KORTIX_MASTER,10)]);function IO(e){return SS.test(e)}function Ro(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 EO(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var MO=new Set(["'",'"',"`","<","(","["]),OO=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function jO(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&&MO.has(e[t]);)t++;for(;n>t&&OO.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 LO=/^\/proxy\/(\d{1,5})(\/.*)?$/,$O=/^\/(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 wS(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:$O.test(t.pathname)}catch{return!1}}function Tr(e){if(!e)return null;let t=jO(EO(e.trim())),n=hf(t);if(n){let r=Ro(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(LO);if(l){let p=parseInt(l[1],10);if(p>=1&&p<=65535)return s=p,o=Ro(`${l[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=Ro(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=DO(e);return r&&r!==e?Tr(r):null}}function UO(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 FO(e,t){return t.some(([n,r])=>e>=n&&e<r)}function kS(e){let t=[],n=new Set,r=UO(e);bS.lastIndex=0;let s;for(;(s=bS.exec(e))!==null;){let o=Tr(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:l}=o;a<1||a>65535||xS.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:FO(s.index,r)}))}return t}function NO(e){return kS(e).length>0}function BO(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function vS(e){return e.trim().toLowerCase().split("_").join("-")}function AS(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function KO(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(vS(n.sandboxId));return`${AS(s)}${t}`}function RS(e){return e.sandboxId.trim().length>0}function dt(e,t,n){let r=Ro(t);if(!RS(n))return ES(e,r);let s=KO(e,r,n);return s||(BO(n.apiBaseUrl)?`http://p${e}-${vS(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${AS(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function qO(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 CS(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function GO(e){return`http://localhost:3211${CS(e)}`}function TS(){return"/health"}function WO(e){return dt(3211,TS(),e)}function HO(e,t){return dt(e,"/",t)}function IS(e){let t=Tr(e);return!(!t||xS.has(t.port)||wS(e))}function yf(e,t){if(!e)return e;let n=Tr(e);return n?IS(n.originalUrl)?dt(n.port,n.path,t):n.originalUrl:e}function ES(e,t="/"){return`http://localhost:${e}${t}`}var MS=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function hf(e){let t=e.match(SS);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(MS);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 VO(e){try{let t=hf(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function zO(e){return IO(e)||PS.test(e)||MS.test(e)}function YO(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Cr="/web-proxy/";function JO(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Cr}${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 QO(e){try{let t=new URL(e),n=t.pathname.indexOf(Cr);if(n===-1)return null;let s=t.pathname.slice(n+Cr.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 XO(e){try{return new URL(e).pathname.includes(Cr)}catch{return e.includes(Cr)}}function ZO(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 ej(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 OS(e){return{health:t=>ff(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>dt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>yf(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Ie(e.requireReady("sandboxPortUrl").sandboxId,t)}}function _f(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=_b(e,t),{ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g}=xb(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{...yS(m),...hS(m),...OS(m),...Rb(m),...jb(m),...tS(m),files:fS(l),...Ab(m),get runtime(){return Me(d("runtime").runtimeUrl)}}}function jS(e){return{apps:{list:()=>Ag(e),create:t=>Rg(e,t),get:t=>Fs(e,t),update:(...t)=>Cg(e,...t),access:{get:(...t)=>Mg(e,...t),update:(...t)=>jg(e,...t),session:(...t)=>Dg(e,...t),agents:t=>Og(e,t)},remove:t=>Tg(e,t),token:t=>Ig(e,t),authEnv:t=>Eg(e,t),artifacts:{register:t=>Ns(e,t),uploadArchive:(...t)=>Lg(e,...t),finalize:(...t)=>Bs(e,...t)},deployments:{create:(...t)=>$g(e,...t),list:t=>Ug(e,t),get:(...t)=>Fg(e,...t),logs:(...t)=>Ng(e,...t),remove:(...t)=>qg(e,...t)},start:t=>Bg(e,t),stop:t=>Kg(e,t),rollback:(...t)=>Gg(e,...t),machines:{list:t=>Wg(e,t),start:(t,n)=>Vg(e,t,n),stop:(t,n)=>zg(e,t,n),restart:(t,n)=>Yg(e,t,n),destroy:(t,n)=>Jg(e,t,n)},scale:(...t)=>Qg(e,...t),exec:(...t)=>Xg(e,...t),volumes:{list:t=>Zg(e,t),create:(...t)=>em(e,...t),update:(...t)=>tm(e,...t),destroy:(...t)=>nm(e,...t),snapshots:(...t)=>rm(e,...t),snapshot:(...t)=>sm(e,...t),restore:(...t)=>om(e,...t),fork:(...t)=>im(e,...t)}}}}function DS(e){return{list:()=>Ea(e),invite:(...t)=>ja(e,...t),update:(...t)=>Ma(e,...t),revoke:t=>Oa(e,t),pendingInvites:()=>Da(e),resendInvite:(...t)=>$a(e,...t),revokeInvite:(...t)=>La(e,...t),requests:()=>Ca(e),approveRequest:(...t)=>Ta(e,...t),rejectRequest:(...t)=>Ia(e,...t),groupGrants:()=>Ua(e),attachGroupGrant:(...t)=>Fa(e,...t),updateGroupGrant:(...t)=>Na(e,...t),detachGroupGrant:t=>Ba(e,t),resourceGrants:{list:()=>Ka(e),create:t=>qa(e,t),remove:t=>Ga(e,t)}}}function LS(e){return{tokens:{list:()=>sg(e),create:t=>og(e,t),revoke:t=>ig(e,t)},setupLinks:{requestSecret:t=>yg(e,t),requestConnector:t=>hg(e,t)},validateManifest:t=>sa(e,t),gitToken:()=>oa(e),agentIdentities:()=>ad(e),secrets:{list:()=>za(e),upsert:t=>Ya(e,t),setStrategy:(...t)=>Ja(e,...t),broker:(...t)=>Qa(e,...t),remove:t=>$n(e,t),setPersonal:(...t)=>tc(e,...t),removePersonal:t=>nc(e,t),setGitCredential:t=>ec(e,t),listProviderOAuth:()=>Xa(e),startProviderOAuth:(...t)=>ds(e,...t),pollProviderOAuth:(...t)=>gs(e,...t),removeProviderOAuth:t=>Za(e,t)},access:DS(e)}}function $S(e){return{list:()=>yc(e),listAll:()=>hc(e),reconcile:(...t)=>_c(e,...t),reconcileMember:(...t)=>bc(e,...t),updateCredential:(...t)=>Sc(e,...t),revoke:(...t)=>Pc(e,...t),activate:(...t)=>xc(e,...t),setDefault:(...t)=>wc(e,...t),rename:(...t)=>kc(e,...t),share:(...t)=>Ac(e,...t),addComputer:(...t)=>vc(e,...t),pipedreamConnect:(...t)=>Rc(e,...t),pipedreamFinalize:(...t)=>Cc(e,...t)}}function Co(e){return{catalog:t=>Bt(e,t),tools:()=>hs(e),search:(...t)=>fc(e,...t),describe:(...t)=>_s(e,...t),call:(...t)=>kt(e,...t),callAction:(t,n,r,s)=>kt(e,`${t}.${n}`,r,s),accounts:(...t)=>bs(e,...t),uploadAttachment:(...t)=>Ss(e,...t)}}function bf(e,t){return{slug:t,run:(r,s,o)=>vs(e,t,r,s,o),call:(r,s,o)=>kt(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?_s(e,`${t}.${r}`):(await Bt(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>bs(e,t),paginate:(r,s,o)=>Qc(e,t,r,s,o),uploadAttachment:(r,s)=>Ss(e,r,{...s,connector:t})}}var tj=100,US=0,nj=new Set(["attachment_size_mismatch","attachment_failed"]),FS=()=>new _("Attachment expired. Attach the file again.",{code:"attachment_expired"});function Sf(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 rj(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+tj-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,Kt(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:FS()});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 P(y,w,x){let k=++y.generation,C=new AbortController;y.abort=C,y.item={...y.item,status:"uploading",error:void 0};let D=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===k,R=rj(y,D,m);qn(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=>{D()&&(y.item={...y.item,status:"ready",attachment:Sf(L),receivedBytes:L.size})}).catch(L=>{L instanceof _&&nj.has(L.code??"")&&(y.upload=void 0),D()&&(y.item={...y.item,status:L instanceof _&&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++,P(y,w,()=>{i--,m(),v()})}m()}function T(y){h(y.map(x=>x.size));let w=y.map(x=>{let k=`attachment-${++US}`;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 b(y){let w=y.map(({attachment:k,file:C})=>{try{return{attachment:Sf(k),file:C}}catch{return}});h(w.flatMap(k=>k?[k.attachment.size]:[]));let x=w.map(k=>{if(!k)return;let C=`attachment-${++US}`,{attachment:D,file:R}=k;return r.set(C,{generation:0,item:{id:C,...R?{file:R}:{},filename:D.filename,mime:D.mime,size:D.size,status:"ready",receivedBytes:D.size,attachment:D}}),C});return m(),x}function S(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 D=()=>{o.delete(pe),w?.removeEventListener("abort",L)},R=j=>{D(),C(j)},L=()=>R(Ae()),pe=()=>{let j=!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"&&(j=!0)}if(j)return;let q;try{q=x.map(W=>{let K=Sf(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)))}D(),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:b,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 FS();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:S,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&&Kt(e,w).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(y){return s.add(y),()=>{s.delete(y)}}}}function NS(e){return{attachments:{upload:(...t)=>qn(e,...t),delete:(...t)=>Kt(e,...t),createController:t=>Pf(e,t)},get:t=>wt(e,t),detail:()=>Mn(e),skills:{remove:(...t)=>ma(e,...t),create:(...t)=>ga(e,...t)},audit:t=>ug(e,t),update:t=>Dn(e,t),archive:()=>Ln(e),llmCatalog:()=>On(e),modelPicker:()=>jn(e),modelAccess:()=>sr(e),setModelAccess:t=>or(e,t),customLlmProviders:()=>ir(e),setCustomLlmProvider:(t,n)=>ar(e,t,n),deleteCustomLlmProvider:t=>cr(e,t),sandboxHealth:()=>Fn(e),onboardingComplete:(...t)=>da(e,...t)}}function BS(e){return{sessions:{list:t=>At(e,t),listPage:t=>Nl(e,t),create:t=>Rt(e,t),ensureWarm:()=>Xl(e),claimWarm:t=>Zl(e,t)},review:{list:t=>Ad(e,t),summary:()=>Rd(e),get:t=>Cd(e,t),submit:t=>Td(e,t),act:(...t)=>Id(e,...t),bulkAct:t=>Ed(e,t)},approvals:{list:t=>Wa(e,t),resolve:(...t)=>Va(e,...t),sessionsNeedingInput:t=>Ha(e,t)}}}function KS(e){return{files:{write:t=>fl(e,t),list:t=>ll(e,t),listDirectory:t=>ul(e,t),read:(t,n)=>dl(e,t,n),search:(...t)=>pl(e,...t),archive:(...t)=>gl(e,...t),archiveRequest:(...t)=>ml(e,...t),history:(...t)=>xl(e,...t)},git:{commits:()=>bl(e),commit:t=>Sl(e,t),commitDiff:t=>Pl(e,t),branches:()=>_l(e),versionDiff:(...t)=>wl(e,...t),inviteCollaborator:(...t)=>ra(e,...t)},changeRequests:{list:(...t)=>kl(e,...t),get:t=>vl(e,t),update:(...t)=>jl(e,...t),diff:t=>Al(e,t),mergePreview:t=>Rl(e,t),open:(...t)=>Cl(e,...t),merge:(...t)=>Tl(e,...t),close:(...t)=>Il(e,...t),reopen:(...t)=>El(e,...t),requestChanges:(...t)=>Ml(e,...t)},...BS(e)}}function qS(e){return{policies:{list:()=>Xc(e),set:(...t)=>Zc(e,...t)},reminders:{list:()=>tr(e),updateMany:(...t)=>Ud(e,...t),removeMany:(...t)=>Fd(e,...t)},rooms:{list:(...t)=>Bd(e,...t),create:(...t)=>Kd(e,...t),get:(...t)=>qd(e,...t),update:(...t)=>Gd(e,...t),messages:(...t)=>Wd(e,...t),post:(...t)=>Hd(e,...t),markRead:(...t)=>Vd(e,...t),addSession:(...t)=>zd(e,...t),removeSession:(...t)=>Yd(e,...t),addPerson:(...t)=>Jd(e,...t),removePerson:(...t)=>Qd(e,...t),people:(...t)=>Xd(e,...t)},triggers:{list:()=>Pu(e),eventApps:()=>Eu(e),eventTypes:(...t)=>Iu(e,...t),create:(...t)=>xu(e,...t),update:(...t)=>wu(e,...t),remove:(...t)=>ku(e,...t),fire:((t,n)=>Au(e,t,n)),runs:(...t)=>Ru(e,...t),projectRuns:(...t)=>Cu(e,...t),replay:(...t)=>Tu(e,...t),setActivation:(...t)=>vu(e,...t)},...KS(e)}}function GS(e,t){return{connectors:{...Co(e),list:()=>Tc(e),config:(...n)=>Lc(e,...n),create:(...n)=>Fc(e,...n),remove:(...n)=>qc(e,...n),sync:()=>Ic(e),auth:{discover:(...n)=>Nc(e,...n)},setName:(...n)=>$c(e,...n),setCredentialMode:(...n)=>Ec(e,...n),setAuthorizationStrategy:(...n)=>Mc(e,...n),setCredential:(...n)=>zc(e,...n),deleteCredential:(...n)=>Yc(e,...n),setSensitive:(...n)=>Oc(e,...n),connections:t,policies:{get:(...n)=>jc(e,...n),set:(...n)=>Dc(e,...n)},listMoves:()=>Bc(e),move:(...n)=>Kc(e,...n),pipedream:{listApps:(...n)=>Gc(e,...n),listSections:(...n)=>Wc(e,...n),connect:(...n)=>Uc(e,...n),finalize:(...n)=>Jc(e,...n)},discover:{list:(...n)=>Ps(e,...n),sections:(...n)=>Hc(e,...n),detail:(...n)=>xs(e,...n)}},...qS(e)}}function WS(e){return{gateway:{logs:t=>Op(e,t),log:t=>jp(e,t),overview:t=>Dp(e,t),series:t=>Lp(e,t),breakdown:t=>$p(e,t),sessions:t=>Up(e,t),errors:t=>Fp(e,t),budgets:()=>Np(e),setBudget:t=>Bp(e,t),deleteBudget:t=>Kp(e,t),keys:()=>qp(e),createKey:t=>Gp(e,t),revokeKey:t=>Wp(e,t),routing:{get:()=>Tp(e),set:t=>Ip(e,t),reset:()=>Ep(e),preview:t=>Mp(e,t)},playground:(t,n,r)=>Hp(e,t,n,r)}}}function HS(e){return{modelDefaults:{get:()=>Du(e),set:t=>Lu(e,t),clear:t=>$u(e,t)},setDefaultAgent:t=>Nu(e,t),sandbox:{list:()=>cl(e),snapshots:()=>tl(e),rebuildSnapshot:t=>nl(e,t),fixWithAgent:()=>rl(e),createTemplate:t=>sl(e,t),updateTemplate:(...t)=>ol(e,...t),removeTemplate:t=>il(e,t),buildTemplate:t=>al(e,t),setProvider:t=>pa(e,t)},setAgentScope:(...t)=>Uu(e,...t)}}function VS(e){return{channels:{slack:{installation:()=>mp(e),connect:t=>fp(e,t),mode:()=>yp(e),completeInstall:t=>hp(e,t),manifest:()=>bp(e),disconnect:()=>Sp(e),getFile:t=>Pp(e,t),uploadFile:t=>xp(e,t)},teams:{completeInstall:t=>_p(e,t)},email:{installation:t=>kp(e,t),mode:()=>vp(e),connect:t=>Ap(e,t),disconnect:t=>Rp(e,t),updatePolicy:(...t)=>Cp(e,...t)}},updateFeatureFlag:(...t)=>la(e,...t),updateExperimentalFeature:(...t)=>ua(e,...t),...HS(e)}}var sj=["screen","actions","audio"],oj=["password_managers","messaging","banking"],ij={localHours:8760,remoteDays:3650},aj=[500,1e3,2e3,5e3,1e4],cj=[720,1080,1440,2160],lj={intervalMs:2e3,maxHeight:1440},uj=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function pj(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(/\.$/,""),uj.test(n)?n:null}function dj(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 gj(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var J=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 zS=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}),xf=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function wf(e,t={}){return u(await c.get(`${J(e)}/devices${Qe({user_id:t.userId,scope:t.scope})}`))}async function kf(e,t){return u(await c.delete(`${J(e)}/devices/${t}`))}async function vf(e,t,n){return u(await c.put(`${J(e)}/devices/${t}/link`,{user_id:n}))}async function Af(e){return u(await c.get(`${J(e)}/enrollment-tokens`))}async function Rf(e,t){return u(await c.post(`${J(e)}/enrollment-tokens`,t))}async function Cf(e,t){return u(await c.delete(`${J(e)}/enrollment-tokens/${t}`))}async function Tf(e,t={}){return u(await c.get(`${J(e)}/enrollments${Qe({status:t.status})}`))}async function If(e,t,n){return u(await c.post(`${J(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function Ef(e,t){return u(await c.post(`${J(e)}/enrollments/${t}/deny`,{}))}async function Mf(e){return u(await c.get(`${J(e)}/policy`))}async function Of(e,t){return u(await c.put(`${J(e)}/policy`,{policy:t}))}async function jf(e){return u(await c.get(`${J(e)}/storage`))}async function Df(e,t){return u(await c.put(`${J(e)}/storage`,t))}async function Lf(e,t={}){return u(await c.get(`${J(e)}/timeline${Qe(xf(t))}`))}async function $f(e,t={}){return u(await c.get(`${J(e)}/timeline/items${Qe(xf(t))}`))}async function Uf(e,t={}){return u(await c.get(`${J(e)}/days${Qe({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function Ff(e,t){return u(await c.get(`${J(e)}/search${zS(t)}`))}async function Nf(e,t,n={}){return u(await c.get(`${J(e)}/frames/${t}${Qe({user_id:n.userId,device_id:n.deviceId})}`))}async function Bf(e,t,n={}){return u(await c.get(`${J(e)}/chunks/${t}/media${Qe({user_id:n.userId,device_id:n.deviceId})}`))}async function Kf(e,t,n){return u(await c.get(`${J(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function qf(e){return u(await c.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function Gf(e,t){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function Wf(e){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function Hf(e){return u(await c.get(J(e)))}async function Vf(e,t){return u(await c.patch(J(e),{enabled:t}))}async function zf(e){return u(await c.get(`/capture/me/search${zS(e)}`))}async function Yf(e={}){return u(await c.get(`/capture/me/timeline${Qe(xf(e))}`))}async function Jf(e){return u(await c.get(`/capture/me/frames/${e}`))}function fj(e){return{workspace:{get:()=>Hf(e),setEnabled:t=>Vf(e,t)},devices:{list:t=>wf(e,t),revoke:t=>kf(e,t),link:(t,n)=>vf(e,t,n),assetUrl:(t,n)=>Kf(e,t,n)},enrollment:{tokens:{list:()=>Af(e),create:t=>Rf(e,t),revoke:t=>Cf(e,t)},list:t=>Tf(e,t),approve:(t,n)=>If(e,t,n),deny:t=>Ef(e,t)},policy:{get:()=>Mf(e),set:t=>Of(e,t)},storage:{get:()=>jf(e),set:t=>Df(e,t)},timeline:{get:t=>Lf(e,t),items:t=>$f(e,t),days:t=>Uf(e,t)},search:t=>Ff(e,t),frame:(t,n)=>Nf(e,t,n),media:(t,n)=>Bf(e,t,n)}}var YS={account:e=>fj(e),deviceGrant:qf,approveDevice:Gf,denyDevice:Wf,me:{search:zf,timeline:Yf,frame:Jf}};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 _(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var yj=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function hj(e,t){let n=o=>{let i=yj.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 _j(){return ut()}var JS=null,QS=!1;function bj(e){let t=JS;JS=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 XS(e,t){t?.global!==!1&&bj(e),es(e,t);let n=hb(e),{auth:r,accounts:s,iam:o,accountInvites:i}=db(),{billing:a,sandboxShares:l}=lb(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=cb();function h(P){let v=$S(P);return{...NS(P),...jS(P),...LS(P),...GS(P,v),...WS(P),...VS(P),connector:T=>bf(P,T),session:T=>_f(P,T,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:Co(),connector:P=>bf(void 0,P),project:h,session:(P,v)=>_f(P,v,e,n),github:d,gitBackend:g,billing:a,sandboxShares:l,connectStatus:m,marketplace:f,capture:YS,notifications:{registerDeviceToken:dm,unregisterDeviceToken:gm,releaseDeviceToken:mm,list:fm,markRead:ym,preferences:hm,updatePreferences:_m,webPushPublicKey:bm,registerWebPushSubscription:Sm,unregisterWebPushSubscription:Pm},mobileClientPolicy:Qf,validateToken:ta,runtime:_j}}function ZS(){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 eP(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function dn(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function tP(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function nP(e){if(dn(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 rP(e){let t=dn(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function sP(e,t){let n=dn(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 oP(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 iP(e,t){return dn(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 aP(e,t,n){return dn(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 cP(e,t,n){let r=dn(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 Xf={thinking:!1,toolDetails:!0,assistantMetadata:!0};function Sj(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function Pj(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 xj(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 _j(e,t){if(!t)return`## Assistant
54
+ `,n}return""}function wj(e,t){if(!t)return`## Assistant
55
55
 
56
- `;let n=e.agent?fj(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=yj(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
56
+ `;let n=e.agent?Sj(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=Pj(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 bj(e,t,n){let r="";e.role==="user"?r+=`## User
60
+ `}function kj(e,t,n){let r="";e.role==="user"?r+=`## User
61
61
 
62
- `:r+=_j(e,n.assistantMetadata);for(let s of t)r+=hj(s,n);return r}function aP(e,t,n=Jf){let r=`# ${e.title||"Untitled Session"}
62
+ `:r+=wj(e,n.assistantMetadata);for(let s of t)r+=xj(s,n);return r}function lP(e,t,n=Xf){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+=bj(s.info,s.parts,n),r+=`---
70
+ `;for(let s of t)r+=kj(s.info,s.parts,n),r+=`---
71
71
 
72
- `;return r}function cP(e,t){return`session-${e}.md`}var Qf="An error occurred";var Sj=["message","error","detail","error_description","msg","errors","data"];function Xf(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 Pj(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 xj(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=wj(e,t);if(n)return n;let r=kj(e,t);return r?r.slice(0,200):void 0}function dP(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function lP(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function wj(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!dP(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 vj=["script","style"];function kj(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=vj.find(i=>t.startsWith(`<${i}`,s)&&dP(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:lP(e,i);continue}r=lP(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function Aj(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 Rj(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function uP(e,t,n){if(typeof e=="string")return To(e,t,n);if(e&&typeof e=="object")return Io(e,t,n)}function To(e,t,n=new WeakSet){let r=Xf(e);if(!r)return;if(t>=4)return r;let s=Aj(r);if(s)return s;let o=dn(r);if(o!==void 0)return typeof o=="string"?To(o,t+1,n):o&&typeof o=="object"?Io(o,t+1,n):String(o);let i=gP(r);if(i){let a=dn(i);if(a&&typeof a=="object"){let l=Io(a,t+1,n);if(l)return l}}if(r.includes("{")){let a=Pj(r);if(a)return To(a,t+1,n)??a}return xj(r)??r}function Io(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=uP(i,t,n);if(a)return a}return}let r=e;for(let i of Sj){let a=uP(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return Rj(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"?To(e,0)??Qf:typeof e=="object"?Io(e,0)??Qf:String(e):Qf}function Tr(e){let t=Cj(e)?.trim();if(!t)return;let n=ye(e);if(!(t===n||Xf(t)===n))return t}function Cj(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(`
72
+ `;return r}function uP(e,t){return`session-${e}.md`}var Zf="An error occurred";var vj=["message","error","detail","error_description","msg","errors","data"];function ey(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 gn(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function Aj(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=gn(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function Rj(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=Cj(e,t);if(n)return n;let r=Ij(e,t);return r?r.slice(0,200):void 0}function mP(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function pP(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function Cj(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!mP(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 Tj=["script","style"];function Ij(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=Tj.find(i=>t.startsWith(`<${i}`,s)&&mP(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:pP(e,i);continue}r=pP(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function Ej(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 Mj(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function dP(e,t,n){if(typeof e=="string")return To(e,t,n);if(e&&typeof e=="object")return Io(e,t,n)}function To(e,t,n=new WeakSet){let r=ey(e);if(!r)return;if(t>=4)return r;let s=Ej(r);if(s)return s;let o=gn(r);if(o!==void 0)return typeof o=="string"?To(o,t+1,n):o&&typeof o=="object"?Io(o,t+1,n):String(o);let i=fP(r);if(i){let a=gn(i);if(a&&typeof a=="object"){let l=Io(a,t+1,n);if(l)return l}}if(r.includes("{")){let a=Aj(r);if(a)return To(a,t+1,n)??a}return Rj(r)??r}function Io(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=dP(i,t,n);if(a)return a}return}let r=e;for(let i of vj){let a=dP(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return Mj(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"?To(e,0)??Zf:typeof e=="object"?Io(e,0)??Zf:String(e):Zf}function Ir(e){let t=Oj(e)?.trim();if(!t)return;let n=ye(e);if(!(t===n||ey(t)===n))return t}function Oj(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 gP(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function Tj(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 Ij(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 pP(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=Ij(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||Tj(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=Xf(e),l=dn(a)??dn(gP(a));return l!==void 0?Se(l):void 0}if(typeof e!="object")return;let t=e,n=pP(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=pP(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 mP={};function V(e,t){for(let n of t)mP[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 Ej=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ae(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=mP[t];if(n)return n;for(let[r,s]of Ej)if(t.startsWith(r))return s;return"other"}function ke(e){for(let t of[e?.filePath,e?.file_path,e?.path,e?.notebook_path])if(typeof t=="string"&&t)return t}var Mj=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function Oj(){return new RegExp(`(^|\\s)([-+]?)(${Mj.join("|")}):("[^"]*"|\\S+)`,"gi")}function jj(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function Dj(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function Lj(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function $j(e){return Lj(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function fP(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Ir(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(Oj(),(s,o,i,a,l)=>{if(!i&&a.toLowerCase()==="site"){let p=$j(l);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(jj(),"$1").replace(Dj(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${fP(n)}`:r:n.length>0?fP(n):t}var Uj=/\s/,Fj=/\w/;function he(e){return e!==void 0&&Uj.test(e)}function Er(e){return e===`
75
- `||e==="\r"||e==="\u2028"||e==="\u2029"}function Zf(e){return e!==void 0&&Fj.test(e)}function Mt(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(Nj(n.charCodeAt(0))):n;return t}function Nj(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 yP(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Xe(e.slice(t))}function Mr(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let s=e.indexOf(n,r+t.length);return s===-1?null:e.slice(r+t.length,s)}function ey(e,t){let n=Mr(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
74
+ `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function fP(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function jj(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 Dj(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 gP(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=Dj(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||jj(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=ey(e),l=gn(a)??gn(fP(a));return l!==void 0?Se(l):void 0}if(typeof e!="object")return;let t=e,n=gP(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=gP(s);if(a)return a}let o=t.data;if(o&&typeof o.responseBody=="string"){let a=gn(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 yP={};function V(e,t){for(let n of t)yP[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 Lj=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ae(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=yP[t];if(n)return n;for(let[r,s]of Lj)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 $j=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function Uj(){return new RegExp(`(^|\\s)([-+]?)(${$j.join("|")}):("[^"]*"|\\S+)`,"gi")}function Fj(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function Nj(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function Bj(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Kj(e){return Bj(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function hP(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Er(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(Uj(),(s,o,i,a,l)=>{if(!i&&a.toLowerCase()==="site"){let p=Kj(l);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(Fj(),"$1").replace(Nj(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${hP(n)}`:r:n.length>0?hP(n):t}var qj=/\s/,Gj=/\w/;function he(e){return e!==void 0&&qj.test(e)}function Mr(e){return e===`
75
+ `||e==="\r"||e==="\u2028"||e==="\u2029"}function ty(e){return e!==void 0&&Gj.test(e)}function Ot(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(Wj(n.charCodeAt(0))):n;return t}function Wj(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 _P(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Xe(e.slice(t))}function Or(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 ny(e,t){let n=Or(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 ty(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 hP(e,t){let n=ty(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function _P(e,t){let n=ty(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 bP(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=ty(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 SP(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 Eo(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 PP(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 xP(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(Er(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&&!Er(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(!Er(e[m]))return e[m];return null}}a=i(l)}return null}function wP(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++;Zf(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]+(Er(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&&Zf(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(!Er(e[g]))return{id:e.slice(a+2,l),title:e[g],status:i(d)}}}}return null}function ny(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||!Zf(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 vP(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 kP(e){return vP(e,!0)}function AP(e){return vP(e,!1)}function Bj(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function RP(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(Bj(e,d))return e.slice(l,p);p=d}return e.slice(l)}return null}var CP=new Set(["read","glob","grep","list"]);function Z(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function Kj(e){return CP.has(ae(e))}function qj(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 ry(e){if(!e)return"";let t=Xe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Mo(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Oo(e){let t=We(e),r=(t.state??{}).input??{};switch(Z(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=ke(r);return i?ry(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?`"${Mo(String(i),40)}" in ${ry(String(a))}`:i?`"${Mo(String(i),60)}"`:""}case"list":return r.path?ry(String(r.path)):"";case"bash":return Mo(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 Mo(i==="query"&&Ir(a)||a,60)}return""}var TP={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 Gj(e,t={}){let n=me(e)?oe(e):e,r={...TP,...t},s=Z(n.tool),o=Oo(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 oy(e){return e.type==="file"}function Wj(e){return e.type==="agent"}function Hj(e){return e.type==="compaction"}function Vj(e){return e.type==="snapshot"}function zj(e){return e.type==="patch"}function Yj(e){return e.type==="step-start"||e.type==="step-finish"}function Jj(e){if(Oe(e)||we(e))return e.text}function Qj(e){if(!oy(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function Xj(e){let t=[],n=[];for(let r of e)oy(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function Zj(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function eD(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var tD=new Set(["todoread","context_info"]);function gn(e){return!tD.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 jr(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 rD(n,t.state)}function rD(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 sD(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 oD(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 iD={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=>MP(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 aD(e,t={}){let n=iD[Z(e)];if(!n)return cD(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function cD(e,t){switch(ae(e)){case"read":return{icon:"glasses",title:"Read",subtitle:IP(ke(t))};case"list":return{icon:"list",title:"List",subtitle:EP(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:sy(ke(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:sy(ke(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function IP(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function sy(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 EP(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function lD(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 Or(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 MP(e){let t=Or(e.description);if(t)return t;let n=Or(e.title,80);if(n)return n;let r=Or(e.message);if(r)return r;let s=Or(e.prompt);if(s)return s;let o=Or(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function uD(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function pD(e,t){return e.find(n=>n.tool?.callID===t)}function dD(e,t){return e.find(n=>n.tool?.callID===t)}var gD=/\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 iy(e){return e?e.replace(gD,""):""}function jo(e){let t=OP(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let s=r&&typeof r=="object"?OP(r):void 0;return s?[s]:[]})}function OP(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 mD={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"},fD={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 yD(e){return e.replace(/^oc[-_]/,"")}function ay(e){return yD(e).replace(/-/g,"_")}function cy(e){return ay(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Do(e){return{label:mD[ay(e)]??cy(e),category:fD[ae(e)]}}var hD=256*1024;function _D(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function bD(e){if(e===void 0)return{};if(e.length>hD)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function SD(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,Lo=e=>typeof e=="number"?e:void 0,$o=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function ly(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var PD=new Set(["add","update","delete","move"]);function xD(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=$o(d),m=g&&(de(g.relativePath)||de(g.filePath));if(!g||!m)return[];let f=de(g.type);return[ly({path:m,type:f&&PD.has(f)?f:void 0,before:de(g.before),after:de(g.after),patch:de(g.patch)??de(g.diff),additions:Lo(g.additions),deletions:Lo(g.deletions),movePath:de(g.movePath)})]});return p.length?p:void 0}let r=ke(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[ly({path:r,after:de(t.content)})];if(e!=="edit")return;let s=$o(n.filediff),o=s?void 0:de(n.patch),i=o?wD(o):void 0,a=s||o?[]:jo(t);return[ly({path:r,before:de(s?.before)??(a.length?a.map(([l])=>l).join(`
77
+ `)&&(n=n.slice(0,-1)),n)}function ry(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 bP(e,t){let n=ry(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function SP(e,t){let n=ry(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=ry(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 xP(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 Eo(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 wP(e,t,n){let r=Ot(t),s=Ot(n);for(let o of Ot(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 kP(e,t){let n=Ot(e),r=t.map(Ot),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(Mr(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&&!Mr(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(!Mr(e[m]))return e[m];return null}}a=i(l)}return null}function vP(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++;ty(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]+(Mr(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&&ty(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(!Mr(e[g]))return{id:e.slice(a+2,l),title:e[g],status:i(d)}}}}return null}function sy(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||!ty(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 AP(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 RP(e){return AP(e,!0)}function CP(e){return AP(e,!1)}function Hj(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function TP(e,t){let n=Ot(e),r=Ot(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(Hj(e,d))return e.slice(l,p);p=d}return e.slice(l)}return null}var IP=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function Vj(e){return IP.has(ae(e))}function zj(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 oy(e){if(!e)return"";let t=Xe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Mo(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Oo(e){let t=We(e),r=(t.state??{}).input??{};switch(ee(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=ve(r);return i?oy(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?`"${Mo(String(i),40)}" in ${oy(String(a))}`:i?`"${Mo(String(i),60)}"`:""}case"list":return r.path?oy(String(r.path)):"";case"bash":return Mo(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 Mo(i==="query"&&Er(a)||a,60)}return""}var EP={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 Yj(e,t={}){let n=me(e)?oe(e):e,r={...EP,...t},s=ee(n.tool),o=Oo(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 te(e){return e.type==="tool"}function ay(e){return e.type==="file"}function Jj(e){return e.type==="agent"}function Qj(e){return e.type==="compaction"}function Xj(e){return e.type==="snapshot"}function Zj(e){return e.type==="patch"}function eD(e){return e.type==="step-start"||e.type==="step-finish"}function tD(e){if(Oe(e)||we(e))return e.text}function nD(e){if(!ay(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function rD(e){let t=[],n=[];for(let r of e)ay(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function sD(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function oD(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var iD=new Set(["todoread","context_info"]);function mn(e){return!iD.has(me(e)?e.name:e.tool)}var aD=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 Dr(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 cD(n,t.state)}function cD(e,t){let n=ee(e);if(aD.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 lD(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 uD(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)te(r)&&mn(r)&&t.push(r);return t}var pD={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=>jP(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 dD(e,t={}){let n=pD[ee(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:MP(ve(t))};case"list":return{icon:"list",title:"List",subtitle:OP(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:iy(ve(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:iy(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 MP(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function iy(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 OP(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function mD(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 jr(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 jP(e){let t=jr(e.description);if(t)return t;let n=jr(e.title,80);if(n)return n;let r=jr(e.message);if(r)return r;let s=jr(e.prompt);if(s)return s;let o=jr(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function fD(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 hD(e,t){return e.find(n=>n.tool?.callID===t)}var _D=/\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 cy(e){return e?e.replace(_D,""):""}function jo(e){let t=DP(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let s=r&&typeof r=="object"?DP(r):void 0;return s?[s]:[]})}function DP(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 bD={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"},SD={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 PD(e){return e.replace(/^oc[-_]/,"")}function ly(e){return PD(e).replace(/-/g,"_")}function uy(e){return ly(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Do(e){return{label:bD[ly(e)]??uy(e),category:SD[ae(e)]}}var xD=256*1024;function wD(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function kD(e){if(e===void 0)return{};if(e.length>xD)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function vD(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,Lo=e=>typeof e=="number"?e:void 0,$o=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function py(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var AD=new Set(["add","update","delete","move"]);function RD(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=$o(d),m=g&&(de(g.relativePath)||de(g.filePath));if(!g||!m)return[];let f=de(g.type);return[py({path:m,type:f&&AD.has(f)?f:void 0,before:de(g.before),after:de(g.after),patch:de(g.patch)??de(g.diff),additions:Lo(g.additions),deletions:Lo(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[py({path:r,after:de(t.content)})];if(e!=="edit")return;let s=$o(n.filediff),o=s?void 0:de(n.patch),i=o?CD(o):void 0,a=s||o?[]:jo(t);return[py({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:Lo(s?.additions)??i?.additions,deletions:Lo(s?.deletions)??i?.deletions})]}function wD(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 vD(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function jP(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=bD(r),i=_D(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=SD(s);m&&(i="error",a=m)}let l=ae(e),p=t.input??{},d="metadata"in t&&$o(t.metadata)||{},g=$o(d.diagnostics);return{name:e,kind:l,title:n||Do(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:xD(l,p,d),diff:de(d.patch)??de(d.diff),diagnostics:g,answers:l==="question"?vD(d):void 0,childSessionId:jr({tool:e,state:t})}}function uy(e){let t=me(e)?oe(e):e;return jP(t.tool,t.state)}function kD(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function AD(e){return{kind:"reasoning",id:e.id,text:e.text}}function RD(e){return{kind:"tool",id:e.id,tool:jP(e.tool,e.state)}}function CD(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 TD(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function ID(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function ED(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function MD(e){return{kind:"agent",id:e.id,name:e.name}}function OD(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:ye(e.error),createdAt:e.time.created}}function jD(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function DD(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function LD(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function py(e){switch(e.type){case"text":return kD(e);case"reasoning":return AD(e);case"tool":return RD(e);case"file":return CD(e);case"subtask":return TD(e);case"patch":return ID(e);case"snapshot":return ED(e);case"agent":return MD(e);case"retry":return OD(e);case"compaction":return jD(e);case"step-start":return DD(e);case"step-finish":return LD(e);default:return{kind:"unknown",raw:e}}}function $D(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 UD(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function Uo(e){let t=e.parts.map(py),n=e.info.role==="assistant"?e.info.error:void 0,r=$D(n),s=!r&&!t.some(UD);return{parts:t,error:r,isEmpty:s}}var dy=Ve+BigInt(1),DP=dy/BigInt(2);function Fo(e){return BigInt(Math.trunc(e))*Xt}function gy(e,t){let r=t-(t&Ve)+e;return r-t>DP?r-=dy:t-r>DP&&(r+=dy),r}function LP(e,t){let n=Tt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return gy(n,t);let s=Fo(r),o=gy(n,s);return(o>s?o-s:s-o)<=ct?o:s}function $P(e){return Tt(e)===null?1:0}function UP(e,t){return e<t?-1:e>t?1:0}function FD(e,t){return No(e,t,Fo(Date.now()))}function my(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 Fo(t??Date.now())}function No(e,t,n){let r=$P(e.info.id),s=$P(t.info.id);if(r!==s)return r-s;if(r===0){let a=LP(e,n),l=LP(t,n);return a!==l?a<l?-1:1:UP(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:UP(e.info.id,t.info.id)}function ND(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 BD(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 FP(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(...FP(e,s));return r}function KD(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=my(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:No(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:GD(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,qD=256;function GD(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>=qD){let a=Dr.keys().next().value;a!==void 0&&Dr.delete(a)}return Dr.set(s,i),i}function WD(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function HD(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(Oe(n)&&n.text?.trim())return n}}function VD(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function zD(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 NP(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function fy(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&&NP(n.error)}return!1}function Lr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yy(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 YD(e){return!!e&&(yy(e)||hy(e)!==null)}function Bo(e){let t=me(e)?oe(e):e,n=BP.get(t);if(n&&n.state===t.state)return n.outcome;let r=JD(t);return BP.set(t,{state:t.state,outcome:r}),r}var BP=new WeakMap;function JD(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(yy(n))return"failed";let r=QD(n);return r===void 0?"ok":XD(r)?"failed":ZD(r)}function QD(e){try{return JSON.parse(e)}catch{return}}function XD(e){return Lr(e)&&e.success===!1&&typeof e.error=="string"}function ZD(e){let t=Lr(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 hy(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Lr(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=eL.exec(ny(r.errorSummary));s&&(r.status=Number(s[1]));let o=Eo(r.errorSummary);if(o===null)return r;try{let i=JSON.parse(o),a=tL(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 eL=/^([1-5]\d{2}) Error\b/;function tL(e){let{message:t,error:n,detail:r}=e,s=[t,Lr(n)?n.message:void 0,Lr(r)?r.error:void 0,r];for(let o of s)if(typeof o=="string"&&o.trim())return o.trim()}function nL(e){return ny(e).replace(/\s+/g," ").trim()||e.trim()}function rL(e){let t=hy(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 sL(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function oL(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 iL(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=kP(n),n=AP(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 aL(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=Eo(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 $r(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Ko(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($r(i[1]),$r(i[2]),i[3]?$r(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($r(i[2]),$r(i[1])),n.length>=t)return n}return n}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function KP(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 qo(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 _y(e){if(!e)return[];let t=KP(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)?qo(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=qo(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?qo(r):[]}];if(Array.isArray(t)&&t.length>0){let s=t[0];if(gt(s)&&(s.title||s.url)){let o=qo(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=Ko(e);if(s.length>0)return[{query:"",sources:s.map(o=>({title:o.title,url:o.url,snippet:o.snippet}))}]}return[]}function Go(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function cL(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Go(e)}}function lL(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function uL(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 qP(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 GP(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=RP(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function pL(e,t){let n=WP(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?GP(r,qP(t)):[]}function WP(e){if(!e)return null;let t=KP(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=Ko(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 dL(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 gL={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 gL[ae(e)]}function Fr(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 mL={run:"Terminal",memory:"Memory"};function fL(e){let t=fn(e);return(t==="hidden"?void 0:mL[t])??Fr(e)}function Ur(e,t,n){return e===1?t:n}function by(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 zP(e){return e.length?Oo(e[0]):""}function je(e){return(e.state??{}).input??{}}var yL={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 hL(e){let t=Z(e.tool);if(t==="agent_task_update"||t==="task_update")switch(je(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return yL[t]??"message"}function HP(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 _L(e){let t=Z(e.tool);if(t==="triggers"){let r=je(e).action||"list";return HP(r)}let n=t.match(/^trigger_(.+)$/);return HP(n?n[1]:"list")}var bL={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 bL[Z(e.tool)]??"read"}var PL={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function xL(e){return PL[Z(e.tool)]??"open"}function mn(e){return e.every(t=>t===e[0])}var wL={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function vL(e){if(Z(e.tool)!=="memory")return"read";let n=je(e).command;return n&&wL[n]||"unknown"}var kL={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},AL={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 RL(e){let t=Xe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function CL(e){let t=je(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return TL(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return RL(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=dL(o);return i?Go(i):"a link"}return""}function TL(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function IL(e){let t=je(e).action;return t&&kL[t]||"Worked on an image"}function EL(e){let t=je(e).action;return t&&AL[t]||"Worked on a presentation"}function ML(e){return e.slice(0,e.indexOf(":"))}var OL={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},jL={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 DL(e){let t=Z(e.tool);if(t==="image_gen"){let n=je(e).action;return n&&OL[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=je(e).action;return n&&jL[n]||"presentation:unknown"}return"shown:result"}var LL=new Set(["create_slide","export_pdf","export_pptx"]);function $L(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=je(t).action;return r?LL.has(r)?"presentation":null:"presentation"}return null}var UL={"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`},VP={image:"image",video:"video",presentation:"presentation",shown:"result"};function FL(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[ML(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Ur(s,VP[r],`${VP[r]}s`)}`)}),`Worked on ${by(n)}`}function Nr(e,t){let n=t.map(We),r=n.length,s=zP(n);switch(e){case"explore":{let o=n.filter(i=>Z(i.tool)==="read").length;return o===r?`Read ${r} ${Ur(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=>ke(je(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} ${Ur(r,"query","queries")}`;if(i===0)return`Read ${r} ${Ur(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of _y(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} ${Ur(l,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=Z(i.tool);if(a==="image_gen")return IL(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return EL(i);let l=CL(i);return l?`Showed you ${l}`:"Showed you the result"}let o=n.map(DL);return mn(o)?UL[o[0]](r):FL(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(hL);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(vL);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(_L);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(xL);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 ${Fr(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>Fr(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${by(o)}`}}}function Sy(e,t){let n=t.map(We),r=zP(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=>Fr(a.tool))));return`Couldn't finish using ${by(i)}`}}}var YP=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),NL={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 BL(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Ir(t)||t}function KL(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 BL(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=NL[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:KL(s,r.objectKeys),tier:YP.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function Wo(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)&&Bo(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function Py(e){return`${e} ${e===1?"step":"steps"}`}function JP(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${Py(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${Py(n)}`:s===0?`${Py(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function xy(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]),Bo(s)!=="ok"&&(n+=1))}if(t.size===0)return JP(Wo(e),!1);let r=[...t].map(([s,o],i)=>{let a=Nr(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function qL(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 GL(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function WL(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 QP(e,t){let n=t.map(We),r=GL(n);return{id:n[0].callID,family:e,label:r==="error"?Sy(e,n):Nr(e,n),parts:t,status:r,durationMs:r==="running"?void 0:WL(n)}}function wy(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(QP(n,r)),n=null,r=[]};for(let o of e){let i=We(o),a=fn(i.tool);if(a!=="hidden"&&!Zs(i)){if(Tm(i.tool)){s(),t.push(QP(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function Ho(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function vy(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 wy(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=Ho(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 HL=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function VL(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 zL(e){let t=e.flatMap(s=>{let o=VL(s);return o?[o]:[]}).join(" ").trim();return t?HL.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function nx(e){return e?.info?.time??{}}function YL(e){let t=nx(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Vo=6e4,JL=10080*Vo,XP=1440;function ZP(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 QL(e,t){let n=t.getTime()-e.getTime(),r=n/Vo,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<XP)return s(Math.round(r/60),"hour");let o=(n-(ZP(t)-ZP(e)))/Vo;return s(Math.round(o/XP),"day")}function rx(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 ex=new Map;function XL(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=ex.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),ex.set(r,s)),s}function zo(e,t,n){return XL(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?ZL(r.value,n):r.value).join("")}function ZL(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function tx(e,t){return zo(e,{year:"numeric"},t)}function e$(e,t,n={}){let r=rx(e);if(!r)return"";let s=i=>zo(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<Vo?"just now":o<JL?QL(r,new Date(t)):s(tx(r,n)!==tx(new Date(t),n))}function t$(e,t={}){let n=rx(e);if(!n)return"";let r=zo(n,{month:"long",day:"numeric",year:"numeric"},t),s=zo(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function ky(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!Im(o)){if(Oe(o)){s(),n.push({kind:"text",part:o});continue}if(ee(o)&&(Em(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function n$(e){let t=fe(e);return t==="show"||t==="show_user"}function Ay(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"&&n$(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var r$=["title","description","path","url","content","language","aspect_ratio","attachment"];function sx(e,t){if(!t||typeof t!="object")return null;let n=t;if(cr(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of r$){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function s$(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 Ry(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=s$(s.items),i=o?o.map(a=>sx(n.callID,a)).filter(a=>!!a):[sx(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 Cy(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Br=e=>"id"in e?e.id:e.userMessage.info.id,ox=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,o$=e=>e.time?.completed;function i$(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function a$(e,t){let n=Br(e);return t.pendingTurnIds.has(n)||ox(e)===0&&t.pendingPromptIds.has(n)}function c$(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Br(r)));if(t)return Br(t);let n=e.turns.findIndex(r=>a$(r,e));return n<=0?null:Br(e.turns[n-1])}function l$(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function u$(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 p$(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Cy({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function d$(e,t){for(let n=e.length-1;n>=0;n--){let r=Br(e[n]);if(t(r))return ox(e[n])===0?r:null}return null}function Ty(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(!o$(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 g$(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 m$(e,t){return!t||!e?!1:e.type!=="idle"}function f$(e,t){return!e&&!!t}function y$(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Se(n.error)?.message||ye(n.error)}}function h$(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Tr(n.error)}}function _$(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Se(n.error)}}function Iy(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 b$=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=Iy(n.parts[r]);if(s)return s}}}function P$(e,t){let n=ee(e)?e:void 0;if(n&&b$.has(n.tool)&&n.state.status==="running"){let r=S$(t);return r||(t?.length?"Handing off to an agent...":void 0)}return Iy(e)}function Ey(e,t){for(let n=e.length-1;n>=0;n--){let r=P$(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function My(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 Oy=1.055;function ix(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 jy(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function ax(e,t,n,r){if(jy(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?ix(e.tokens,o):0}function cx(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function Yo(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}=cx(d.info);n+=ax(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=lx(g,t),f=g.tokens&&jy(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*Oy,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function lx(e,t){if(jy(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?ix({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function x$(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=cx(s),a=0,l=!1;for(let p of r.parts)p.type==="step-finish"&&(l=!0,a+=ax(p,o,i,t));l||(a+=lx(s,t)),n+=a}return n*Oy}function w$(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function v$(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function k$(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 A$(e){if(!(!e||e.type!=="retry"))return ye(e.message)}function R$(e){return(e.info.summary?.diffs?.length??0)>0}function ux(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 Dy(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(ux(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):ux(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function T$(e){let t=e==null?"":My(e);return t?`Worked for ${t}`:"Worked"}function px(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 I$(e){if(px(e))return e.assistantMessages[0].parts[0]}function E$(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=bP(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 M$(e){return e?e.split(`
84
- `).filter(n=>n.trim()).length<=3:!1}function O$(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 j$(e){if(!e)return[];let t=[],n=e.split(`
86
- `).filter(r=>r.trim());for(let r of n){let s=wP(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 D$(e,t){let n=mt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function L$(e,t){return t?"failed":e?"running":"done"}var $$={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function U$(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function F$(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(PP(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
80
+ `):de(t.new_source)),patch:o,additions:Lo(s?.additions)??i?.additions,deletions:Lo(s?.deletions)??i?.deletions})]}function CD(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 TD(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function LP(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=kD(r),i=wD(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=vD(s);m&&(i="error",a=m)}let l=ae(e),p=t.input??{},d="metadata"in t&&$o(t.metadata)||{},g=$o(d.diagnostics);return{name:e,kind:l,title:n||Do(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:RD(l,p,d),diff:de(d.patch)??de(d.diff),diagnostics:g,answers:l==="question"?TD(d):void 0,childSessionId:Dr({tool:e,state:t})}}function dy(e){let t=me(e)?oe(e):e;return LP(t.tool,t.state)}function ID(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function ED(e){return{kind:"reasoning",id:e.id,text:e.text}}function MD(e){return{kind:"tool",id:e.id,tool:LP(e.tool,e.state)}}function OD(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 jD(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function DD(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function LD(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function $D(e){return{kind:"agent",id:e.id,name:e.name}}function UD(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:ye(e.error),createdAt:e.time.created}}function FD(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function ND(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function BD(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function gy(e){switch(e.type){case"text":return ID(e);case"reasoning":return ED(e);case"tool":return MD(e);case"file":return OD(e);case"subtask":return jD(e);case"patch":return DD(e);case"snapshot":return LD(e);case"agent":return $D(e);case"retry":return UD(e);case"compaction":return FD(e);case"step-start":return ND(e);case"step-finish":return BD(e);default:return{kind:"unknown",raw:e}}}function KD(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 qD(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function Uo(e){let t=e.parts.map(gy),n=e.info.role==="assistant"?e.info.error:void 0,r=KD(n),s=!r&&!t.some(qD);return{parts:t,error:r,isEmpty:s}}var my=Ve+BigInt(1),$P=my/BigInt(2);function Fo(e){return BigInt(Math.trunc(e))*Zt}function fy(e,t){let r=t-(t&Ve)+e;return r-t>$P?r-=my:t-r>$P&&(r+=my),r}function UP(e,t){let n=It(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return fy(n,t);let s=Fo(r),o=fy(n,s);return(o>s?o-s:s-o)<=ct?o:s}function FP(e){return It(e)===null?1:0}function NP(e,t){return e<t?-1:e>t?1:0}function GD(e,t){return No(e,t,Fo(Date.now()))}function yy(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 Fo(t??Date.now())}function No(e,t,n){let r=FP(e.info.id),s=FP(t.info.id);if(r!==s)return r-s;if(r===0){let a=UP(e,n),l=UP(t,n);return a!==l?a<l?-1:1:NP(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:NP(e.info.id,t.info.id)}function WD(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 HD(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 BP(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(...BP(e,s));return r}function VD(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=yy(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:No(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:YD(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 Lr=new Map,zD=256;function YD(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=Lr.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(Lr.size>=zD){let a=Lr.keys().next().value;a!==void 0&&Lr.delete(a)}return Lr.set(s,i),i}function JD(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function QD(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(Oe(n)&&n.text?.trim())return n}}function XD(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function ZD(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!te(o))continue;let i=o,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:o,message:s})}return r}function KP(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function hy(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&&KP(n.error)}return!1}function $r(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _y(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 eL(e){return!!e&&(_y(e)||by(e)!==null)}function Bo(e){let t=me(e)?oe(e):e,n=qP.get(t);if(n&&n.state===t.state)return n.outcome;let r=tL(t);return qP.set(t,{state:t.state,outcome:r}),r}var qP=new WeakMap;function tL(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(_y(n))return"failed";let r=nL(n);return r===void 0?"ok":rL(r)?"failed":sL(r)}function nL(e){try{return JSON.parse(e)}catch{return}}function rL(e){return $r(e)&&e.success===!1&&typeof e.error=="string"}function sL(e){let t=$r(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 by(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!$r(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=oL.exec(sy(r.errorSummary));s&&(r.status=Number(s[1]));let o=Eo(r.errorSummary);if(o===null)return r;try{let i=JSON.parse(o),a=iL(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 oL=/^([1-5]\d{2}) Error\b/;function iL(e){let{message:t,error:n,detail:r}=e,s=[t,$r(n)?n.message:void 0,$r(r)?r.error:void 0,r];for(let o of s)if(typeof o=="string"&&o.trim())return o.trim()}function aL(e){return sy(e).replace(/\s+/g," ").trim()||e.trim()}function cL(e){let t=by(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 lL(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function uL(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 pL(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=RP(n),n=CP(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 dL(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=Eo(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 Ur(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function Ko(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(Ur(i[1]),Ur(i[2]),i[3]?Ur(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(Ur(i[2]),Ur(i[1])),n.length>=t)return n}return n}function gt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function GP(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 qo(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 Sy(e){if(!e)return[];let t=GP(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)?qo(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=qo(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?qo(r):[]}];if(Array.isArray(t)&&t.length>0){let s=t[0];if(gt(s)&&(s.title||s.url)){let o=qo(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=Ko(e);if(s.length>0)return[{query:"",sources:s.map(o=>({title:o.title,url:o.url,snippet:o.snippet}))}]}return[]}function Go(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function gL(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return Go(e)}}function mL(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function fL(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 WP(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 HP(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=TP(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function yL(e,t){let n=VP(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?HP(r,WP(t)):[]}function VP(e){if(!e)return null;let t=GP(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=Ko(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 hL(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 _L={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 yn(e){return _L[ae(e)]}function Nr(e){let t=ee(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var bL={run:"Terminal",memory:"Memory"};function SL(e){let t=yn(e);return(t==="hidden"?void 0:bL[t])??Nr(e)}function Fr(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 JP(e){return e.length?Oo(e[0]):""}function je(e){return(e.state??{}).input??{}}var PL={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 xL(e){let t=ee(e.tool);if(t==="agent_task_update"||t==="task_update")switch(je(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return PL[t]??"message"}function zP(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 wL(e){let t=ee(e.tool);if(t==="triggers"){let r=je(e).action||"list";return zP(r)}let n=t.match(/^trigger_(.+)$/);return zP(n?n[1]:"list")}var kL={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 vL(e){return kL[ee(e.tool)]??"read"}var AL={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function RL(e){return AL[ee(e.tool)]??"open"}function fn(e){return e.every(t=>t===e[0])}var CL={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function TL(e){if(ee(e.tool)!=="memory")return"read";let n=je(e).command;return n&&CL[n]||"unknown"}var IL={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},EL={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 ML(e){let t=Xe(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function OL(e){let t=je(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return jL(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return ML(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=hL(o);return i?Go(i):"a link"}return""}function jL(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function DL(e){let t=je(e).action;return t&&IL[t]||"Worked on an image"}function LL(e){let t=je(e).action;return t&&EL[t]||"Worked on a presentation"}function $L(e){return e.slice(0,e.indexOf(":"))}var UL={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},FL={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 NL(e){let t=ee(e.tool);if(t==="image_gen"){let n=je(e).action;return n&&UL[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=je(e).action;return n&&FL[n]||"presentation:unknown"}return"shown:result"}var BL=new Set(["create_slide","export_pdf","export_pptx"]);function KL(e){let t=We(e),n=ee(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=je(t).action;return r?BL.has(r)?"presentation":null:"presentation"}return null}var qL={"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`},YP={image:"image",video:"video",presentation:"presentation",shown:"result"};function GL(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[$L(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Fr(s,YP[r],`${YP[r]}s`)}`)}),`Worked on ${Py(n)}`}function Br(e,t){let n=t.map(We),r=n.length,s=JP(n);switch(e){case"explore":{let o=n.filter(i=>ee(i.tool)==="read").length;return o===r?`Read ${r} ${Fr(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(je(a))).filter(Boolean)).size||r,i=n.every(a=>ee(a.tool)==="write")?"Wrote":"Updated";return o===1?s?`${i} ${s}`:`${i} a file`:`${i} ${o} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"script":return r===1?"Ran a script":`Ran ${r} scripts`;case"web":{let o=p=>{let d=ee(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(o).length;if(i===r)return`Searched the web \xB7 ${r} ${Fr(r,"query","queries")}`;if(i===0)return`Read ${r} ${Fr(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of Sy(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} ${Fr(l,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return DL(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return LL(i);let l=OL(i);return l?`Showed you ${l}`:"Showed you the result"}let o=n.map(NL);return fn(o)?qL[o[0]](r):GL(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(xL);if(fn(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(TL);if(fn(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(vL);if(fn(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(wL);if(fn(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(RL);if(fn(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 ${Nr(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>Nr(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${Py(o)}`}}}function xy(e,t){let n=t.map(We),r=JP(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let s=ee(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${s} ${r}`:`Couldn't ${s} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let s=n.filter(a=>a.state?.status==="error"),o=s.length?s:n,i=Array.from(new Set(o.map(a=>Nr(a.tool))));return`Couldn't finish using ${Py(i)}`}}}var QP=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),WL={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 HL(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Er(t)||t}function VL(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 HL(r,s.trim())}}function hn(e){let t=me(e)?oe(e):e;if(we(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!te(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=fe(t.tool),r=WL[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:VL(s,r.objectKeys),tier:QP.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function Wo(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(hn(o).tier==="plumbing"){r=!0;continue}if(we(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,te(o)&&Bo(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function wy(e){return`${e} ${e===1?"step":"steps"}`}function XP(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${wy(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${wy(n)}`:s===0?`${wy(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function ky(e){let t=new Map,n=0;for(let s of e){if(!te(s)||hn(s).tier==="plumbing")continue;let o=yn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),Bo(s)!=="ok"&&(n+=1))}if(t.size===0)return XP(Wo(e),!1);let r=[...t].map(([s,o],i)=>{let a=Br(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function zL(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 YL(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function JL(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 ZP(e,t){let n=t.map(We),r=YL(n);return{id:n[0].callID,family:e,label:r==="error"?xy(e,n):Br(e,n),parts:t,status:r,durationMs:r==="running"?void 0:JL(n)}}function vy(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(ZP(n,r)),n=null,r=[]};for(let o of e){let i=We(o),a=yn(i.tool);if(a!=="hidden"&&!Zs(i)){if(Em(i.tool)){s(),t.push(ZP(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function Ho(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function Ay(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 vy(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=Ho(a);continue}if(o(),te(a)){s.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}o(),i();for(let a=0;a<n.length-1;a++){let l=n[a];l.kind==="thought"&&(l.running=!1)}return n}var QL=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function XL(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 ZL(e){let t=e.flatMap(s=>{let o=XL(s);return o?[o]:[]}).join(" ").trim();return t?QL.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function sx(e){return e?.info?.time??{}}function e$(e){let t=sx(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Vo=6e4,t$=10080*Vo,ex=1440;function tx(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 n$(e,t){let n=t.getTime()-e.getTime(),r=n/Vo,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<ex)return s(Math.round(r/60),"hour");let o=(n-(tx(t)-tx(e)))/Vo;return s(Math.round(o/ex),"day")}function ox(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 nx=new Map;function r$(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=nx.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),nx.set(r,s)),s}function zo(e,t,n){return r$(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?s$(r.value,n):r.value).join("")}function s$(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function rx(e,t){return zo(e,{year:"numeric"},t)}function o$(e,t,n={}){let r=ox(e);if(!r)return"";let s=i=>zo(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<Vo?"just now":o<t$?n$(r,new Date(t)):s(rx(r,n)!==rx(new Date(t),n))}function i$(e,t={}){let n=ox(e);if(!n)return"";let r=zo(n,{month:"long",day:"numeric",year:"numeric"},t),s=zo(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function Ry(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!Mm(o)){if(Oe(o)){s(),n.push({kind:"text",part:o});continue}if(te(o)&&(Om(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function a$(e){let t=fe(e);return t==="show"||t==="show_user"}function Cy(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"&&a$(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var c$=["title","description","path","url","content","language","aspect_ratio","attachment"];function ix(e,t){if(!t||typeof t!="object")return null;let n=t;if(lr(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of c$){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function l$(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 Ty(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=l$(s.items),i=o?o.map(a=>ix(n.callID,a)).filter(a=>!!a):[ix(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 Iy(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Kr=e=>"id"in e?e.id:e.userMessage.info.id,ax=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,u$=e=>e.time?.completed;function p$(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function d$(e,t){let n=Kr(e);return t.pendingTurnIds.has(n)||ax(e)===0&&t.pendingPromptIds.has(n)}function g$(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Kr(r)));if(t)return Kr(t);let n=e.turns.findIndex(r=>d$(r,e));return n<=0?null:Kr(e.turns[n-1])}function m$(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function f$(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 y$(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Iy({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function h$(e,t){for(let n=e.length-1;n>=0;n--){let r=Kr(e[n]);if(t(r))return ax(e[n])===0?r:null}return null}function Ey(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(!u$(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 _$(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 b$(e,t){return!t||!e?!1:e.type!=="idle"}function S$(e,t){return!e&&!!t}function P$(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Se(n.error)?.message||ye(n.error)}}function x$(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Ir(n.error)}}function w$(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Se(n.error)}}function My(e){if(e){if(te(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(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 k$=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function v$(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=My(n.parts[r]);if(s)return s}}}function A$(e,t){let n=te(e)?e:void 0;if(n&&k$.has(n.tool)&&n.state.status==="running"){let r=v$(t);return r||(t?.length?"Handing off to an agent...":void 0)}return My(e)}function Oy(e,t){for(let n=e.length-1;n>=0;n--){let r=A$(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function jy(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 Dy=1.055;function cx(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 Ly(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function lx(e,t,n,r){if(Ly(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?cx(e.tokens,o):0}function ux(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function Yo(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}=ux(d.info);n+=lx(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=px(g,t),f=g.tokens&&Ly(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*Dy,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function px(e,t){if(Ly(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?cx({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function R$(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=ux(s),a=0,l=!1;for(let p of r.parts)p.type==="step-finish"&&(l=!0,a+=lx(p,o,i,t));l||(a+=px(s,t)),n+=a}return n*Dy}function C$(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function T$(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function I$(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 E$(e){if(!(!e||e.type!=="retry"))return ye(e.message)}function M$(e){return(e.info.summary?.diffs?.length??0)>0}function dx(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 O$(e){return e.kind==="text"&&!e.part.text?.trim()}function $y(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(dx(o)||O$(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):dx(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function j$(e){let t=e==null?"":jy(e);return t?`Worked for ${t}`:"Worked"}function gx(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 te(s)&&s.tool==="bash"}function D$(e){if(gx(e))return e.assistantMessages[0].parts[0]}function L$(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 $$(e){return e?e.split(`
84
+ `).filter(n=>n.trim()).length<=3:!1}function U$(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 F$(e){if(!e)return[];let t=[],n=e.split(`
86
+ `).filter(r=>r.trim());for(let r of n){let s=vP(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 N$(e,t){let n=mt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function B$(e,t){return t?"failed":e?"running":"done"}var K$={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function q$(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function G$(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(wP(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 N$={add:{...mt.write,icon:"create"},delete:{...mt.delete,icon:"delete"},move:{...mt.rename,icon:"edit"},update:{...mt.edit,icon:"edit"}},dx={...mt.change,icon:"edit"};function B$(e){if(e.length===0)return dx;let t=gx(e[0]);for(let n=1;n<e.length;n++)if(gx(e[n])!==t)return dx;return N$[t]}function gx(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function K$(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 Ly(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 q$(e){if(!e)return null;let t=Mr(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=ey(e,"content");if(r!==null){let o=r.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 W$={add:{...mt.write,icon:"create"},delete:{...mt.delete,icon:"delete"},move:{...mt.rename,icon:"edit"},update:{...mt.edit,icon:"edit"}},mx={...mt.change,icon:"edit"};function H$(e){if(e.length===0)return mx;let t=fx(e[0]);for(let n=1;n<e.length;n++)if(fx(e[n])!==t)return mx;return W$[t]}function fx(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function V$(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 Uy(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 z$(e){if(!e)return null;let t=Or(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=ny(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=ey(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 G$(e){let t=_P(e,"skill_content");return t!==null?t.trim():e}function mx(e){let t=Mr(e,"<skill_files>","</skill_files>");return t===null?[]:SP(t,"<file>","</file>").map(n=>n.trim())}function W$(e){let t=hP(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 H$(e){return xP(e,["Base directory","Directory","Skill directory"])?.trim()??""}function fx(e){return Xe(W$(e)||H$(e))}function V$(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 z$="skills";function Y$(e){let t=yP(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?`${z$}/${r}`:""}function J$(e,t,n){let s=Xe(t?.trim()??"")||fx(e)||Y$(n),o=mx(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 Q$=4e3;function Kr(e,t=Q$){return e.length>t?`${e.slice(0,t)}
94
- \u2026`:e}function yx(e){if(e!==void 0)try{return Kr(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 X$(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 Z$=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Uy(e){let t=e.match(Z$);return t?Number(t[1]):void 0}function e0(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 t0=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function n0(e){let t=-1;for(let n of t0){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}function r0(e){let t=ne(e.input?.command)??"",n=e.output??"",r=Uy(n),o=iy(n0(e0(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 Fy(e){return ne(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function s0(e){let t=e.status==="error"?e.error:e.output&&Kr(e.output)||void 0;return{kind:"file-read",path:Fy(e),preview:t}}function o0(e){let t=ne(e.input?.content),n=e.status==="error"?e.error:Kr(t??e.output??"")||void 0;return{kind:"file-write",path:Fy(e),preview:n}}var i0=256*1024;function a0(e,t){if(e.length+t.length>i0)return;let n=e.split(`
92
+ `);return{path:n,type:"file",content:o}}let s=ny(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 Y$(e){let t=SP(e,"skill_content");return t!==null?t.trim():e}function yx(e){let t=Or(e,"<skill_files>","</skill_files>");return t===null?[]:xP(t,"<file>","</file>").map(n=>n.trim())}function J$(e){let t=bP(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 Q$(e){return kP(e,["Base directory","Directory","Skill directory"])?.trim()??""}function hx(e){return Xe(J$(e)||Q$(e))}function X$(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 Z$="skills";function e0(e){let t=_P(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?`${Z$}/${r}`:""}function t0(e,t,n){let s=Xe(t?.trim()??"")||hx(e)||e0(n),o=yx(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 n0=4e3;function qr(e,t=n0){return e.length>t?`${e.slice(0,t)}
94
+ \u2026`:e}function _x(e){if(e!==void 0)try{return qr(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 _n(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function r0(e){let t=ne(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=_n(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=_n(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 s0=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Ny(e){let t=e.match(s0);return t?Number(t[1]):void 0}function o0(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 i0=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function a0(e){let t=-1;for(let n of i0){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}function c0(e){let t=ne(e.input?.command)??"",n=e.output??"",r=Ny(n),o=cy(a0(o0(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 By(e){return ne(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function l0(e){let t=e.status==="error"?e.error:e.output&&qr(e.output)||void 0;return{kind:"file-read",path:By(e),preview:t}}function u0(e){let t=ne(e.input?.content),n=e.status==="error"?e.error:qr(t??e.output??"")||void 0;return{kind:"file-write",path:By(e),preview:n}}var p0=256*1024;function d0(e,t){if(e.length+t.length>p0)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 c0(e){let t=jo(e.input),n=t.map(([s,o])=>a0(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:Fy(e),diff:r}}var _x=/^Found\s+(\d+)\s+match/i,l0=/^(\/[^:]+?):\s*/,hx=/Line\s+(\d+):/g;function u0(e){let t=e.trim(),n=t.match(_x),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(l0);if(!a)continue;let l=a[1],p=i.slice(a[0].length),d=[],g;for(hx.lastIndex=0;(g=hx.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 p0(e){return e.trim().split(`
97
- `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function d0(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=_x.test(e.output.trim())?u0(e.output):p0(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function g0(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 $y(e){let t=hn(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function m0(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map($y)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map($y)};let n=hn(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map($y)}:{kind:"todo",items:[]}}function f0(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 y0(e){let n=e.input&&Object.keys(e.input).length>0?yx(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Kr(e.outputParsed):yx(e.outputParsed):e.outputText!==void 0?r=Kr(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function bx(e){switch(ae(e.name)){case"web_search":return X$(e);case"bash":return r0(e);case"read":return s0(e);case"write":return o0(e);case"edit":return c0(e);case"grep":case"glob":return d0(e);case"task":return g0(e);case"todowrite":return m0(e);case"question":return f0(e);default:return y0(e)}}var h0=new Set(["AbortError","MessageAbortedError"]),_0=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],b0=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function Sx(e){let t=e.toLowerCase();return b0.some(n=>t.includes(n))?!1:_0.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 qr(e){if(typeof e=="string")return Sx(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&h0.has(n))return!0;let r=S0(t);return typeof r=="string"?Sx(r):!1}var Px=["user","runtime-disposed","orphan-finalized","wake"],P0=["orphan-finalized","wake"];function x0(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 Px.includes(n)?n:void 0}var Gr="kortix-active-instance",xx=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function wx(e){return xx.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 w0(e){let t=_n(e);return!!t&&t.innerPath===""}function v0(e){let t=_n(e);return!t||!t.innerPath?e:t.innerPath}function vx(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 wx(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function kx(e){return e?_n(e)?.instanceId??null:null}function k0(){return typeof window>"u"?null:kx(window.location.pathname)||Ax()}function Ax(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Gr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function A0(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Gr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Gr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Gr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function R0(e,t){return t?vx(t,e):e}function C0(e){let t=_n(e);return t?t.innerPath||"/dashboard":e}function Hr(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 Ny(e){let t=Hr(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 T0=Ny;function Jo(e){let t=Ny(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var I0=Jo;function Rx(e){return Jo(e)!==null}var E0=Rx,M0=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],O0=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],j0=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function Cx(e){return j0.test(Hr(e))}function bn(e){let t=Hr(e);return t?Cx(t)||M0.some(n=>n.test(t)):!1}var D0=/server url not ready|sandbox is still loading/i;function L0(e){return D0.test(Hr(e))||bn(e)}var Wr=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 Tx(e){let t=Jo(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=Hr(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 $0=Tx;function By(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 U0(e,t){return e.external_id?`${ot()}/p/${e.external_id}/${t}`:null}async function F0(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function Ix(e){let t=await nr();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:Gs(r,s,o),created:!0}}async function N0(){return(await nr().catch(()=>null))?.sandbox??null}async function B0(e){return{sandbox:(await Ix(e)).sandbox}}async function K0(e){let t=tr(e);if(!t)return null;try{let n=await lm(t);return n?Gs(await wt(n.project_id),n,null):(await nr(t))?.sandbox??null}catch{return null}}async function q0(e,t){throw await Ws(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function G0(e){let t=tr(e);return(await cm().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function W0(){return null}async function H0(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Ws(e);if(!t)throw new Error("Project session sandbox not found");await Yn(t.projectId,t.sessionId)}async function V0(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Ws(e);if(!t)throw new Error("Project session sandbox not found");await Jn(t.projectId,t.sessionId)}async function z0(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function Y0(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function Ky(e,t,n){let r=By(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 J0(e,t){return Ky(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function Q0(e,t,n,r="member"){await Ky(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function X0(e,t,n){await Ky(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var qy="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function Z0(e){throw N("getInvite",qy)}async function eU(e){throw N("acceptInvite",qy)}async function tU(e){throw N("declineInvite",qy)}async function nU(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function rU(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function sU(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function oU(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function iU(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function aU(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var Ex=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function cU(e){return Ex.includes(e)}async function lU(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 uU(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 Mx(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function Mx(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 pU(){return(await Le(`${ot()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function dU(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function gU(e){}async function mU(e){}async function fU(e){return{serverTypes:[],location:e||"hel1"}}async function yU(e){throw new Error("Retired instance provisioning is unavailable. Create a project session on platinum (or the legacy daytona fallback).")}async function hU(e){throw N("deleteInstance")}async function _U(e,t){}async function bU(){throw N("claimComputer")}async function SU(e){return null}function PU(e,t){throw N("getSandboxProvisionStreamUrl")}var Vr=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function Ox(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 jx(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Dx(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:Ox(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 jx(s);if(!s.ok)throw new Vr(Dx(s,o),s.status,o);return o}function xU(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 wU(e,t){return te(`/marketplace/items${xU(t)}`,e)}function vU(e){return te("/marketplace/marketplaces",e)}function kU(e,t){return te(`/marketplace/items/${encodeURIComponent(e)}`,t)}function AU(e,t,n){return te(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function RU(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 TU(e){return te("/auth/logout",e,{method:"POST",body:{}})}function IU(e,t){return te(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function EU(e,t){return te("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function MU(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function OU(e,t){return te(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function jU(e,t,n={}){return te(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function DU(e,t){return te(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function LU(e,t,n,r){return te(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function $U(e,t){return te(`/p/public-share/${encodeURIComponent(e)}`,t)}function UU(e,t,n){return te(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function FU(e){return te("/system/maintenance",e)}function NU(e,t){return te("/system/maintenance",t,{method:"PUT",body:e})}function BU(e){return te("/user-roles",e)}function KU(e,t){return te("/system/demo-request",t,{method:"POST",body:e})}async function qU(e,t,n){let r=await fetch(`${qe(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Ht(t)}`,{headers:Ox(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await jx(r);throw new Vr(Dx(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 GU(e,t){throw N("openStressTestStream")}function WU(e,t){throw N("buildPublicTemplateUrl")}async function HU(e,t,n){throw N("getPublicTemplate")}var VU="kortix:connect-link:";function Gy(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`${VU}${t.toString(36)}${n.toString(36)}`}function zU(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(Gy(i));if(!a)return;let l=JSON.parse(a);if(Date.parse(l.expires_at)<=Date.now()){t.removeItem(Gy(i));return}return l}catch{return}},o=(i,a)=>{if(t)try{t.setItem(Gy(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 Lx="Could not start the connect flow.";async function YU(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:Lx}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:Lx};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var $x=3e3,Ux=5e3,Fx=5*6e4;function JU(e,t){let n=e===0?$x:Ux;return t+n>Fx?null:n}function QU(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 XU(){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 ZU(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 eF(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 tF(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 nF(){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 iQ="1";var rF="kortix.query-cache";function Bx(e){return!!e&&typeof e.then=="function"}function Nx(e){return Bx(e)?e:Promise.resolve()}function sF(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 oF(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:l=rF,now:p=()=>Date.now()}=e,d=`${l}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),P=()=>{try{return Nx(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},k=(x,v)=>{if(!v)return 0;let C;try{C=JSON.parse(v)}catch{return P(),0}if(!C||C.v!==s||C.user!==n||!Array.isArray(C.queries)||p()-C.at>o)return P(),0;let D=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"}),D+=1)}return D},T=x=>x.getQueryCache().getAll().filter(v=>v.state.data!==void 0&&r(v.queryKey)).map(v=>({k:v.queryKey,d:v.state.data,t:v.state.dataUpdatedAt})).sort((v,C)=>C.t-v.t),b=(x,v)=>{let C=[],D=0;for(let R of x){let L=JSON.stringify(R).length+1;D+L>v||(C.push(R),D+=L)}return C},S=async x=>{let v=b(T(x),i);for(;;){let C={v:s,user:n,at:p(),queries:v};try{await Nx(t.setItem(d,JSON.stringify(C)));return}catch{if(v.length===0)return;v=v.slice(0,Math.floor(v.length/2))}}},O=()=>{f!==null&&(clearTimeout(f),f=null)},y=()=>{O();let x=g;return!x||!m||(m=!1,h=h.then(()=>S(x)).catch(()=>{})),h},w=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,y()},a))};return{storageKey:d,restore(x){let v;try{v=t.getItem(d)}catch{return 0}return Bx(v)?v.then(C=>k(x,C)).catch(()=>0):k(x,v)},persist(x){g=x,m=!0;let v=x.getQueryCache().subscribe(C=>{C.type!=="updated"&&C.type!=="removed"&&C.type!=="added"||r(C.query.queryKey)&&w()});return()=>{v(),g===x&&(g=null,O())}},flush(){return y()},async clear(){O(),g=null,m=!1,await h,await P()}}}function iF(){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 Kx="/kortix/part/";function qx(e){return typeof e=="string"&&e.startsWith(Kx)}async function aF(e){if(!qx(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 Gx(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 cF(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 Wy(e,t){return cF(e,t)?(t?Gx(t):null)??Gx(e):null}function zr(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 lF(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var uF=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function pF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dF(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(pF).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function gF(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function Wx(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function mF(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:uF.test(n.hostname)?t.backendUrls.some(r=>{let s=gF(r);return s!==null&&Wx(s)===Wx(n)}):t.templates.some(r=>dF(n.origin,r))}async function Hx(e,t={}){if(!zr(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 mF(e,{templates:db(),backendUrls:r})}async function Vx(e,t={}){let n=Wy(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 fF(e,t={}){if(zr(e)){if(!await Hx(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 Vx(e,t),e}var yF=3e3;function zx(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 hF(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 zx(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function _F(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function bF(e,t){throw N("buildPresentationTemplatePdfUrl")}function SF(e,t){throw N("buildPresentationTemplateImageUrl")}function Yx(e,t){return`${_F(e)}/presentation/convert-to-${t}`}async function PF(e,t,n,r){let s=Yx(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,P)=>{let k=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(k),P(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 xF(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 wF(e){return e==="unreachable"}function vF(e){return!e||e.status===0?"unknown":e.ok&&df(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var Jx=1e4,kF={connection:"unknown",faultSinceMs:null};function AF(e,t,n,r=Jx){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 Qx({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<Qo,l=!!t&&i-t.atMs<ei;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<=Xo,streamFresh:!!s&&i-s.atMs<=Sn,inboxFresh:!!n&&i-n.atMs<=Zo,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 Hy(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 RF(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"&&!Hy(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=>!Hy(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 TF(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 IF(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,P=l&&!n&&s.atMs>=p,k=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(P&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:Pn(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(k)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 Xx(e){let t=Qx(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=RF(e,t,s,o);if(i)return i;let{result:a,openTurn:l}=CF(e,t,s,o);return a??TF(e,t,o)??IF(e,t,l,o)}var Qo=6e4,Xo=45e3,Sn=45e3,Zo=1e4,EF=3e3,ei=15e3;function MF(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function OF(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 jF(e){return Xx(e)}function DF(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,l=[null,t?t.atMs+Qo:null,n?n.atMs+ei:null,r?r.atMs+Zo:null,s?s.atMs+Xo: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 Zx(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||qr({name:s.name??void 0,message:s.message})?null:s}var LF="SandboxMemoryGuard";function $F(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=Zx(e,t);if(r?.message){if(r.name!==LF)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 UF=6e4;function FF(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function NF(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var ew=9e4;function BF(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+ew}var KF=75e3,qF=2,GF=2e4;function Vy(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function WF(e){return e.filter(t=>t!=null).join("|")}function HF(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function VF(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Vy(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Vy(),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=HF(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 zF={"retry-start":"retrying",restart:"restarting"};function YF(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${zF[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function JF(e){return e===1?"once":e===2?"twice":`${e} times`}function QF(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 ${JF(t)}`),`Tried: ${r.join(", then ")}.`}var XF={"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 tw(e){return!!(e.metadata??{}).legacy_migration}function ZF(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 tw(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function eN(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 tN={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 nN(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function ti(e){return e.runtime_sessions??e.opencode_sessions??[]}function nw(e){let t=ti(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 rN(e){let t=nw(e);return t?ti(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 sN(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=>ti(r).some(s=>s.id===t))??null)}var oN=new Set;function rw(e){for(let t of[...oN])try{t(e)}catch{}}var cw={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 lw=e=>Object.values(e.ext??{}).find(t=>t.version===ve),uw=e=>!!e&&lw(e)!==void 0,pw=e=>{let t=lw(e);return t?t.native_id??null:e.thread_id};function dw(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:pw(t),hasMessages:n,empty:!n&&e.older[t.thread_id]===!1}}var sw=new WeakMap;function gw(e,t){let n=pw(e),r=sw.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=Qs({...cw,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return sw.set(t,{native:n,rows:o}),o}var zy=e=>e.info.time?.created;var iN=(e,t)=>(zy(e)??-1/0)-(zy(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var ow=new WeakMap,iw=new WeakMap,mw=e=>typeof e=="object"&&e!==null,aN=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,cN=e=>e.info.role==="user"&&e.parts.some(t=>mw(t)&&t.type==="compaction"),lN=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},aw=new WeakMap;function uN(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(!mw(p)||a.type==="compaction")return a;let d=`${s}|${l}|${a.id}`,g=aw.get(p);return g&&g.key===d?(o=!0,g.block):(aw.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function pN(e){let t=new Map,n=new Set;for(let r of e){if(!cN(r))continue;let s=e.find(o=>!n.has(o)&&lN(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function dN(e,t,n,r,s){let o=ow.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=Xs({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=uN(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 ow.set(n,p),p}function fw(e,t,n){let r=iw.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(iN),{paired:o,used:i}=pN(s),a={tool_input:0,cut_point:0,attachment:0},l=[];for(let m of s){if(i.has(m))continue;let f=dN(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=aN(s.map(zy).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=l.filter(m=>m.role==="user"&&m.kind==="turn"),g={...cw,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:ve,native_id:t}}}]};return iw.set(n,{sessionId:e,native:t,log:g}),g}var Yy=new WeakMap,xn=new WeakMap,yw=new WeakMap;function ni(e){let t,n=xn.get(e);return n&&(t=gN(n).get(e.id)),t?(Yy.set(t,e),t):(e.type!=="harness"?t=Rm(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=yw.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},yw.set(e,t)),t&&Yy.set(t,e),t)}var Yr=e=>Yy.get(e),Ot=e=>e.flatMap(t=>ni(t)??[]),hw=new WeakMap;function gN(e){let t=hw.get(e);return t||hw.set(e,t=new Map(ft(e)[0]?.parts.map(n=>[n.id,n]))),t}var _w=new Map;function ft(e){let t=_w.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:""},_w.set(e.thread_id,t)),gw(t,e)}var mN="kortix-v1-import",Jy={schema:ce,v:1};function ri(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",fN=e=>e.status==="pending"||e.status==="running",Xy=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function vw(e,t){let n=Xy(e);return!fN(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var bw=new WeakMap;function kw(e,t){let n=bw.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={...Jy,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 bw.set(e,s),s}var Sw=new WeakMap;function yN(e){let t=Sw.get(e);return t||(t={...Jy,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:[]},Sw.set(e,t)),t}var Pw=new WeakMap;function hN(e){let t=Pw.get(e);return t||(t={...Jy,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:[]},Pw.set(e,t)),t}var _N=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function bN(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 P=r.get(g.message_id);P&&!t.has(g.message_id)&&(l=P,i.has(P)||i.set(P,i.size),P.user.kind==="compaction"&&(p=P));continue}if(g.role!=="assistant"||_N(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 P=a.get(p);P||(P={user:hN(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,P)),f=P}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:yN(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 PN(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 Aw(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=Tr(r);return{code:n.error.code,message:s?.message||ye(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function xN(e,t,n){return e.length&&e.every(t)?Yo(e.flatMap(r=>ft(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:Zy(e,n)}function Zy(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 Yo(n,t)??null}function wN(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 vN(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 kN(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)?jr(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var AN=e=>e.assistant.some(t=>t.blocks.some(n=>Qy(n)&&ae(n.name)==="todowrite"&&gn(n))),RN=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function CN(e,t){let n=e.map(s=>Aw(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 xw=new WeakMap,TN=[];function eh(e){let t=ri(e.messages,n=>n.role==="assistant");return!!t&&fy(ft(t))}var ww=new WeakMap;function IN(e){let t=ww.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},ww.set(e,t)}return t}function si(e,t={}){let n=t.hideOutOfContext?IN(e):e,r=new Set(t.held??TN),s=bN(n.messages,r),o=PN(s,t.liveMessageId),{list:i,hint:a}=t.foldCompactions?SN(s,o):{list:s,hint:o},l=ri(n.messages,b=>b.role==="assistant"),p=eh(n),d=Ty({turns:i.map(b=>({userMessage:{info:{id:b.user.message_id}},assistantMessages:b.assistant.map(S=>({info:{time:S.status==="streaming"?{}:{completed:1},error:S.error??void 0}}))})),hintMessageId:a,unrunTurnIds:r}),g=ri(i,AN)??i[i.length-1],m=i.map(b=>!b.partial&&RN(b.user)),f=CN(i,m),h=uw(n),P=b=>h||b.producer.harness===mN,k=t.threads??[],T=new Set(k.map(b=>b.thread_id));return i.map((b,S)=>{let O=t.busy===!0&&d.workingTurnId===b.user.message_id,y=d.pendingTurnIds.includes(b.user.message_id),w=p&&b.assistant.includes(l),x=f[S],v=`${b.partial}|${O}|${y}|${b===g}|${w}|${x?(x.continued?"c":"")+x.retries:"-"}`,C=xw.get(b.user);if(C&&C.key===v&&C.pricing===t.pricing&&C.heads===t.threads&&C.assistant.length===b.assistant.length&&C.assistant.every((j,q)=>j===b.assistant[q]))return C.turn;let D=b.assistant.flatMap(j=>j.blocks);for(let j of b.assistant)for(let q of j.blocks)xn.set(q,j);let R=kN(b,D,k,T),L=b.assistant[b.assistant.length-1],pe={internal:m[S],autoRetry:x,id:b.user.message_id,user:b.user,assistant:b.assistant,partial:b.partial,continues:b.continues??null,blocks:D,status:w?"streaming":L?L.status:b.user.kind==="compaction"?b.user.status:"pending",error:Aw(b),cost:xN([b.user,...b.assistant],P,t.pricing),compaction:wN(b.user),threads:R,plan:b===g,shell:vN(b),response:ri(D,j=>j.type==="text"&&!!j.text.trim())??null,attachments:b.user.blocks.filter(j=>j.type==="attachment"&&(j.mime.startsWith("image/")||j.mime==="application/pdf")),live:O,queued:y,retrying:w};return xw.set(b.user,{assistant:b.assistant,key:v,pricing:t.pricing,heads:t.threads,turn:pe}),pe})}var th=e=>Yr(e);function Iw(e,t={}){return Ay(ky(Ot(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(Yr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(th)}:n.kind==="text"?{kind:n.kind,block:Yr(n.part)}:{kind:n.kind,block:th(n.part)})}var EN=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:Ot(e.blocks)}:{kind:e.kind,part:ni(e.block)};function Ew(e,t){let n=new Map(e.map(o=>[EN(o),o])),r=Dy([...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 MN(e){if(!ee(e)||!Cm(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=uy(e);return(n.answers??Ly(n.outputText??"",t.length)??[]).length>0}function Mw(e){return vy(Ot(e),n=>yn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(MN)?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:Yr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(th),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 Ow(e,t){return Ey(Ot(e.blocks).map(n=>({part:n})),t?.flatMap(ft))}function jw(e){return Wo(Ot(e))}function Dw(e){return xy(Ot(e))}function Lw(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=ni(n),s=xn.get(n);return!!r&&we(r)&&Ho(r)&&(!s||s.status==="streaming")}):!1}var Rw=new WeakMap;function $w(e){if(!Xy(e))return e;let t=Rw.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},Rw.set(e,t)}return t}function ON(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function Uw(e){let t=e.map(oe),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=Ry(t).map(ON);return ur({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function Fw(e,t,n){let r=oe(e),s=r.state;return ur({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function Nw(e){let t=ft(e).map(r=>Uo(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 Cw=Object.freeze([]),Tw=new WeakMap;function Bw(e){if(!e)return Cw;let t=Tw.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:Cw,Tw.set(e,t)}return t}function Kw(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 si(e)){let s=Zy([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 jN="prt_kortix_restore_g";function Gw(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(jN))}function Ww(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 nh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ze=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,DN=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function Hw(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=nh(t)?t.restore:void 0;if(!nh(n))return null;let r=nh(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])=>DN.has(a)?i:i+Ze(l),0)}];return{generation:Ze(n.generation),missing:o.filter(i=>i.count>0)}}var Vw=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function zw(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of Vw(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 Yw=(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}},LN=(e,t)=>e.map(n=>n.type==="text"?Yw(n,t):n),qw=new WeakMap;function $N(e,t){let n=qw.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>Vw(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?Yw(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:LN(s.result.content,t)}}:s)}:e;return qw.set(e,{texts:t,out:r}),r}var oi=1024*1024;function Jw(e){return e.reduce((t,n)=>t+n.bytes,0)>oi?"download":"inline"}function Qw(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>oi)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function Xw(e,t){if(t.size===0)return e;let n=e.messages.map(r=>$N(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function UN(e){return e==="TIMEOUT"||e==="request_deadline"}function FN(e){let t=ev(e)?e.code:void 0;return typeof t=="string"?t:void 0}var ev=e=>typeof e=="object"&&e!==null;function Zw(e){let t=e?.metadata;return!!ev(t)&&t.warm===!0}var NN=5,BN=2e3,KN=e=>new Promise(t=>setTimeout(t,e));async function qN(e,{attempts:t=NN,delayMs:n=BN,sleep:r=KN}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function GN(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 UN(FN(g))?qN(async()=>!Zw(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(Zw(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 WN=12e4,ii=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},HN=1e3,VN=15e3,tv=100,zN=50,YN=10;function nv(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 Wr(`session ${l.status}`):new _(`Session synchronization failed: ${l.status}`,{status:l.status});return{messages:await l.json(),nextCursor:l.headers.get("x-next-cursor")||void 0}}}function rv(e){return JN(nv(e))}function sv(e){return new rh({...e,loadPage:nv(e)})}async function JN(e){let t=[],n=new Set,r;do{let i=await e({limit:tv,...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 QN={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},rh=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??QN,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??WN,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 ii;if(!r&&qr(n))return;if(r||this.update({freshness:bn(n)?"loading":"error"}),n instanceof _&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(HN*2**this.retryAttempt,VN);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"?zN:tv,...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 ii(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<YN&&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 XN=5e3,iv=40,o4=5*6e4,ZN=16,Jr=new Map;function av(e,t,n,r=Date.now()){let s=cv(e,t);for(Jr.delete(s),Jr.set(s,{envelope:n,atMs:r});Jr.size>ZN;){let o=Jr.keys().next().value;if(o===void 0)break;Jr.delete(o)}}var ov=new Map;function cv(e,t){return`${e}/${t}`}function eB(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=XN}function lv(e,t,n=Date.now()){if(!e||!t)return null;let r=cv(e,t),s=ov.get(r);return s?eB(s,n)?s.promise:(ov.delete(r),null):null}function uv(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 tB=/(?:\n\n)?Command exited with code (-?\d+)\s*$/;function nB(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=tB.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 pv(e){let t=!1,n=e.blocks.map(r=>{if(r.type!=="tool_call")return r;let s=nB(r);return s!==r&&(t=!0),s});return t?{...e,blocks:n}:e}var dv=Object.freeze({generation:0,session:{},threads:{},messages:{},revs:{},older:{}});function rB(e,t){let n=pv(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 gv(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)!Ll(p)||e.revs[p.message_id]!==void 0||(r=rB(r,p));let a={...e.threads};for(let p of t.threads)$l(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 sB=2e3;async function oB(e,t,n){let r=lv(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??sB,null)})]).finally(()=>clearTimeout(s)):null;return(o&&uv(o))??Hn(e,t,{limit:iv,history:!0,signal:n.signal})}async function fv(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s=Gn?await l_(Gn,t,n):null;if(s==="missing")return{envelope:null,empty:!1,log:null};if(s){let i=dw(gv(dv,s));return{envelope:null,empty:!!i?.empty&&i.runtimeSessionId===r&&await mv(t,n,r),log:s}}let o;try{o=await oB(t,n,{})}catch{return{envelope:null,empty:!1}}return av(t,n,o),sh(o)!==r?{envelope:o,empty:!1}:{envelope:o,empty:await mv(t,n,r)}}async function mv(e,t,n){try{let r=await Vn(e,t);return oh({savedEmptyRoot:n,rootSessionId:n,turnRead:!0,hasEndedTurn:r.last_ended!=null,hasOpenOrQueuedTurn:r.turns.length>0})}catch{return!1}}function sh(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 oh(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function iB(e){throw N("buildTunnelEventStreamUrl")}function aB(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(S,O){o?.(S,O);let y=d.get(S);if(y)for(let w of y)try{w(O)}catch{}}async function P(){if(m)return;let S=new AbortController;g=S,p&&(p.aborted?S.abort():p.addEventListener("abort",()=>S.abort(),{once:!0}));let O=S.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(),v=new TextDecoder,C="",D="message",R=[],L=j=>{if(j===""){R.length>0&&h(D,R.join(`
98
- `)),D="message",R=[];return}if(j.startsWith(":"))return;let q=j.indexOf(":"),W=q===-1?j:j.slice(0,q),K=q===-1?"":j.slice(q+1);K.startsWith(" ")&&(K=K.slice(1)),W==="event"?D=K.trim()||"message":W==="data"?R.push(K):W==="id"&&!K.includes("\0")&&(f=K)},pe=j=>{let q="";!j&&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:j,value:q}=await x.read();if(j)break;C+=v.decode(q,{stream:!0}),pe(!1)}m||(C+=v.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 k(){m=!0,g?.abort(),g=null,d.clear()}function T(S,O){let y=d.get(S)??new Set;y.add(O),d.set(S,y)}function b(S,O){d.get(S)?.delete(O)}return{connect:P,close:k,addEventListener:T,removeEventListener:b}}function cB(e,t){throw N("createTunnelEventStream")}var yv="/_kortix/viewer",ai=6e4,wn=new Map;function hv(){wn.clear(),Qr.clear()}async function lB(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 ih(e={}){let t=e.path??yv,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=lB(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-ai:Date.now()+ai;return wn.set(t,{session:o,expiresAt:a}),o});return wn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function _v(e={}){let t=e.path??yv;return Object.assign(async()=>(await ih(e))?.access_token??null,{invalidate:n=>{let r=wn.get(t);r&&!r.inflight&&r.session?.access_token===n&&wn.delete(t)}})}var Qr=new Map;async function uB(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 Qr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-ai:Date.now()+ai}),r.token}catch{return null}}function ah(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=Qr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=uB(n,r).then(a=>(a===null&&Qr.delete(n),a));return Qr.set(n,i),i}}function bv(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:ah({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 Sv(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 ci(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:Sv(t.groups),groupIds:Sv(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 xv(e,t={}){let n=ci(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 pB=60,ch=new Map;function wv(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 Pv(e){return JSON.parse(new TextDecoder().decode(wv(e)))}async function dB(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=ch.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(()=>ch.delete(e)),ch.set(e,n)),n}return JSON.parse(e)}async function vv(e,t={}){let n=S=>{throw new yt("unauthenticated",`Kortix sign-in token refused: ${S}.`)},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=Pv(a),g=Pv(l)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await dB(r,t.fetch??((S,O)=>fetch(S,O)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(S=>S.kty==="EC"&&(d.kid===void 0||S.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${l}`),P;try{P=wv(p)}catch{return n("malformed")}let k=!1;for(let S of f)try{let{kid:O,alg:y,use:w,key_ops:x,...v}=S,C=await crypto.subtle.importKey("jwk",v,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},C,P,h)){k=!0;break}}catch{}if(!k)return n("bad signature");let T=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+pB<T)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let S=g.aud;if(!(S===o||Array.isArray(S)&&S.includes(o)))return n("wrong audience")}let b=ci(g);return b||n("no subject")}function lh(e){let t=e.agents.map(gB),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 gB(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 uh(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>to(n?{...r,mode:null}:r))}function kv(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=uh(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 Av=lh;function Rv(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function ph(e){return{providerID:"kortix",modelID:e}}function vn(e,t){return ph(e.startsWith("kortix/")?e.slice(7):e)}var Cv=[{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 dh(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function fB(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function Tv(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 Xr(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 Iv(e){return e.reduce((t,n)=>{let r=dh(n)??0,s=dh(t)??0;return r!==s?r>s?n:t:Xr(n.id)>Xr(t.id)?n:t})}function gh(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of Tv(e,fB)){let a=[...Tv(o,p=>p.family||p.id).values()].map(Iv),l=a.filter(p=>{let d=dh(p);return d!==null&&Math.abs(n-d)<r});for(let p of l.length>0?l:[Iv(a)])s.add(p.id)}return s}function mh(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=>Xr(r.id)>0)?n.filter(r=>Xr(r.id)>0):n}var Ev={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:[]},Mv=[...Cv,{id:Ev.id,env:Ev.env}],yB={"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 Ov(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var hB=(()=>{let e=new Map;for(let{id:n,env:r}of Mv)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=>Ov(o)===n)??s[0])}return t})();function jv(e){let t=yB[e.id];if(t)return t;let n=e.env??[],r=n.length===1?hB.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[Ov(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}var _B=["low","medium","high"];function Dv(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:[..._B]}: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 Lv=Mv;var L4=Lv.map(e=>({id:e.id,authRequirement:jv(e)})),$v=new Set(["kortix"]);function bB(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=Dv({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 Uv(e){return e.modelPicker?bB(e.modelPicker):void 0}function SB(e){return"capabilities"in e&&e.capabilities!=null}function li(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1&&n.available!==!1}function Fv(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)&&$v.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:Rv({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 Nv(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var Kv="kortix",Bv="codex";function qv(e){return e.providerID===Kv&&!e.modelID.includes("/")}function PB(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function kn(e){return qv(e)}function xB(e){return gh(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function Gv(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=xB(e.catalogModels),s=Nv(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===Kv){let d=PB(i.modelID,i.provider),g=d===Bv?t?.has(Bv)??!1:t?.has(d)??!1;if(qv(i))return!n;if(!g)return!1;if(l==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return kn(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return kn(i)}catch{return kn(i)}return!1}if(l==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return kn(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return kn(i)}catch{return kn(i)}return!1}}function Wv(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 Hv(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?ph(r):void 0}function Vv(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 wB=new Set(["explicit","repointed","fallback"]);function zv(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:vn(n),from:vn(r),reason:typeof o=="string"?o:"other",atMs:s}}function Yv(e,t){return!t||(e??-1)>=t.atMs}function Jv(e){let t=e.session?Qn(e.session):null,n=t?vn(t):void 0,r=e.session?.metadata;return(wB.has(String(r?.opencode_model_source))||r?.opencode_model_restored===!0?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(i=>!!i)}function Qv(e){let{models:t,providers:n}=e,r=l=>li(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 mh(Object.keys(m.models).map(P=>({id:P})))){let P={providerID:m.id,modelID:h.id};if(r(P))return P}}}})(),i=s(e.picks??[]);return{model:i??s([e.serverDefault,e.globalDefault,e.agentModel,o]),explicit:i,fallback:o}}return sk(vB);})();
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 g0(e){let t=jo(e.input),n=t.map(([s,o])=>d0(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:By(e),diff:r}}var Sx=/^Found\s+(\d+)\s+match/i,m0=/^(\/[^:]+?):\s*/,bx=/Line\s+(\d+):/g;function f0(e){let t=e.trim(),n=t.match(Sx),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(m0);if(!a)continue;let l=a[1],p=i.slice(a[0].length),d=[],g;for(bx.lastIndex=0;(g=bx.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 y0(e){return e.trim().split(`
97
+ `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function h0(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=Sx.test(e.output.trim())?f0(e.output):y0(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function _0(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 Fy(e){let t=_n(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function b0(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(Fy)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(Fy)};let n=_n(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(Fy)}:{kind:"todo",items:[]}}function S0(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=_n(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let l=_n(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 P0(e){let n=e.input&&Object.keys(e.input).length>0?_x(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?qr(e.outputParsed):_x(e.outputParsed):e.outputText!==void 0?r=qr(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function Px(e){switch(ae(e.name)){case"web_search":return r0(e);case"bash":return c0(e);case"read":return l0(e);case"write":return u0(e);case"edit":return g0(e);case"grep":case"glob":return h0(e);case"task":return _0(e);case"todowrite":return b0(e);case"question":return S0(e);default:return P0(e)}}var x0=new Set(["AbortError","MessageAbortedError"]),w0=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],k0=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function xx(e){let t=e.toLowerCase();return k0.some(n=>t.includes(n))?!1:w0.some(n=>t.includes(n))}function v0(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 Gr(e){if(typeof e=="string")return xx(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&x0.has(n))return!0;let r=v0(t);return typeof r=="string"?xx(r):!1}var wx=["user","runtime-disposed","orphan-finalized","wake"],A0=["orphan-finalized","wake"];function R0(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 wx.includes(n)?n:void 0}var Wr="kortix-active-instance",kx=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function vx(e){return kx.some(t=>e===t||e.startsWith(`${t}/`))}function bn(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 C0(e){let t=bn(e);return!!t&&t.innerPath===""}function T0(e){let t=bn(e);return!t||!t.innerPath?e:t.innerPath}function Ax(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=bn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return vx(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function Rx(e){return e?bn(e)?.instanceId??null:null}function I0(){return typeof window>"u"?null:Rx(window.location.pathname)||Cx()}function Cx(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Wr}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function E0(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Wr}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Wr}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Wr}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function M0(e,t){return t?Ax(t,e):e}function O0(e){let t=bn(e);return t?t.innerPath||"/dashboard":e}function Hr(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 Ky(e){let t=Hr(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 j0=Ky;function Jo(e){let t=Ky(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var D0=Jo;function Tx(e){return Jo(e)!==null}var L0=Tx,$0=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],U0=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],F0=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function Ix(e){return F0.test(Hr(e))}function Pn(e){let t=Hr(e);return t?Ix(t)||$0.some(n=>n.test(t)):!1}var N0=/server url not ready|sandbox is still loading/i;function B0(e){return N0.test(Hr(e))||Pn(e)}var Sn=class extends Error{constructor(t){let n=t?.trim();super(n&&Pn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function Ex(e){let t=Jo(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=Hr(e);return Pn(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 K0=Ex;function qy(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 q0(e,t){return e.external_id?`${ot()}/p/${e.external_id}/${t}`:null}async function G0(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function Mx(e){let t=await rr();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:Gs(r,s,o),created:!0}}async function W0(){return(await rr().catch(()=>null))?.sandbox??null}async function H0(e){return{sandbox:(await Mx(e)).sandbox}}async function V0(e){let t=nr(e);if(!t)return null;try{let n=await pm(t);return n?Gs(await wt(n.project_id),n,null):(await rr(t))?.sandbox??null}catch{return null}}async function z0(e,t){throw await Ws(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function Y0(e){let t=nr(e);return(await um().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function J0(){return null}async function Q0(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Ws(e);if(!t)throw new Error("Project session sandbox not found");await Qn(t.projectId,t.sessionId)}async function X0(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Ws(e);if(!t)throw new Error("Project session sandbox not found");await Xn(t.projectId,t.sessionId)}async function Z0(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function eU(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function Gy(e,t,n){let r=qy(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 tU(e,t){return Gy(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function nU(e,t,n,r="member"){await Gy(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function rU(e,t,n){await Gy(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var Wy="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function sU(e){throw N("getInvite",Wy)}async function oU(e){throw N("acceptInvite",Wy)}async function iU(e){throw N("declineInvite",Wy)}async function aU(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function cU(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function lU(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function uU(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function pU(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function dU(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var Ox=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function gU(e){return Ox.includes(e)}async function mU(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 fU(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 jx(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function jx(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 yU(){return(await Le(`${ot()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function hU(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function _U(e){}async function bU(e){}async function SU(e){return{serverTypes:[],location:e||"hel1"}}async function PU(e){throw new Error("Retired instance provisioning is unavailable. Create a project session on platinum (or the legacy daytona fallback).")}async function xU(e){throw N("deleteInstance")}async function wU(e,t){}async function kU(){throw N("claimComputer")}async function vU(e){return null}function AU(e,t){throw N("getSandboxProvisionStreamUrl")}var Vr=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function Dx(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 Lx(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function $x(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function z(e,t,n){let r=n?.body!==void 0,s=await fetch(`${qe(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:Dx(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 Lx(s);if(!s.ok)throw new Vr($x(s,o),s.status,o);return o}function RU(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 CU(e,t){return z(`/marketplace/items${RU(t)}`,e)}function TU(e){return z("/marketplace/marketplaces",e)}function IU(e,t){return z(`/marketplace/items/${encodeURIComponent(e)}`,t)}function EU(e,t,n){return z(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function MU(e,t){return z("/access/check-email",t,{method:"POST",body:{email:e}})}function OU(e,t){return z("/access/request-access",t,{method:"POST",body:e})}function jU(e){return z("/auth/logout",e,{method:"POST",body:{}})}function DU(e,t){return z(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function LU(e,t){return z("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function $U(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function UU(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function FU(e,t,n={}){return z(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function NU(e,t){return z(`/connectors/app-form/${encodeURIComponent(e)}`,t)}function BU(e,t,n){return z(`/connectors/app-form/${encodeURIComponent(e)}`,n,{method:"POST",body:{store:t.store,client_id:t.clientId,client_secret:t.clientSecret}})}function KU(e,t){return z(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function qU(e,t,n,r){return z(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function GU(e,t){return z(`/p/public-share/${encodeURIComponent(e)}`,t)}async function WU(e,t={backendUrl:Ct()}){return(await z(`/public/responses/${encodeURIComponent(e)}`,{...t,accessToken:null})).response}function HU(e,t,n){return z(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function VU(e){return z("/system/maintenance",e)}function zU(e,t){return z("/system/maintenance",t,{method:"PUT",body:e})}function YU(e){return z("/user-roles",e)}function JU(e,t){return z("/system/demo-request",t,{method:"POST",body:e})}async function QU(e,t,n){let r=await fetch(`${qe(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Vt(t)}`,{headers:Dx(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await Lx(r);throw new Vr($x(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 XU(e,t){throw N("openStressTestStream")}function ZU(e,t){throw N("buildPublicTemplateUrl")}async function eF(e,t,n){throw N("getPublicTemplate")}var tF="kortix:connect-link:";function Hy(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`${tF}${t.toString(36)}${n.toString(36)}`}function nF(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(Hy(i));if(!a)return;let l=JSON.parse(a);if(Date.parse(l.expires_at)<=Date.now()){t.removeItem(Hy(i));return}return l}catch{return}},o=(i,a)=>{if(t)try{t.setItem(Hy(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 Ux="Could not start the connect flow.";async function rF(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:Ux}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:Ux};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var Fx=3e3,Nx=5e3,Bx=5*6e4;function sF(e,t){let n=e===0?Fx:Nx;return t+n>Bx?null:n}function oF(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 iF(){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 aF(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 cF(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 lF(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 uF(){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 yQ="1";var pF="kortix.query-cache";function qx(e){return!!e&&typeof e.then=="function"}function Kx(e){return qx(e)?e:Promise.resolve()}function dF(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 gF(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:l=pF,now:p=()=>Date.now()}=e,d=`${l}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),P=()=>{try{return Kx(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},v=(x,k)=>{if(!k)return 0;let C;try{C=JSON.parse(k)}catch{return P(),0}if(!C||C.v!==s||C.user!==n||!Array.isArray(C.queries)||p()-C.at>o)return P(),0;let D=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"}),D+=1)}return D},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),b=(x,k)=>{let C=[],D=0;for(let R of x){let L=JSON.stringify(R).length+1;D+L>k||(C.push(R),D+=L)}return C},S=async x=>{let k=b(T(x),i);for(;;){let C={v:s,user:n,at:p(),queries:k};try{await Kx(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(()=>S(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 qx(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 P()}}}function mF(){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 Gx="/kortix/part/";function Wx(e){return typeof e=="string"&&e.startsWith(Gx)}async function fF(e){if(!Wx(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 Hx(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 yF(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 Vy(e,t){return yF(e,t)?(t?Hx(t):null)??Hx(e):null}function zr(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 hF(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var _F=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function bF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function SF(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(bF).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function PF(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function Vx(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function xF(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:_F.test(n.hostname)?t.backendUrls.some(r=>{let s=PF(r);return s!==null&&Vx(s)===Vx(n)}):t.templates.some(r=>SF(n.origin,r))}async function zx(e,t={}){if(!zr(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 xF(e,{templates:mb(),backendUrls:r})}async function Yx(e,t={}){let n=Vy(e,t.serverUrl||I().backendUrl||void 0);if(!n)return!1;let r=await Nt();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 wF(e,t={}){if(zr(e)){if(!await zx(e,t)||!await Nt())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 Yx(e,t),e}var kF=3e3;function Jx(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 vF(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 Jx(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function AF(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function RF(e,t){throw N("buildPresentationTemplatePdfUrl")}function CF(e,t){throw N("buildPresentationTemplateImageUrl")}function Qx(e,t){return`${AF(e)}/presentation/convert-to-${t}`}async function TF(e,t,n,r){let s=Qx(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,P)=>{let v=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(v),P(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 EF(e){return e==="unreachable"}function MF(e){return!e||e.status===0?"unknown":e.ok&&mf(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var Xx=1e4,OF={connection:"unknown",faultSinceMs:null};function jF(e,t,n,r=Xx){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 Zx({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<Qo,l=!!t&&i-t.atMs<ei;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<=Xo,streamFresh:!!s&&i-s.atMs<=xn,inboxFresh:!!n&&i-n.atMs<=Zo,activityFresh:!!o&&i-o.atMs<=xn}}function wn(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function zy(e,t,n){if(!t)return!1;let r=wn(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=wn(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function DF(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"&&!zy(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function LF(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,l=i?s.turns.filter(g=>!zy(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:wn(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function $F(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,P=l&&!n&&s.atMs>=p,v=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(P&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:wn(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 ew(e){let t=Zx(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=DF(e,t,s,o);if(i)return i;let{result:a,openTurn:l}=LF(e,t,s,o);return a??$F(e,t,o)??UF(e,t,l,o)}var Qo=6e4,Xo=45e3,xn=45e3,Zo=1e4,FF=3e3,ei=15e3;function NF(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function BF(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 KF(e){return ew(e)}function qF(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,l=[null,t?t.atMs+Qo:null,n?n.atMs+ei:null,r?r.atMs+Zo:null,s?s.atMs+Xo:null,o?o.atMs+xn:null,i?i.atMs+xn:null],p=null;for(let d of l)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function tw(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||Gr({name:s.name??void 0,message:s.message})?null:s}var GF="SandboxMemoryGuard";function WF(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=tw(e,t);if(r?.message){if(r.name!==GF)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 HF=6e4;function VF(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function zF(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var nw=9e4;function YF(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+nw}var JF=75e3,QF=2,XF=2e4;function Yy(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function ZF(e){return e.filter(t=>t!=null).join("|")}function eN(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function tN(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Yy(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Yy(),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=eN(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 nN={"retry-start":"retrying",restart:"restarting"};function rN(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${nN[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function sN(e){return e===1?"once":e===2?"twice":`${e} times`}function oN(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 ${sN(t)}`),`Tried: ${r.join(", then ")}.`}var iN={"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 rw(e){return!!(e.metadata??{}).legacy_migration}function aN(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 rw(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function cN(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 lN={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 uN(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function ti(e){return e.runtime_sessions??e.opencode_sessions??[]}function sw(e){let t=ti(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 pN(e){let t=sw(e);return t?ti(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 dN(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=>ti(r).some(s=>s.id===t))??null)}var gN=new Set;function ow(e){for(let t of[...gN])try{t(e)}catch{}}var uw={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 pw=e=>Object.values(e.ext??{}).find(t=>t.version===ke),dw=e=>!!e&&pw(e)!==void 0,gw=e=>{let t=pw(e);return t?t.native_id??null:e.thread_id};function mw(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:gw(t),hasMessages:n,empty:!n&&e.older[t.thread_id]===!1}}var iw=new WeakMap;function fw(e,t){let n=gw(e),r=iw.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=Qs({...uw,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return iw.set(t,{native:n,rows:o}),o}var Jy=e=>e.info.time?.created;var mN=(e,t)=>(Jy(e)??-1/0)-(Jy(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var aw=new WeakMap,cw=new WeakMap,yw=e=>typeof e=="object"&&e!==null,fN=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,yN=e=>e.info.role==="user"&&e.parts.some(t=>yw(t)&&t.type==="compaction"),hN=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},lw=new WeakMap;function _N(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(!yw(p)||a.type==="compaction")return a;let d=`${s}|${l}|${a.id}`,g=lw.get(p);return g&&g.key===d?(o=!0,g.block):(lw.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function bN(e){let t=new Map,n=new Set;for(let r of e){if(!yN(r))continue;let s=e.find(o=>!n.has(o)&&hN(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function SN(e,t,n,r,s){let o=aw.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=Xs({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=_N(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 aw.set(n,p),p}function hw(e,t,n){let r=cw.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(mN),{paired:o,used:i}=bN(s),a={tool_input:0,cut_point:0,attachment:0},l=[];for(let m of s){if(i.has(m))continue;let f=SN(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=fN(s.map(Jy).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=l.filter(m=>m.role==="user"&&m.kind==="turn"),g={...uw,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 cw.set(n,{sessionId:e,native:t,log:g}),g}var Qy=new WeakMap,kn=new WeakMap,_w=new WeakMap;function ni(e){let t,n=kn.get(e);return n&&(t=PN(n).get(e.id)),t?(Qy.set(t,e),t):(e.type!=="harness"?t=Tm(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=_w.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},_w.set(e,t)),t&&Qy.set(t,e),t)}var Yr=e=>Qy.get(e),jt=e=>e.flatMap(t=>ni(t)??[]),bw=new WeakMap;function PN(e){let t=bw.get(e);return t||bw.set(e,t=new Map(ft(e)[0]?.parts.map(n=>[n.id,n]))),t}var Sw=new Map;function ft(e){let t=Sw.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:""},Sw.set(e.thread_id,t)),fw(t,e)}var xN="kortix-v1-import",Xy={schema:ce,v:1};function ri(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var Zy=e=>e.type==="tool_call",wN=e=>e.status==="pending"||e.status==="running",eh=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function Aw(e,t){let n=eh(e);return!wN(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var Pw=new WeakMap;function Rw(e,t){let n=Pw.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={...Xy,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 Pw.set(e,s),s}var xw=new WeakMap;function kN(e){let t=xw.get(e);return t||(t={...Xy,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:[]},xw.set(e,t)),t}var ww=new WeakMap;function vN(e){let t=ww.get(e);return t||(t={...Xy,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:[]},ww.set(e,t)),t}var AN=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 P=r.get(g.message_id);P&&!t.has(g.message_id)&&(l=P,i.has(P)||i.set(P,i.size),P.user.kind==="compaction"&&(p=P));continue}if(g.role!=="assistant"||AN(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 P=a.get(p);P||(P={user:vN(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,P)),f=P}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:kN(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 CN(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 Cw(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=Ir(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)?Yo(e.flatMap(r=>ft(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:th(e,n)}function th(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 Yo(n,t)??null}function EN(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 MN(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&&Zy(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:Zy(i)?Dr(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var jN=e=>e.assistant.some(t=>t.blocks.some(n=>Zy(n)&&ae(n.name)==="todowrite"&&mn(n))),DN=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function LN(e,t){let n=e.map(s=>Cw(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 kw=new WeakMap,$N=[];function nh(e){let t=ri(e.messages,n=>n.role==="assistant");return!!t&&hy(ft(t))}var vw=new WeakMap;function UN(e){let t=vw.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},vw.set(e,t)}return t}function si(e,t={}){let n=t.hideOutOfContext?UN(e):e,r=new Set(t.held??$N),s=RN(n.messages,r),o=TN(s,t.liveMessageId),{list:i,hint:a}=t.foldCompactions?CN(s,o):{list:s,hint:o},l=ri(n.messages,b=>b.role==="assistant"),p=nh(n),d=Ey({turns:i.map(b=>({userMessage:{info:{id:b.user.message_id}},assistantMessages:b.assistant.map(S=>({info:{time:S.status==="streaming"?{}:{completed:1},error:S.error??void 0}}))})),hintMessageId:a,unrunTurnIds:r}),g=ri(i,jN)??i[i.length-1],m=i.map(b=>!b.partial&&DN(b.user)),f=LN(i,m),h=dw(n),P=b=>h||b.producer.harness===xN,v=t.threads??[],T=new Set(v.map(b=>b.thread_id));return i.map((b,S)=>{let O=t.busy===!0&&d.workingTurnId===b.user.message_id,y=d.pendingTurnIds.includes(b.user.message_id),w=p&&b.assistant.includes(l),x=f[S],k=`${b.partial}|${O}|${y}|${b===g}|${w}|${x?(x.continued?"c":"")+x.retries:"-"}`,C=kw.get(b.user);if(C&&C.key===k&&C.pricing===t.pricing&&C.heads===t.threads&&C.assistant.length===b.assistant.length&&C.assistant.every((j,q)=>j===b.assistant[q]))return C.turn;let D=b.assistant.flatMap(j=>j.blocks);for(let j of b.assistant)for(let q of j.blocks)kn.set(q,j);let R=ON(b,D,v,T),L=b.assistant[b.assistant.length-1],pe={internal:m[S],autoRetry:x,id:b.user.message_id,user:b.user,assistant:b.assistant,partial:b.partial,continues:b.continues??null,blocks:D,status:w?"streaming":L?L.status:b.user.kind==="compaction"?b.user.status:"pending",error:Cw(b),cost:IN([b.user,...b.assistant],P,t.pricing),compaction:EN(b.user),threads:R,plan:b===g,shell:MN(b),response:ri(D,j=>j.type==="text"&&!!j.text.trim())??null,attachments:b.user.blocks.filter(j=>j.type==="attachment"&&(j.mime.startsWith("image/")||j.mime==="application/pdf")),live:O,queued:y,retrying:w};return kw.set(b.user,{assistant:b.assistant,key:k,pricing:t.pricing,heads:t.threads,turn:pe}),pe})}var rh=e=>Yr(e);function Mw(e,t={}){return Cy(Ry(jt(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(Yr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(rh)}:n.kind==="text"?{kind:n.kind,block:Yr(n.part)}:{kind:n.kind,block:rh(n.part)})}var FN=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:jt(e.blocks)}:{kind:e.kind,part:ni(e.block)};function Ow(e,t){let n=new Map(e.map(o=>[FN(o),o])),r=$y([...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 NN(e){if(!te(e)||!Im(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=dy(e);return(n.answers??Uy(n.outputText??"",t.length)??[]).length>0}function jw(e){return Ay(jt(e),n=>hn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(NN)?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:Yr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(rh),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&&kn.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function Dw(e,t){return Oy(jt(e.blocks).map(n=>({part:n})),t?.flatMap(ft))}function Lw(e){return Wo(jt(e))}function $w(e){return ky(jt(e))}function Uw(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=ni(n),s=kn.get(n);return!!r&&we(r)&&Ho(r)&&(!s||s.status==="streaming")}):!1}var Tw=new WeakMap;function Fw(e){if(!eh(e))return e;let t=Tw.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},Tw.set(e,t)}return t}function BN(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function Nw(e){let t=e.map(oe),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=Ty(t).map(BN);return pr({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function Bw(e,t,n){let r=oe(e),s=r.state;return pr({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function Kw(e){let t=ft(e).map(r=>Uo(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 Iw=Object.freeze([]),Ew=new WeakMap;function qw(e){if(!e)return Iw;let t=Ew.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&mn(s)):[]);t=n.length?n:Iw,Ew.set(e,t)}return t}function Gw(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 si(e)){let s=th([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 KN="prt_kortix_restore_g";function Hw(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(KN))}function Vw(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 sh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ze=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,qN=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function zw(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=sh(t)?t.restore:void 0;if(!sh(n))return null;let r=sh(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])=>qN.has(a)?i:i+Ze(l),0)}];return{generation:Ze(n.generation),missing:o.filter(i=>i.count>0)}}var Yw=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function Jw(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of Yw(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}},GN=(e,t)=>e.map(n=>n.type==="text"?Qw(n,t):n),Ww=new WeakMap;function WN(e,t){let n=Ww.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>Yw(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:GN(s.result.content,t)}}:s)}:e;return Ww.set(e,{texts:t,out:r}),r}var oi=1024*1024;function Xw(e){return e.reduce((t,n)=>t+n.bytes,0)>oi?"download":"inline"}function Zw(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>oi)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function ek(e,t){if(t.size===0)return e;let n=e.messages.map(r=>WN(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function HN(e){return e==="TIMEOUT"||e==="request_deadline"}function VN(e){let t=nk(e)?e.code:void 0;return typeof t=="string"?t:void 0}var nk=e=>typeof e=="object"&&e!==null;function tk(e){let t=e?.metadata;return!!nk(t)&&t.warm===!0}var zN=5,YN=2e3,JN=e=>new Promise(t=>setTimeout(t,e));async function QN(e,{attempts:t=zN,delayMs:n=YN,sleep:r=JN}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function XN(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 HN(VN(g))?QN(async()=>!tk(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(tk(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 ZN=12e4,ii=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},eB=1e3,tB=15e3,rk=100,nB=50,rB=10,ai=class extends Sn{};async function sB(e){let t=await e.json().catch(()=>null);return t!==null&&typeof t=="object"&&t.retry===!1}function sk(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?await sB(l)?new ai(`session ${l.status}`):new Sn(`session ${l.status}`):new _(`Session synchronization failed: ${l.status}`,{status:l.status});return{messages:await l.json(),nextCursor:l.headers.get("x-next-cursor")||void 0}}}function ok(e){return oB(sk(e))}function ik(e){return new oh({...e,loadPage:sk(e)})}async function oB(e){let t=[],n=new Set,r;do{let i=await e({limit:rk,...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 iB={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},oh=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailParked=!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??iB,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??ZN,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,this.tailParked=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof ii;if(!r&&Gr(n))return;if(r||this.update({freshness:Pn(n)?"loading":"error"}),n instanceof _&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}if(n instanceof ai){this.tailParked=!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(eB*2**this.retryAttempt,tB);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"?nB:rk,...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 ii(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<rB&&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.tailParked||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 aB=5e3,ck=40,f4=5*6e4,cB=16,Jr=new Map;function lk(e,t,n,r=Date.now()){let s=uk(e,t);for(Jr.delete(s),Jr.set(s,{envelope:n,atMs:r});Jr.size>cB;){let o=Jr.keys().next().value;if(o===void 0)break;Jr.delete(o)}}var ak=new Map;function uk(e,t){return`${e}/${t}`}function lB(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=aB}function pk(e,t,n=Date.now()){if(!e||!t)return null;let r=uk(e,t),s=ak.get(r);return s?lB(s,n)?s.promise:(ak.delete(r),null):null}function dk(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 uB=/(?:\n\n)?Command exited with code (-?\d+)\s*$/;function pB(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=uB.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 gk(e){let t=!1,n=e.blocks.map(r=>{if(r.type!=="tool_call")return r;let s=pB(r);return s!==r&&(t=!0),s});return t?{...e,blocks:n}:e}var mk=Object.freeze({generation:0,session:{},threads:{},messages:{},revs:{},older:{}});function dB(e,t){let n=gk(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 fk(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)!$l(p)||e.revs[p.message_id]!==void 0||(r=dB(r,p));let a={...e.threads};for(let p of t.threads)Ul(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 gB=2e3;async function mB(e,t,n){let r=pk(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??gB,null)})]).finally(()=>clearTimeout(s)):null;return(o&&dk(o))??zn(e,t,{limit:ck,history:!0,signal:n.signal})}async function hk(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s=Hn?await p_(Hn,t,n):null;if(s==="missing")return{envelope:null,empty:!1,log:null};if(s){let i=mw(fk(mk,s));return{envelope:null,empty:!!i?.empty&&i.runtimeSessionId===r&&await yk(t,n,r),log:s}}let o;try{o=await mB(t,n,{})}catch{return{envelope:null,empty:!1}}return lk(t,n,o),ih(o)!==r?{envelope:o,empty:!1}:{envelope:o,empty:await yk(t,n,r)}}async function yk(e,t,n){try{let r=await Yn(e,t);return ah({savedEmptyRoot:n,rootSessionId:n,turnRead:!0,hasEndedTurn:r.last_ended!=null,hasOpenOrQueuedTurn:r.turns.length>0})}catch{return!1}}function ih(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 ah(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function fB(e){throw N("buildTunnelEventStreamUrl")}function yB(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(S,O){o?.(S,O);let y=d.get(S);if(y)for(let w of y)try{w(O)}catch{}}async function P(){if(m)return;let S=new AbortController;g=S,p&&(p.aborted?S.abort():p.addEventListener("abort",()=>S.abort(),{once:!0}));let O=S.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="",D="message",R=[],L=j=>{if(j===""){R.length>0&&h(D,R.join(`
98
+ `)),D="message",R=[];return}if(j.startsWith(":"))return;let q=j.indexOf(":"),W=q===-1?j:j.slice(0,q),K=q===-1?"":j.slice(q+1);K.startsWith(" ")&&(K=K.slice(1)),W==="event"?D=K.trim()||"message":W==="data"?R.push(K):W==="id"&&!K.includes("\0")&&(f=K)},pe=j=>{let q="";!j&&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:j,value:q}=await x.read();if(j)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(S,O){let y=d.get(S)??new Set;y.add(O),d.set(S,y)}function b(S,O){d.get(S)?.delete(O)}return{connect:P,close:v,addEventListener:T,removeEventListener:b}}function hB(e,t){throw N("createTunnelEventStream")}var _k="/_kortix/viewer",ci=6e4,vn=new Map;function bk(){vn.clear(),Qr.clear()}async function _B(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 ch(e={}){let t=e.path??_k,n=e.fetch??((o,i)=>fetch(o,i)),r=vn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=_B(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-ci:Date.now()+ci;return vn.set(t,{session:o,expiresAt:a}),o});return vn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function Sk(e={}){let t=e.path??_k;return Object.assign(async()=>(await ch(e))?.access_token??null,{invalidate:n=>{let r=vn.get(t);r&&!r.inflight&&r.session?.access_token===n&&vn.delete(t)}})}var Qr=new Map;async function bB(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 Qr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-ci:Date.now()+ci}),r.token}catch{return null}}function lh(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=Qr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=bB(n,r).then(a=>(a===null&&Qr.delete(n),a));return Qr.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:lh({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 xk(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 li(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:xk(t.groups),groupIds:xk(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 kk(e,t={}){let n=li(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 SB=60,uh=new Map;function vk(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 wk(e){return JSON.parse(new TextDecoder().decode(vk(e)))}async function PB(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=uh.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(()=>uh.delete(e)),uh.set(e,n)),n}return JSON.parse(e)}async function Ak(e,t={}){let n=S=>{throw new yt("unauthenticated",`Kortix sign-in token refused: ${S}.`)},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=wk(a),g=wk(l)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await PB(r,t.fetch??((S,O)=>fetch(S,O)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(S=>S.kty==="EC"&&(d.kid===void 0||S.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${l}`),P;try{P=vk(p)}catch{return n("malformed")}let v=!1;for(let S of f)try{let{kid:O,alg:y,use:w,key_ops:x,...k}=S,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,P,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+SB<T)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let S=g.aud;if(!(S===o||Array.isArray(S)&&S.includes(o)))return n("wrong audience")}let b=li(g);return b||n("no subject")}function ph(e){let t=e.agents.map(xB),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 xB(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 dh(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>to(n?{...r,mode:null}:r))}function Rk(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=dh(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 Ck=ph;function Tk(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function gh(e){return{providerID:"kortix",modelID:e}}function An(e,t){return gh(e.startsWith("kortix/")?e.slice(7):e)}var Ik=[{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 mh(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function kB(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function Ek(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 Xr(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 Mk(e){return e.reduce((t,n)=>{let r=mh(n)??0,s=mh(t)??0;return r!==s?r>s?n:t:Xr(n.id)>Xr(t.id)?n:t})}function fh(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of Ek(e,kB)){let a=[...Ek(o,p=>p.family||p.id).values()].map(Mk),l=a.filter(p=>{let d=mh(p);return d!==null&&Math.abs(n-d)<r});for(let p of l.length>0?l:[Mk(a)])s.add(p.id)}return s}function yh(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=>Xr(r.id)>0)?n.filter(r=>Xr(r.id)>0):n}var Ok={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:[]},jk=[...Ik,{id:Ok.id,env:Ok.env}],vB={"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 Dk(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var AB=(()=>{let e=new Map;for(let{id:n,env:r}of jk)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=>Dk(o)===n)??s[0])}return t})();function Lk(e){let t=vB[e.id];if(t)return t;let n=e.env??[],r=n.length===1?AB.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[Dk(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}var RB=["low","medium","high"];function $k(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:[...RB]}: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 Uk=jk;var H4=Uk.map(e=>({id:e.id,authRequirement:Lk(e)})),Fk=new Set(["kortix"]);function CB(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=$k({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 Nk(e){return e.modelPicker?CB(e.modelPicker):void 0}function TB(e){return"capabilities"in e&&e.capabilities!=null}function ui(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1&&n.available!==!1}function Bk(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)&&Fk.has(o.id))for(let[i,a]of Object.entries(o.models)){if(i==="auto"||i==="kortix/auto")continue;let l;if(TB(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:Tk({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 Kk(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var Gk="kortix",qk="codex";function Wk(e){return e.providerID===Gk&&!e.modelID.includes("/")}function IB(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Rn(e){return Wk(e)}function EB(e){return fh(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function Hk(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=EB(e.catalogModels),s=Kk(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===Gk){let d=IB(i.modelID,i.provider),g=d===qk?t?.has(qk)??!1:t?.has(d)??!1;if(Wk(i))return!n;if(!g)return!1;if(l==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return Rn(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Rn(i)}catch{return Rn(i)}return!1}if(l==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return Rn(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Rn(i)}catch{return Rn(i)}return!1}}function Vk(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 zk(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?gh(r):void 0}function Yk(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 MB=new Set(["explicit","repointed","fallback"]);function Jk(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:An(n),from:An(r),reason:typeof o=="string"?o:"other",atMs:s}}function Qk(e,t){return!t||(e??-1)>=t.atMs}function Xk(e){let t=e.session?Zn(e.session):null,n=t?An(t):void 0,r=e.session?.metadata;return(MB.has(String(r?.opencode_model_source))||r?.opencode_model_restored===!0?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(i=>!!i)}function Zk(e){let{models:t,providers:n}=e,r=l=>ui(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 yh(Object.keys(m.models).map(P=>({id:P})))){let P={providerID:m.id,modelID:h.id};if(r(P))return P}}}})(),i=s(e.picks??[]);return{model:i??s([e.serverDefault,e.globalDefault,e.agentModel,o]),explicit:i,fallback:o}}return iv(OB);})();