@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.
- package/README.md +22 -0
- package/dist/core/client/kortix.d.ts.map +1 -1
- package/dist/core/client/project-core.d.ts.map +1 -1
- package/dist/core/http/runtime-errors.d.ts +7 -1
- package/dist/core/http/runtime-errors.d.ts.map +1 -1
- package/dist/core/http/runtime-errors.js +2 -0
- package/dist/core/http/runtime-errors.js.map +1 -1
- package/dist/core/rest/platform-client/host-boundary.d.ts +52 -0
- package/dist/core/rest/platform-client/host-boundary.d.ts.map +1 -1
- package/dist/core/rest/platform-client/host-boundary.js +23 -0
- package/dist/core/rest/platform-client/host-boundary.js.map +1 -1
- package/dist/core/rest/projects-client/git-history.d.ts +1 -1
- package/dist/core/rest/projects-client/git-history.d.ts.map +1 -1
- package/dist/core/rest/projects-client/projects.d.ts +14 -8
- package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
- package/dist/core/rest/projects-client/projects.js +1 -1
- package/dist/core/rest/projects-client/projects.js.map +1 -1
- package/dist/core/rest/projects-client/sessions.d.ts +46 -2
- package/dist/core/rest/projects-client/sessions.d.ts.map +1 -1
- package/dist/core/rest/projects-client/sessions.js +24 -2
- package/dist/core/rest/projects-client/sessions.js.map +1 -1
- package/dist/core/runtime/runtime-types.d.ts +11 -0
- package/dist/core/runtime/runtime-types.d.ts.map +1 -1
- package/dist/core/session-sync/session-sync-controller.d.ts +6 -0
- package/dist/core/session-sync/session-sync-controller.d.ts.map +1 -1
- package/dist/core/session-sync/session-sync-controller.js +29 -1
- package/dist/core/session-sync/session-sync-controller.js.map +1 -1
- package/dist/core/turns/shell.d.ts +5 -1
- package/dist/core/turns/shell.d.ts.map +1 -1
- package/dist/core/turns/shell.js +5 -1
- package/dist/core/turns/shell.js.map +1 -1
- package/dist/kortix.esm.min.js +33 -33
- package/dist/kortix.global.js +33 -33
- package/dist/react/runtime-actions.d.ts +1 -0
- package/dist/react/runtime-actions.d.ts.map +1 -1
- package/dist/react/runtime-actions.js +1 -0
- package/dist/react/runtime-actions.js.map +1 -1
- package/dist/react/use-feature-flag.d.ts +1 -1
- package/dist/react/use-feature-flag.d.ts.map +1 -1
- package/dist/react/use-feature-flag.js +2 -1
- package/dist/react/use-feature-flag.js.map +1 -1
- package/dist/react/use-opencode-config.d.ts +3 -0
- package/dist/react/use-opencode-config.d.ts.map +1 -1
- package/dist/react/use-opencode-config.js +3 -0
- package/dist/react/use-opencode-config.js.map +1 -1
- package/dist/react/use-opencode-mcp.d.ts +1 -0
- package/dist/react/use-opencode-mcp.d.ts.map +1 -1
- package/dist/react/use-opencode-mcp.js.map +1 -1
- package/dist/react/use-opencode-sessions/sessions.d.ts +1 -0
- package/dist/react/use-opencode-sessions/sessions.d.ts.map +1 -1
- package/dist/react/use-opencode-sessions/sessions.js +1 -0
- package/dist/react/use-opencode-sessions/sessions.js.map +1 -1
- package/package.json +2 -2
package/dist/kortix.esm.min.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var dx={backendUrl:"",getToken:async()=>null},Zs=null,ir=null;function uO(e){ir=e}function pO(){return ir}function eo(e,t){t?.global!==!1&&(Zs=e)}function I(){return ir?.()??Zs??dx}function to(){return Zs!==null||ir?.()!==void 0}function gx(e){return new Promise(t=>setTimeout(t,e))}async function ar(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 gx(s)),i=await e(),i)return i;return i}var no=12e4;function mx(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Ka(e,t,n=no){let r=e instanceof Request?e.signal:t?.signal;if(mx(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function cr(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var S=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)}},ie=class extends S{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},ut=class extends S{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},vt=class extends S{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"}},fx="ENDPOINT_RETIRED";function N(e,t){let n=t?` ${t}`:"";return new S(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:fx})}var en="feature_disabled";function qa(e){if(!(e instanceof S)||e.status!==403||e.code!==en)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Ga(e){let t=qa(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function Wa(e){let t=qa(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}var lr="repository_disconnected",yx=new Set(["app_uninstalled","app_suspended","repo_not_accessible"]);function hx(e){return!!e&&typeof e=="object"&&e.code===lr}function _x(e){if(e?.status!=="error")return null;let t=e.last_error_code;return t&&yx.has(t)?t:null}function ur(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 ut(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 Ha(e){return e instanceof ut}function tn(e){if(e instanceof ie)return!0;let t=e?.status;return t===401||t===403}function Va(e){if(!(e instanceof ut))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 ve(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function ke(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(ve())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function pr(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(ve())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var za="request_deadline",bx=/^Request exceeded the \d+s server processing deadline$/,Ya=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===za||bx.test(n),Sx="git_mirror_unavailable",Px=/^git mirror is temporarily unavailable$/,xx=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Sx||Px.test(n),wx="connectors_provider_unavailable",vx=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===wx;async function kx(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await ke(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 ve();return{message:n,data:r}}function Ax(e,t,n){return Ya(e,t,n)||xx(e,t,n)||vx(e,t)||e===403&&t?.code===en||e===501&&t?.code===Qa||e===409&&(t?.code===Xa||t?.code===Za||t?.code===ec||t?.code===lr)||e===503&&(t?.code===tc||t?.code===nc)}async function Ja(e,t,n,r){let{message:s,data:o}=await kx(e,t),i=new S(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Ya(e.status,o,s)?za:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=ur(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 vt(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&&!Ax(e.status,o,s)&&I().onError?.(i,r),{error:i,success:!1}}var Rx="X-Kortix-Impersonate",so="kortix.impersonation",pt=null,dr=!1,ro=new Set;function oo(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function Cx(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 Tx(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 rc(){for(let e of ro)try{e()}catch{}}function Ix(){return dr||(dr=!0,pt=Tx(oo()?.getItem(so)??null)),pt&&!Cx(pt)?(sc(),null):pt}function PO(e){if(dr=!0,!e){sc();return}pt=e;try{oo()?.setItem(so,JSON.stringify(e))}catch{}rc()}function sc(){dr=!0;let e=pt!==null;pt=null;try{oo()?.removeItem(so)}catch{}e&&rc()}function xO(e){return ro.add(e),()=>{ro.delete(e)}}var Ex=/(^|\/)admin\/(api|analytics)(\/|$)/;function Mx(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Ex.test(t)}function oc(e){if(e!==void 0&&!Mx(e))return{};let t=Ix();return t?{[Rx]:t.grantId}:{}}function Ox(e){}function jx(){return!1}function Dx(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function gr(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function nn(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function mr(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(Dx))nn(n,s,o);return n}function ao(e,t,n){let r={...t},s=I().clientVersion?.trim();s&&!gr(r,"x-kortix-client-version")&&nn(r,"X-Kortix-Client-Version",s);for(let[i,a]of Object.entries(oc(e)))nn(r,i,a);let o=I().credentialHeader?.trim();return o?gr(r,o)||nn(r,o,n):gr(r,"authorization")||nn(r,"Authorization",`Bearer ${n}`),r}async function kt(e,t){let n=await fr();if(!n)throw new ie;return{headers:new Headers(ao(e,mr(e,{headers:t}),n)),rejected:()=>rn(n)}}function Lx(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function ic(e,t,n,r,s){if(t instanceof Request){let l=new Headers(ao(t.url,mr(t,n),r));return e(new Request(t,{headers:l,...s?{signal:s}:{}}))}let o=String(t),i=ao(o,mr(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var ac=null;async function co(e){let t=await ar(()=>I().getToken(),e);return t&&(ac=t),t}var fr=co;function rn(e=ac){e&&I().getToken.invalidate?.(e)}var io=new Map;function $x(e){let t=io.get(e);if(t)return t;let n=(async()=>(rn(e),fr({attempts:2,baseDelayMs:200})))().finally(()=>io.delete(e));return io.set(e,n),n}async function dt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=no}=n,o=n.fetch??I().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:Ka(e,t,s);if(i?.aborted)throw ve();let a=await(i?ke(fr(),i):fr());if(!a)throw new ie;let l=r&&!Lx(t)&&!gr(mr(e,t),"authorization"),p=l&&e instanceof Request?e.clone():e,d=await ic(o,e,t,a,i);if(d.status!==401||!l)return d;let g=await $x(a);return!g||g===a?d:ic(o,p,t,g,i)}async function Oe(e,t,n,r){let s=await dt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new S(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var cc=()=>I().backendUrl||"",Ux=new Set([502,503,504]),Fx=e=>Ux.has(e),lc=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Nx=e=>lc(e)||(e??"GET").toUpperCase()==="DELETE",Bx=2,yr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function je(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 Kx(e,i,n,r,s,o,a,l)}finally{i.signal?.removeEventListener("abort",p)}}async function Kx(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw ve();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 Gx(e,t,l,s,o,i,a);if(p instanceof ie)return{error:p,success:!1};if(!p.ok)return await Ja(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await ke(p.json(),a.activeController.signal):g?.includes("text/")?d=await ke(p.text(),a.activeController.signal):d=await ke(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(l){return Wx(l,e,t.method,n,r,s,a)}finally{hr(a)}}function hr(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function qx(e,t,n){try{await ke(e.arrayBuffer(),t)}catch(r){if(yr(r))throw r}finally{hr(n)}}async function Gx(e,t,n,r,s,o,i){let a=lc(t.method),l=Nx(t.method),p=l?Bx+1:1,d;for(let g=0;g<p;g++){g>0&&await pr(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 ke(dt(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 ie)return new ie;if(i.didTimeout&&yr(f)&&!t.signal?.aborted&&l&&g<p-1){i.didTimeout=!1;continue}if(yr(f)||g===p-1)throw f;continue}if(!a||!Fx(d.status)||g===p-1)return s||hr(i),d;await qx(d,m.signal,i)}return d}function Wx(e,t,n,r,s,o,i){hr(i);let a=yr(e);a&&(i.isAborted=!0);let l;if(a){if(!i.didTimeout)return{error:new S("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(cc(),"")||t;l=new S(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(l=new S(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(cc(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&I().onError?.(l,s)):(l=new S(String(e)),r&&I().onError?.(l,s));return{error:l,success:!1}}var De=()=>I().backendUrl||"",Qa="feature_not_supported",Xa="model_not_servable",Za="provision_in_flight",ec="sandbox_state_change_in_progress",tc="analytics_unavailable",nc="accounts_list_unavailable",BO={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new S(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 S(n.message,{name:n.name||"ApiError",stack:n.stack}):new S(String(n));return I().onError?.(r,t),{error:r,success:!1}}}};async function Hx(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await dt(`${De()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof ie)return cr();throw a}finally{clearTimeout(i)}}var c={putRaw:(e,t,n)=>je(`${De()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>je(`${De()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>je(`${De()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>je(`${De()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>je(`${De()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>je(`${De()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],je(`${De()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],je(`${De()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:Hx};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function lo(e){return e.replace(/\/v1\/?$/,"")}async function At(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=lo(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 uc(){return u(await c.get("/accounts"))}async function pc(e){return u(await c.post("/accounts",e))}async function dc(e){return u(await c.get(`/accounts/${e}`))}async function gc(e,t){return u(await c.patch(`/accounts/${e}`,{name:t}))}async function mc(e){return u(await c.get(`/accounts/${e}/branding`))}async function fc(e,t){return u(await c.put(`/accounts/${e}/branding`,t))}async function yc(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 hc(e,t){return u(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function _c(e){return u(await c.delete(`/accounts/${e}/branding`))}async function bc(e){return u(await c.get(`/accounts/${e}/members`))}async function Sc(e,t){return u(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function Pc(e){return u(await c.get(`/accounts/${e}/invites`))}async function xc(e,t){return u(await c.delete(`/accounts/${e}/invites/${t}`))}async function wc(e,t){return u(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function vc(){return u(await c.get("/account-invites",{showErrors:!1})).invites}async function kc(e){return u(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function uo(e){return u(await c.post(`/account-invites/${e}/accept`,{}))}function Vx(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 Ac(e,t){let n=await uo(e);return{accepted:n,landing:Vx(n,t)}}async function Rc(e){return u(await c.post(`/account-invites/${e}/decline`,{}))}async function Cc(e,t){return u(await c.delete(`/accounts/${e}/members/${t}`))}async function Tc(e,t,n){return u(await c.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Ic(e){return u(await c.post(`/accounts/${e}/leave`,{}))}async function zO(e){return At(e,"/v1/accounts")}async function Ec(){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 ZO=["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 Rt(){return u(await c.get("/projects"))}async function Oc(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/projects${t}`))}async function Ct(e,t){return u(await c.get(`/projects/${e}`,t))}async function jc(e,t,n="write"){return u(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Dc(e,t){return u(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Lc(e){return u(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function ej(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function _r(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 br(e,t){return u(await c.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Sr(e,t){return u(await c.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function tj(e,t){return u(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function $c(e){return u(await c.post("/projects",e))}async function Uc(e){return u(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function Fc(e,t={}){return u(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var zx="provision_stream_unterminated",Mc=200;function Yx(e){let t=e.split(`
|
|
1
|
+
var mx={backendUrl:"",getToken:async()=>null},eo=null,ar=null;function gO(e){ar=e}function mO(){return ar}function to(e,t){t?.global!==!1&&(eo=e)}function I(){return ar?.()??eo??mx}function no(){return eo!==null||ar?.()!==void 0}function fx(e){return new Promise(t=>setTimeout(t,e))}async function cr(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 fx(s)),i=await e(),i)return i;return i}var ro=12e4;function yx(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Ga(e,t,n=ro){let r=e instanceof Request?e.signal:t?.signal;if(yx(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function lr(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var S=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)}},ie=class extends S{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},ut=class extends S{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},vt=class extends S{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"}},hx="ENDPOINT_RETIRED";function N(e,t){let n=t?` ${t}`:"";return new S(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:hx})}var tn="feature_disabled";function Wa(e){if(!(e instanceof S)||e.status!==403||e.code!==tn)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Ha(e){let t=Wa(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function Va(e){let t=Wa(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}var ur="repository_disconnected",_x=new Set(["app_uninstalled","app_suspended","repo_not_accessible"]);function bx(e){return!!e&&typeof e=="object"&&e.code===ur}function Sx(e){if(e?.status!=="error")return null;let t=e.last_error_code;return t&&_x.has(t)?t:null}function pr(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 ut(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 za(e){return e instanceof ut}function nn(e){if(e instanceof ie)return!0;let t=e?.status;return t===401||t===403}function Ya(e){if(!(e instanceof ut))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 ke(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function ve(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(ke())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function dr(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(ke())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var Ja="request_deadline",Px=/^Request exceeded the \d+s server processing deadline$/,Qa=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ja||Px.test(n),xx="git_mirror_unavailable",wx=/^git mirror is temporarily unavailable$/,kx=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===xx||wx.test(n),vx="connectors_provider_unavailable",Ax=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===vx;async function Rx(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await ve(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 ke();return{message:n,data:r}}function Cx(e,t,n){return Qa(e,t,n)||kx(e,t,n)||Ax(e,t)||e===403&&t?.code===tn||e===501&&t?.code===Za||e===409&&(t?.code===ec||t?.code===tc||t?.code===nc||t?.code===ur)||e===503&&(t?.code===rc||t?.code===sc)}async function Xa(e,t,n,r){let{message:s,data:o}=await Rx(e,t),i=new S(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Qa(e.status,o,s)?Ja:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=pr(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 vt(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&&!Cx(e.status,o,s)&&I().onError?.(i,r),{error:i,success:!1}}var Tx="X-Kortix-Impersonate",oo="kortix.impersonation",pt=null,gr=!1,so=new Set;function io(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function Ix(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 Ex(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 oc(){for(let e of so)try{e()}catch{}}function Mx(){return gr||(gr=!0,pt=Ex(io()?.getItem(oo)??null)),pt&&!Ix(pt)?(ic(),null):pt}function kO(e){if(gr=!0,!e){ic();return}pt=e;try{io()?.setItem(oo,JSON.stringify(e))}catch{}oc()}function ic(){gr=!0;let e=pt!==null;pt=null;try{io()?.removeItem(oo)}catch{}e&&oc()}function vO(e){return so.add(e),()=>{so.delete(e)}}var Ox=/(^|\/)admin\/(api|analytics)(\/|$)/;function jx(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Ox.test(t)}function ac(e){if(e!==void 0&&!jx(e))return{};let t=Mx();return t?{[Tx]:t.grantId}:{}}function Dx(e){}function Lx(){return!1}function $x(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function mr(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function rn(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function fr(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap($x))rn(n,s,o);return n}function co(e,t,n){let r={...t},s=I().clientVersion?.trim();s&&!mr(r,"x-kortix-client-version")&&rn(r,"X-Kortix-Client-Version",s);for(let[i,a]of Object.entries(ac(e)))rn(r,i,a);let o=I().credentialHeader?.trim();return o?mr(r,o)||rn(r,o,n):mr(r,"authorization")||rn(r,"Authorization",`Bearer ${n}`),r}async function At(e,t){let n=await yr();if(!n)throw new ie;return{headers:new Headers(co(e,fr(e,{headers:t}),n)),rejected:()=>sn(n)}}function Ux(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function cc(e,t,n,r,s){if(t instanceof Request){let l=new Headers(co(t.url,fr(t,n),r));return e(new Request(t,{headers:l,...s?{signal:s}:{}}))}let o=String(t),i=co(o,fr(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var lc=null;async function lo(e){let t=await cr(()=>I().getToken(),e);return t&&(lc=t),t}var yr=lo;function sn(e=lc){e&&I().getToken.invalidate?.(e)}var ao=new Map;function Fx(e){let t=ao.get(e);if(t)return t;let n=(async()=>(sn(e),yr({attempts:2,baseDelayMs:200})))().finally(()=>ao.delete(e));return ao.set(e,n),n}async function dt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=ro}=n,o=n.fetch??I().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:Ga(e,t,s);if(i?.aborted)throw ke();let a=await(i?ve(yr(),i):yr());if(!a)throw new ie;let l=r&&!Ux(t)&&!mr(fr(e,t),"authorization"),p=l&&e instanceof Request?e.clone():e,d=await cc(o,e,t,a,i);if(d.status!==401||!l)return d;let g=await Fx(a);return!g||g===a?d:cc(o,p,t,g,i)}async function Oe(e,t,n,r){let s=await dt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new S(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var uc=()=>I().backendUrl||"",Nx=new Set([502,503,504]),Bx=e=>Nx.has(e),pc=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Kx=e=>pc(e)||(e??"GET").toUpperCase()==="DELETE",qx=2,hr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function je(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 Gx(e,i,n,r,s,o,a,l)}finally{i.signal?.removeEventListener("abort",p)}}async function Gx(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw ke();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 Hx(e,t,l,s,o,i,a);if(p instanceof ie)return{error:p,success:!1};if(!p.ok)return await Xa(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await ve(p.json(),a.activeController.signal):g?.includes("text/")?d=await ve(p.text(),a.activeController.signal):d=await ve(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(l){return Vx(l,e,t.method,n,r,s,a)}finally{_r(a)}}function _r(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Wx(e,t,n){try{await ve(e.arrayBuffer(),t)}catch(r){if(hr(r))throw r}finally{_r(n)}}async function Hx(e,t,n,r,s,o,i){let a=pc(t.method),l=Kx(t.method),p=l?qx+1:1,d;for(let g=0;g<p;g++){g>0&&await dr(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 ve(dt(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 ie)return new ie;if(i.didTimeout&&hr(f)&&!t.signal?.aborted&&l&&g<p-1){i.didTimeout=!1;continue}if(hr(f)||g===p-1)throw f;continue}if(!a||!Bx(d.status)||g===p-1)return s||_r(i),d;await Wx(d,m.signal,i)}return d}function Vx(e,t,n,r,s,o,i){_r(i);let a=hr(e);a&&(i.isAborted=!0);let l;if(a){if(!i.didTimeout)return{error:new S("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(uc(),"")||t;l=new S(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(l=new S(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(uc(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&I().onError?.(l,s)):(l=new S(String(e)),r&&I().onError?.(l,s));return{error:l,success:!1}}var De=()=>I().backendUrl||"",Za="feature_not_supported",ec="model_not_servable",tc="provision_in_flight",nc="sandbox_state_change_in_progress",rc="analytics_unavailable",sc="accounts_list_unavailable",GO={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new S(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 S(n.message,{name:n.name||"ApiError",stack:n.stack}):new S(String(n));return I().onError?.(r,t),{error:r,success:!1}}}};async function zx(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await dt(`${De()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof ie)return lr();throw a}finally{clearTimeout(i)}}var c={putRaw:(e,t,n)=>je(`${De()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>je(`${De()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>je(`${De()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>je(`${De()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>je(`${De()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>je(`${De()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],je(`${De()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],je(`${De()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:zx};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function uo(e){return e.replace(/\/v1\/?$/,"")}async function Rt(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=uo(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 dc(){return u(await c.get("/accounts"))}async function gc(e){return u(await c.post("/accounts",e))}async function mc(e){return u(await c.get(`/accounts/${e}`))}async function fc(e,t){return u(await c.patch(`/accounts/${e}`,{name:t}))}async function yc(e){return u(await c.get(`/accounts/${e}/branding`))}async function hc(e,t){return u(await c.put(`/accounts/${e}/branding`,t))}async function _c(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 bc(e,t){return u(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function Sc(e){return u(await c.delete(`/accounts/${e}/branding`))}async function Pc(e){return u(await c.get(`/accounts/${e}/members`))}async function xc(e,t){return u(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function wc(e){return u(await c.get(`/accounts/${e}/invites`))}async function kc(e,t){return u(await c.delete(`/accounts/${e}/invites/${t}`))}async function vc(e,t){return u(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Ac(){return u(await c.get("/account-invites",{showErrors:!1})).invites}async function Rc(e){return u(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function po(e){return u(await c.post(`/account-invites/${e}/accept`,{}))}function Yx(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 Cc(e,t){let n=await po(e);return{accepted:n,landing:Yx(n,t)}}async function Tc(e){return u(await c.post(`/account-invites/${e}/decline`,{}))}async function Ic(e,t){return u(await c.delete(`/accounts/${e}/members/${t}`))}async function Ec(e,t,n){return u(await c.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Mc(e){return u(await c.post(`/accounts/${e}/leave`,{}))}async function QO(e){return Rt(e,"/v1/accounts")}async function Oc(){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 nj=["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 Ct(){return u(await c.get("/projects"))}async function Dc(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/projects${t}`))}async function Tt(e,t){return u(await c.get(`/projects/${e}`,t))}async function Lc(e,t,n="write"){return u(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function $c(e,t){return u(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Uc(e){return u(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function rj(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function br(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 Sr(e,t){return u(await c.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Pr(e,t){return u(await c.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function sj(e,t){return u(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Fc(e){return u(await c.post("/projects",e))}async function Nc(e){return u(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function Bc(e,t={}){return u(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Jx="provision_stream_unterminated",jc=200;function Qx(e){let t=e.split(`
|
|
2
2
|
`).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
|
|
3
|
-
`);try{return JSON.parse(n)}catch(r){let s=n.length>
|
|
3
|
+
`);try{return JSON.parse(n)}catch(r){let s=n.length>jc?`${n.slice(0,jc)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function oj(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 S(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=Yx(g);if(m){if(t(m),m.type==="error")throw new S(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new S("Provision stream ended without a result",{code:zx});return a}async function rj(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await c.get(`/projects/quota${t}`))}async function sj(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Pr(e,t){return u(await c.patch(`/projects/${e}`,t))}async function Nc(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Bc(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function Kc(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function oj(e,t){return u(await c.put(`/projects/${e}/default-reasoning-effort`,{effort:t}))}async function ij(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function aj(e,t){throw N("updateTemplateWarmPool")}async function qc(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function cj(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function xr(e){return u(await c.delete(`/projects/${e}`))}async function lj(e,t){return u(await c.post(`/projects/${e}/transfer`,{account_id:t}))}async function uj(e,t){return At(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function pj(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=lo(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 Gc(e,t,n){return u(await c.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function Wc(e,t,n){return u(await c.post(`/projects/${e}/skills/remove`,t,{showErrors:!1,...n}))}async function _j(e){return u(await c.get(`/projects/${e}/git/connection`),"Failed to read the Git connection")}async function Hc(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function Vc(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function zc(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Yc(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Jc(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Qc(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 Xc(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 Zc(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function el(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function tl(e){return u(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function nl(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 rl(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function sl(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 kj(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function ol(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function il(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function al(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function cl(e){return u(await c.get(`/projects/${e}/access`))}async function ll(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function ul(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function Aj(e){return"status"in e&&e.status==="invited"}async function pl(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 dl(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function gl(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function ml(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function fl(e){return u(await c.get(`/projects/${e}/group-grants`))}async function yl(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 hl(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 _l(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function bl(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function Sl(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 Pl(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function xl(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function wl(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function vl(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 kl(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Al(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function Rl(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Cl(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Tl(e){return u(await c.get(`/projects/${e}/oauth`)).items??[]}async function po(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 go(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Il(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Jx=2e3,Qx=3e3,Xx=10*6e4;async function Ij(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 po(t,n,r);if(l())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Jx,p.interval_ms||Qx),g=p.expires_at||a()+Xx;for(;!l()&&a()<g;){if(await i(d),l())return{status:"cancelled"};let m;try{m=await go(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 El(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function wr(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Ml(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Ol(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var mo=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Tt=(e,t)=>`${mo(e)}/${encodeURIComponent(t)}`,jl=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Dl(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${mo(e)}${n}`))}async function Ll(e,t){return u(await c.post(mo(e),t))}async function $l(e,t,n){return u(await c.put(`${Tt(e,t)}/value`,{value:n}))}async function Ul(e,t){return u(await c.post(`${Tt(e,t)}/retry`))}async function Fl(e,t){return u(await c.delete(Tt(e,t)))}async function Nl(e,t,n,r){return u(await c.put(`${Tt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function Bl(e,t,n,r){return u(await c.delete(`${Tt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function Kl(e,t,n,r){return u(await c.put(`${Tt(e,t)}/access`,{mode:n,user_ids:r}))}async function ql(e,t,n){return u(await c.get(jl(e,t,n)))}async function Gl(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function Wl(e,t,n,r){return u(await c.put(jl(e,t,n),{secret_ids:r}))}async function fo(){return co()}async function Zx(e){return ar(()=>I().getToken(),e,yo)}function yo(){rn()}function Fj(e){e===null&&rn()}function Nj(e){}async function sn(){return fo()}async function Bj(e){return Zx(e)}async function U(e,t,n){try{return await dt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof ie)return cr();throw r}}function vr(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function on(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(`${vr(e,"catalog")}${r}`)).connectors??[]}async function ho(e){let t=[];for(let n of await on(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 Hl(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await ho(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 _o(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 on(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 ew(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 tw=9e4;async function It(e,t,n={},r={}){let{connector:s,action:o}=ew(t),i=r.account?.trim(),a=r.approvalContext?.trim(),l=u(await c.post(vr(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??tw,signal:r.signal}));return l.ok&&l.binding!==void 0&&!("output"in l)&&(l.output=l.data),l}async function bo(e,t){let n=await c.get(vr(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function nw(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 rw(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 So(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=rw(I().backendUrl),a=vr(e,"attachments"),l=await U(`${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 S(nw(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 zj(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 Vl(e){return u(await c.get(`/projects/${e}/connections`))}async function zl(e){return u(await c.get(`/projects/${e}/connections/all`))}async function Yl(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function Jl(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function Ql(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function Le(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function Yj(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function Jj(e,t,n){return u(await c.put(Le(e,t,"application"),n))}async function Qj(e,t){return u(await c.get(Le(e,t,"application")))}async function Xj(e,t,n){return u(await c.post(Le(e,t,"discover"),n))}async function Zj(e,t,n={}){return u(await c.post(Le(e,t,"discover-resource"),n))}async function eD(e,t,n){return u(await c.post(Le(e,t,"register"),n))}async function tD(e,t,n){return u(await c.post(Le(e,t,"authorize"),n))}async function nD(e,t,n){return u(await c.post(Le(e,t,"device"),n))}async function rD(e,t,n){return u(await c.post(Le(e,t,`device/${encodeURIComponent(n)}`),{}))}async function sD(e,t){return u(await c.get(Le(e,t,"status")))}async function Xl(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Zl(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function eu(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function tu(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function nu(e,t){return u(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function ru(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function su(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function ou(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function iu(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 au(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function cu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function lu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function uu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function pu(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function du(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function oD(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function iD(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function gu(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function mu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function sw(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 fu=sw;async function aD(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function yu(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function hu(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function cD(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function _u(e){return u(await c.get(`/projects/${e}/connector-moves`)).moves}async function bu(e,t,n={}){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/move`,n.connectionId?{connection_id:n.connectionId}:{}))}async function Su(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Pu(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 xu(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 lD(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 uD(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 Po(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 wu(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 xo(e,t){let n=new URLSearchParams({id:t});return u(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var pD=Po,dD=xo;async function vu(){return u(await c.get("/connectors/connect-status"))}async function ku(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 Au(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function gD(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function ow(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 Ru=ow;var kr=class extends S{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}},wo=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)}},vo=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)}},Ae=e=>typeof e=="string"&&e?e:null;function Cu(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function iw(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function aw(e,t,n){if(!(e instanceof S)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Ae(r.reason)??Ae(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 kr(Ae(r.message)??Ae(r.hint)??s,{status:e.status,code:i===null?Cu(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Ae(r.connector)??t,action:Ae(r.action)??n,binding:Ae(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:iw(e.response),connectUrl:Ae(r.connect_url),hint:Ae(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Ae(r.requested_account)})}function cw(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 ko(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 It(e,`${o}.${i}`,r,s)}catch(l){throw aw(l,o,i)}if(a.status==="pending_approval")throw new wo(o,i,a);if(!a.ok||a.upstream_error){let l=a.upstream_error??a.reason??"connector_error";throw new kr(l,{status:200,code:a.upstream_error?"upstream_error":Cu(l),details:a,data:a,reason:l,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return cw(a)}async function*Tu(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 vo(t,n,i,l);let d=await ko(e,t,n,l,a);yield d,l=o(d,l)}}async function Iu(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function Eu(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Mu(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Ou(e){return u(await c.get(`/projects/${e}/snapshots`))}async function Ar(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function ju(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Du(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Lu(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function $u(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Uu(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Fu(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Nu(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Rr(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 kt(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function Bu(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 Ku(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 qu(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 Gu(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 lw=10*6e4;async function Wu(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 Oe(o,{method:"GET"},{timeoutMs:lw},"Failed to download")).blob()}async function Hu(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Rr(`${I().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function MD(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 Oe(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}async function Vu(e,t){return u(await c.put(`/projects/${e}/files/content`,t,{showErrors:!1}))}var Ao=52428800,uw=104857600,zu=20;var Tr=e=>`/projects/${encodeURIComponent(e)}/attachments`,Ir={showErrors:!1,deadlineCoversBody:!0},Yu=3e4,pw=12e4,dw=6e4,gw=5*6e4,mw=6e4,fw=6e4;function Cr(){return new S("Request aborted",{name:"AbortError",code:"ABORTED"})}function an(e){if(e?.aborted)throw Cr()}function yw(e){return!(e instanceof S)||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 cn(e,t,n=!1){let r;for(let s=0;;s++){an(t);try{return await e()}catch(o){let i=n&&o instanceof S&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(yw(o)||i))throw o;r??=Date.now()+(n?gw:dw);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await pr(a,t)}catch{throw an(t),o}}}}function hw(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function Ro(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"&&hw(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 Ju(e,t,n,r){return u(await c.post(Tr(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Ir,signal:n,timeout:Yu}),"Failed to start attachment upload")}async function Qu(e,t,n,r){let s=Ro({...await cn(()=>Ju(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function Xu(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 S(r,{status:e,details:n,code:String(n?.statusCode??e)})}function _w(e){if(!(e instanceof S))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function bw(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 S("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},mw)},m=()=>{d(Cr()),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(Xu(i.status,i.responseText))},i.onerror=()=>d(new S("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(Cr()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function Sw(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"?Cr():new S(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw Xu(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function Pw(e,t,n){an(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?bw(r,e,t,n):Sw(e,t,n)}async function xw(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 cn(()=>Pw(i,t,r),r.signal)}catch(a){let l=_w(a);if(l!==409){if(o||!(l===400||l===401||l===403))throw a;o=!0,s=await Qu(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return Zu(e,t,s,r)}async function Zu(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${Tr(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){an(r.signal);let a=i.received_bytes,l=Math.min(a+s,t.size),p=t.slice(a,l),d=await cn(async()=>u(await c.putRaw(`${o}/chunks/${a/s}`,p,{...Ir,signal:r.signal,timeout:Yu}),"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 Er(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");an(n.signal);let r=n.resume?Ro({...n.resume},t):Ro({...await cn(()=>Ju(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()<fw&&(r=await Qu(e,t,r,n)),r=r.upload.kind==="direct"?await xw(e,t,r,n):await Zu(e,t,r,n)),n.onProcessing?.();let s=`${Tr(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await cn(async()=>u(await c.post(`${s}/complete`,{},{...Ir,signal:n.signal,timeout:pw}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof S&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function ln(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${Tr(e)}/${encodeURIComponent(t)}`,{...Ir,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function ep(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 tp(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 np(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function rp(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 sp(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 op(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 ip(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 ap(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function cp(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function lp(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function up(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function pp(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function dp(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function gp(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function mp(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function fp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function yp(e,t,n){return u(await c.patch(`/projects/${e}/change-requests/${t}`,n))}var Et=new Set,ww=500;function Mr(e){e&&(Et.add(e),Et.size>ww&&Et.delete(Et.values().next().value))}function hp(e){return!!e&&Et.has(e)}function HD(e){e&&Et.delete(e)}var ue="kortix.session/2",Se=1,vw=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),z=e=>typeof e=="string",Re=e=>z(e)&&e.length>0,Ue=e=>e===null||z(e),J=(e,t)=>e===void 0||t(e),$e=(...e)=>t=>e.includes(t),un=e=>Number.isInteger(e)&&e>=0,Mt=e=>typeof e=="number",Sp=e=>e.schema===ue&&un(e.v),gt=e=>J(e,z),Co=e=>e===void 0||re(e)&&Object.values(e).every(t=>re(t)&&z(t.version)),Pp=e=>e===null||re(e)&&z(e.provider)&&z(e.model)&>(e.variant),kw=e=>e===null||re(e)&&Mt(e.input)&&Mt(e.output)&&Mt(e.cache_read)&&Mt(e.cache_write)&&J(e.reasoning,Mt)&&J(e.cost,Mt),_p=e=>re(e)&&(e.type==="text"&&z(e.text)||e.type==="attachment"&&z(e.mime)),Aw=e=>re(e)&&Array.isArray(e.content)&&e.content.every(_p)&&J(e.model_content,t=>Array.isArray(t)&&t.every(_p))&&typeof e.is_error=="boolean",bp={text:e=>z(e.text)&&J(e.bytes,un)&>(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>z(e.text),attachment:e=>z(e.mime)&>(e.ref)&&J(e.bytes,un)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>z(e.call_id)&&z(e.name)&&Re(e.kind)&&$e("pending","running","complete","error")(e.status)&&J(e.result,Aw),compaction:e=>Ue(e.summary)&&Ue(e.first_kept_message_id),subtask:e=>z(e.thread_id)&&z(e.agent)&&z(e.description),step:e=>$e("start","finish")(e.phase),harness:e=>Re(e.harness)&&Re(e.kind)&&typeof e.model_visible=="boolean"};function Rw(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!re(r)||!Re(r.id)||n.has(r.id)||!Object.hasOwn(bp,r.type)||!bp[r.type](r)||!Co(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function To(e){return re(e)&&Sp(e)&&Re(e.message_id)&&Re(e.thread_id)&&Number.isInteger(e.seq)&&$e("user","assistant","system")(e.role)&&$e("turn","compaction","context")(e.kind)&&$e("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&J(e.hidden_reason,$e("failed_attempt","aborted","retracted","reverted","superseded"))&&J(e.origin,$e("prompt","steer","command","automation","subagent","notification"))&&J(e.agent,Ue)&&J(e.reply_to,Ue)&&J(e.parent_message_id,Ue)&>(e.native_agent_id)&>(e.context_ref)&&Pp(e.model)&&kw(e.usage)&&$e("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||re(e.error)&&Re(e.error.code)&&z(e.error.message))&&z(e.created_at)&&Ue(e.completed_at)&&re(e.producer)&&Re(e.producer.harness)&&z(e.producer.harness_version)&&z(e.producer.adapter_version)&&Co(e.ext)&&Rw(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function Io(e){return re(e)&&Sp(e)&&Re(e.thread_id)&&Ue(e.parent_thread_id)&&(e.spawned_by===null||re(e.spawned_by))&&z(e.created_at)}function Cw(e){return re(e)&&J(e.schema,t=>t===ue)&&J(e.v,un)&>(e.session_id)&&J(e.title,Ue)&>(e.created_at)&&J(e.restore_grade,$e("native","converted","partial"))&&J(e.todos,Array.isArray)&&J(e.pending,t=>re(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&J(e.selection,t=>re(t)&&J(t.agent,Ue)&&Pp(t.model??null))&&J(e.harness,t=>re(t)&&z(t.current)&&Array.isArray(t.history))&&Co(e.ext)}function Ot(e){return re(e)&&un(e.generation)&&typeof e.has_more=="boolean"&&Cw(e.session)&&Array.isArray(e.threads)&&e.threads.every(Io)&&(e.thread_id===null||Re(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>To(t)&&t.thread_id===e.thread_id)}var Tw=e=>Ot(e)&&e.messages.length>0;function Iw(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 xp={paintable:Tw,fit:Iw,capturedAt:()=>0},Ew=new WeakMap;function wp(e,t,n){Ew.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 Or(e){return!!e&&typeof e.then=="function"}function vp(e,t){return Or(e)?e.then(t):t(e)}function kp(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:s,now:o}=e,i=`${n}index`,a=T=>{try{let _=t.getItem(T);return Or(_)?_.catch(()=>null):_}catch{return null}},l=async T=>{try{await t.removeItem(T)}catch{}},p=T=>{if(!T)return[];try{let _=JSON.parse(T);return _?.v===1&&Array.isArray(_.entries)?_.entries:[]}catch{return[]}},d=Promise.resolve(),g=T=>{let _=d.then(T,T);return d=_.catch(()=>{}),_},m=async T=>{try{await t.setItem(i,JSON.stringify({v:1,entries:T}))}catch{}},f=async()=>p(await a(i));return{indexKey:i,safeGet:a,safeRemove:l,enqueue:g,loadIndex:f,saveIndex:m,evict:async(T,_)=>{let b=[...T].sort((y,w)=>y.u-w.u),O=b.reduce((y,w)=>y+w.b,0);for(;b.length>r||O>s;){let y=b.findIndex(x=>x.s!==_);if(y===-1)break;let[w]=b.splice(y,1);O-=w.b,await l(`${n}${w.s}`)}return b},touch:T=>{g(async()=>{let _=await f(),b=_.find(O=>O.s===T);b&&(b.u=o(),await m(_))})},forgetScope:T=>g(async()=>{await l(`${n}${T}`);let _=await f(),b=_.filter(O=>O.s!==T);b.length!==_.length&&await m(b)})}}function Mw(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 Ow=12,jw=15e5,Dw=3e5,Lw=336*60*60*1e3,Cp="kortix.saved-copy";function $w(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let s=a=>{let 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 Uw(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var Fw={paintable:Mw,fit:$w,capturedAt:Uw};function nL(e){let t=Rp(e,Fw),n=Rp({...e,namespace:`${e.namespace??Cp}.log`},xp),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 wp(r,n,t.remove),r}function Rp(e,t){let{storage:n,userId:r,maxSessions:s=Ow,maxBytes:o=jw,maxEnvelopeBytes:i=Dw,maxAgeMs:a=Lw,namespace:l=Cp,now:p=()=>Date.now()}=e,d=`${l}:${r}:`,g=kp({storage:n,prefix:d,maxSessions:s,maxBytes:o,now:p}),{indexKey:m,safeGet:f,safeRemove:h,enqueue:P,loadIndex:k,saveIndex:T,evict:_,touch:b,forgetScope:O}=g,y=(x,v)=>`${d}${x}/${v}`,w=x=>{try{let v=n.removeItem(x);Or(v)&&v.catch(()=>{})}catch{}};return{keyFor:y,read(x,v){let C=`${x}/${v}`;return vp(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):(b(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 le=t.capturedAt(C);return P(async()=>{let j=await k(),q=j.find(ct=>ct.s===D);if(q&&le>0&&q.c>le)return;let W=j.filter(ct=>ct.s!==D),K={s:D,b:L.length,u:p(),c:le},Me=await _([...W,K],D),Xs=y(x,v);try{await n.setItem(Xs,L)}catch{let ct=Me.filter(lt=>lt.s!==D).sort((lt,px)=>lt.u-px.u)[0];ct&&(await h(`${d}${ct.s}`),Me=Me.filter(lt=>lt.s!==ct.s));try{await n.setItem(Xs,L)}catch{await h(Xs),Me=Me.filter(lt=>lt.s!==D)}}await T(Me)})},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 Tp=null;function rL(e){Tp=e}function Ip(){return Tp}var Nw=new Set;function Ep(e){for(let t of Nw)try{t(e)}catch{}}var Bw=new Set;function Mp(e){for(let t of Bw)try{t(e)}catch{}}var pn=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},Kw=40;var qw="session_log_missing";async function Gw(e,t,n,r,s){try{let o=await e(t,n,r,s);return Ot(o)?o:null}catch(o){return o?.code===qw?"missing":null}}function Op(e,t,n,r){return Gw(e,t,n,{limit:Kw},r)}function yL(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 hL=50,Ww=200,_L=Ww;function jp(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 Dp(e,t){let n=await c.get(`/projects/${e}/sessions${jp(t)}`,{showErrors:!1});return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function jt(e,t){return u(await c.get(`/projects/${e}/sessions${jp(t)}`))}async function Lp(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function $p(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Up(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Fp(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Np(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Bp(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function bL(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 SL(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 Kp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function qp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Gp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Wp(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Dt(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return!t?.initial_prompt&&!t?.fork_from_session_id&&Mr(n?.session_id),n}async function Hp(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||Mr(r.session.session_id),r}async function Vp(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Mr(n.session_id),n}async function jr(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function zp(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 Yp(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 Dr(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 Jp(e,t,n={},r){let s;try{s=await pn(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!Ot(s))throw new Error("The response is not a session log page");return s}async function Lr(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function PL(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 Hw(e){if(e)return e==="interrupt"?"transcript":"composer"}async function $r(e,t,n){let r=n.placement??Hw(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 Qp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Xp(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Zp(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function ed(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function td(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function nd(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function rd(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function sd(e,t){let n=u(await c.delete(`/projects/${e}/sessions/${t}`));return Ip()?.remove(e,t),Mp(t),n}async function od(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function id(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Ur(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Fr(e,t){let n=u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}));return Ep(t),n}async function ad(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function Vw(e){let t=e.split(`
|
|
7
|
+
`);let m=Qx(g);if(m){if(t(m),m.type==="error")throw new S(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new S("Provision stream ended without a result",{code:Jx});return a}async function ij(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await c.get(`/projects/quota${t}`))}async function aj(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function xr(e,t){return u(await c.patch(`/projects/${e}`,t))}async function Kc(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function qc(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function Gc(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function cj(e,t){return u(await c.put(`/projects/${e}/default-reasoning-effort`,{effort:t}))}async function lj(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function uj(e,t){throw N("updateTemplateWarmPool")}async function Wc(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function pj(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function wr(e){return u(await c.delete(`/projects/${e}`))}async function dj(e,t){return u(await c.post(`/projects/${e}/transfer`,{account_id:t}))}async function gj(e,t){return Rt(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function mj(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=uo(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 Hc(e,t,n){return u(await c.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function Vc(e,t,n){return u(await c.post(`/projects/${e}/skills/remove`,t,{showErrors:!1,...n}))}async function Pj(e){return u(await c.get(`/projects/${e}/git/connection`),"Failed to read the Git connection")}async function zc(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function Yc(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Jc(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Qc(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Xc(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Zc(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 el(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 tl(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function nl(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function rl(e){return u(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function sl(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 ol(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function il(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 Cj(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function al(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function cl(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function ll(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function ul(e){return u(await c.get(`/projects/${e}/access`))}async function pl(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function dl(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function Tj(e){return"status"in e&&e.status==="invited"}async function gl(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 ml(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function fl(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function yl(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function hl(e){return u(await c.get(`/projects/${e}/group-grants`))}async function _l(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 bl(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 Sl(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function Pl(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function xl(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 wl(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function kl(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function vl(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Al(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 Rl(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Cl(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function Tl(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Il(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function El(e){return u(await c.get(`/projects/${e}/oauth`)).items??[]}async function go(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 mo(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Ml(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Xx=2e3,Zx=3e3,ew=10*6e4;async function Oj(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 go(t,n,r);if(l())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Xx,p.interval_ms||Zx),g=p.expires_at||a()+ew;for(;!l()&&a()<g;){if(await i(d),l())return{status:"cancelled"};let m;try{m=await mo(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 Ol(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function kr(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function jl(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Dl(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var fo=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,It=(e,t)=>`${fo(e)}/${encodeURIComponent(t)}`,Ll=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function $l(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${fo(e)}${n}`))}async function Ul(e,t){return u(await c.post(fo(e),t))}async function Fl(e,t,n){return u(await c.put(`${It(e,t)}/value`,{value:n}))}async function Nl(e,t){return u(await c.post(`${It(e,t)}/retry`))}async function Bl(e,t){return u(await c.delete(It(e,t)))}async function Kl(e,t,n,r){return u(await c.put(`${It(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function ql(e,t,n,r){return u(await c.delete(`${It(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function Gl(e,t,n,r){return u(await c.put(`${It(e,t)}/access`,{mode:n,user_ids:r}))}async function Wl(e,t,n){return u(await c.get(Ll(e,t,n)))}async function Hl(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function Vl(e,t,n,r){return u(await c.put(Ll(e,t,n),{secret_ids:r}))}async function yo(){return lo()}async function tw(e){return cr(()=>I().getToken(),e,ho)}function ho(){sn()}function Kj(e){e===null&&sn()}function qj(e){}async function on(){return yo()}async function Gj(e){return tw(e)}async function U(e,t,n){try{return await dt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof ie)return lr();throw r}}function vr(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function an(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(`${vr(e,"catalog")}${r}`)).connectors??[]}async function _o(e){let t=[];for(let n of await an(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 zl(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await _o(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 bo(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 an(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 nw(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 rw=9e4;async function Et(e,t,n={},r={}){let{connector:s,action:o}=nw(t),i=r.account?.trim(),a=r.approvalContext?.trim(),l=u(await c.post(vr(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??rw,signal:r.signal}));return l.ok&&l.binding!==void 0&&!("output"in l)&&(l.output=l.data),l}async function So(e,t){let n=await c.get(vr(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function sw(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 ow(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 Po(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=ow(I().backendUrl),a=vr(e,"attachments"),l=await U(`${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 S(sw(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 Qj(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 Yl(e){return u(await c.get(`/projects/${e}/connections`))}async function Jl(e){return u(await c.get(`/projects/${e}/connections/all`))}async function Ql(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function Xl(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function Zl(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function Le(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function Xj(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function Zj(e,t,n){return u(await c.put(Le(e,t,"application"),n))}async function eD(e,t){return u(await c.get(Le(e,t,"application")))}async function tD(e,t,n){return u(await c.post(Le(e,t,"discover"),n))}async function nD(e,t,n={}){return u(await c.post(Le(e,t,"discover-resource"),n))}async function rD(e,t,n){return u(await c.post(Le(e,t,"register"),n))}async function sD(e,t,n){return u(await c.post(Le(e,t,"authorize"),n))}async function oD(e,t,n){return u(await c.post(Le(e,t,"device"),n))}async function iD(e,t,n){return u(await c.post(Le(e,t,`device/${encodeURIComponent(n)}`),{}))}async function aD(e,t){return u(await c.get(Le(e,t,"status")))}async function eu(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function tu(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function nu(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function ru(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function su(e,t){return u(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function ou(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function iu(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function au(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function cu(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 lu(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function uu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function pu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function du(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function gu(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function mu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function cD(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function lD(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function fu(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function yu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function iw(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 hu=iw;async function uD(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function _u(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function bu(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function pD(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function Su(e){return u(await c.get(`/projects/${e}/connector-moves`)).moves}async function Pu(e,t,n={}){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/move`,n.connectionId?{connection_id:n.connectionId}:{}))}async function xu(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function wu(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 ku(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 dD(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 gD(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 xo(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 vu(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 wo(e,t){let n=new URLSearchParams({id:t});return u(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var mD=xo,fD=wo;async function Au(){return u(await c.get("/connectors/connect-status"))}async function Ru(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 Cu(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function yD(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function aw(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 Tu=aw;var Ar=class extends S{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}},ko=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)}},vo=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)}},Ae=e=>typeof e=="string"&&e?e:null;function Iu(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function cw(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function lw(e,t,n){if(!(e instanceof S)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Ae(r.reason)??Ae(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 Ar(Ae(r.message)??Ae(r.hint)??s,{status:e.status,code:i===null?Iu(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Ae(r.connector)??t,action:Ae(r.action)??n,binding:Ae(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:cw(e.response),connectUrl:Ae(r.connect_url),hint:Ae(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Ae(r.requested_account)})}function uw(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 Ao(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 Et(e,`${o}.${i}`,r,s)}catch(l){throw lw(l,o,i)}if(a.status==="pending_approval")throw new ko(o,i,a);if(!a.ok||a.upstream_error){let l=a.upstream_error??a.reason??"connector_error";throw new Ar(l,{status:200,code:a.upstream_error?"upstream_error":Iu(l),details:a,data:a,reason:l,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return uw(a)}async function*Eu(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 vo(t,n,i,l);let d=await Ao(e,t,n,l,a);yield d,l=o(d,l)}}async function Mu(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function Ou(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function ju(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Du(e){return u(await c.get(`/projects/${e}/snapshots`))}async function Rr(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Lu(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function $u(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Uu(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function Fu(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Nu(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Bu(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Ku(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Cr(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 At(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function qu(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 Gu(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 Wu(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 Hu(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 pw=10*6e4;async function Vu(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 Oe(o,{method:"GET"},{timeoutMs:pw},"Failed to download")).blob()}async function zu(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Cr(`${I().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function DD(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 Oe(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}async function Yu(e,t){return u(await c.put(`/projects/${e}/files/content`,t,{showErrors:!1}))}var Ro=52428800,dw=104857600,Ju=20;var Ir=e=>`/projects/${encodeURIComponent(e)}/attachments`,Er={showErrors:!1,deadlineCoversBody:!0},Qu=3e4,gw=12e4,mw=6e4,fw=5*6e4,yw=6e4,hw=6e4;function Tr(){return new S("Request aborted",{name:"AbortError",code:"ABORTED"})}function cn(e){if(e?.aborted)throw Tr()}function _w(e){return!(e instanceof S)||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 ln(e,t,n=!1){let r;for(let s=0;;s++){cn(t);try{return await e()}catch(o){let i=n&&o instanceof S&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(_w(o)||i))throw o;r??=Date.now()+(n?fw:mw);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await dr(a,t)}catch{throw cn(t),o}}}}function bw(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function Co(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"&&bw(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 Xu(e,t,n,r){return u(await c.post(Ir(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Er,signal:n,timeout:Qu}),"Failed to start attachment upload")}async function Zu(e,t,n,r){let s=Co({...await ln(()=>Xu(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function ep(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 S(r,{status:e,details:n,code:String(n?.statusCode??e)})}function Sw(e){if(!(e instanceof S))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function Pw(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 S("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},yw)},m=()=>{d(Tr()),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(ep(i.status,i.responseText))},i.onerror=()=>d(new S("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(Tr()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function xw(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"?Tr():new S(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw ep(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function ww(e,t,n){cn(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?Pw(r,e,t,n):xw(e,t,n)}async function kw(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 ln(()=>ww(i,t,r),r.signal)}catch(a){let l=Sw(a);if(l!==409){if(o||!(l===400||l===401||l===403))throw a;o=!0,s=await Zu(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return tp(e,t,s,r)}async function tp(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${Ir(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){cn(r.signal);let a=i.received_bytes,l=Math.min(a+s,t.size),p=t.slice(a,l),d=await ln(async()=>u(await c.putRaw(`${o}/chunks/${a/s}`,p,{...Er,signal:r.signal,timeout:Qu}),"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 Mr(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");cn(n.signal);let r=n.resume?Co({...n.resume},t):Co({...await ln(()=>Xu(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()<hw&&(r=await Zu(e,t,r,n)),r=r.upload.kind==="direct"?await kw(e,t,r,n):await tp(e,t,r,n)),n.onProcessing?.();let s=`${Ir(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await ln(async()=>u(await c.post(`${s}/complete`,{},{...Er,signal:n.signal,timeout:gw}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof S&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function un(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${Ir(e)}/${encodeURIComponent(t)}`,{...Er,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function np(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 rp(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 sp(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function op(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 ip(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 ap(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 cp(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 lp(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function up(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function pp(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function dp(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function gp(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function mp(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function fp(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function yp(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function hp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function _p(e,t,n){return u(await c.patch(`/projects/${e}/change-requests/${t}`,n))}var Mt=new Set,vw=500;function Or(e){e&&(Mt.add(e),Mt.size>vw&&Mt.delete(Mt.values().next().value))}function bp(e){return!!e&&Mt.has(e)}function YD(e){e&&Mt.delete(e)}var ue="kortix.session/2",Se=1,Aw=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Y=e=>typeof e=="string",Re=e=>Y(e)&&e.length>0,Ue=e=>e===null||Y(e),Q=(e,t)=>e===void 0||t(e),$e=(...e)=>t=>e.includes(t),pn=e=>Number.isInteger(e)&&e>=0,Ot=e=>typeof e=="number",xp=e=>e.schema===ue&&pn(e.v),gt=e=>Q(e,Y),To=e=>e===void 0||re(e)&&Object.values(e).every(t=>re(t)&&Y(t.version)),wp=e=>e===null||re(e)&&Y(e.provider)&&Y(e.model)&>(e.variant),Rw=e=>e===null||re(e)&&Ot(e.input)&&Ot(e.output)&&Ot(e.cache_read)&&Ot(e.cache_write)&&Q(e.reasoning,Ot)&&Q(e.cost,Ot),Sp=e=>re(e)&&(e.type==="text"&&Y(e.text)||e.type==="attachment"&&Y(e.mime)),Cw=e=>re(e)&&Array.isArray(e.content)&&e.content.every(Sp)&&Q(e.model_content,t=>Array.isArray(t)&&t.every(Sp))&&typeof e.is_error=="boolean",Pp={text:e=>Y(e.text)&&Q(e.bytes,pn)&>(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>Y(e.text),attachment:e=>Y(e.mime)&>(e.ref)&&Q(e.bytes,pn)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>Y(e.call_id)&&Y(e.name)&&Re(e.kind)&&$e("pending","running","complete","error")(e.status)&&Q(e.result,Cw),compaction:e=>Ue(e.summary)&&Ue(e.first_kept_message_id),subtask:e=>Y(e.thread_id)&&Y(e.agent)&&Y(e.description),step:e=>$e("start","finish")(e.phase),harness:e=>Re(e.harness)&&Re(e.kind)&&typeof e.model_visible=="boolean"};function Tw(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!re(r)||!Re(r.id)||n.has(r.id)||!Object.hasOwn(Pp,r.type)||!Pp[r.type](r)||!To(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function Io(e){return re(e)&&xp(e)&&Re(e.message_id)&&Re(e.thread_id)&&Number.isInteger(e.seq)&&$e("user","assistant","system")(e.role)&&$e("turn","compaction","context")(e.kind)&&$e("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&Q(e.hidden_reason,$e("failed_attempt","aborted","retracted","reverted","superseded"))&&Q(e.origin,$e("prompt","steer","command","automation","subagent","notification"))&&Q(e.agent,Ue)&&Q(e.reply_to,Ue)&&Q(e.parent_message_id,Ue)&>(e.native_agent_id)&>(e.context_ref)&&wp(e.model)&&Rw(e.usage)&&$e("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||re(e.error)&&Re(e.error.code)&&Y(e.error.message))&&Y(e.created_at)&&Ue(e.completed_at)&&re(e.producer)&&Re(e.producer.harness)&&Y(e.producer.harness_version)&&Y(e.producer.adapter_version)&&To(e.ext)&&Tw(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function Eo(e){return re(e)&&xp(e)&&Re(e.thread_id)&&Ue(e.parent_thread_id)&&(e.spawned_by===null||re(e.spawned_by))&&Y(e.created_at)}function Iw(e){return re(e)&&Q(e.schema,t=>t===ue)&&Q(e.v,pn)&>(e.session_id)&&Q(e.title,Ue)&>(e.created_at)&&Q(e.restore_grade,$e("native","converted","partial"))&&Q(e.todos,Array.isArray)&&Q(e.pending,t=>re(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&Q(e.selection,t=>re(t)&&Q(t.agent,Ue)&&wp(t.model??null))&&Q(e.harness,t=>re(t)&&Y(t.current)&&Array.isArray(t.history))&&To(e.ext)}function jt(e){return re(e)&&pn(e.generation)&&typeof e.has_more=="boolean"&&Iw(e.session)&&Array.isArray(e.threads)&&e.threads.every(Eo)&&(e.thread_id===null||Re(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>Io(t)&&t.thread_id===e.thread_id)}var Ew=e=>jt(e)&&e.messages.length>0;function Mw(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 kp={paintable:Ew,fit:Mw,capturedAt:()=>0},Ow=new WeakMap;function vp(e,t,n){Ow.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 jr(e){return!!e&&typeof e.then=="function"}function Ap(e,t){return jr(e)?e.then(t):t(e)}function Rp(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:s,now:o}=e,i=`${n}index`,a=T=>{try{let _=t.getItem(T);return jr(_)?_.catch(()=>null):_}catch{return null}},l=async T=>{try{await t.removeItem(T)}catch{}},p=T=>{if(!T)return[];try{let _=JSON.parse(T);return _?.v===1&&Array.isArray(_.entries)?_.entries:[]}catch{return[]}},d=Promise.resolve(),g=T=>{let _=d.then(T,T);return d=_.catch(()=>{}),_},m=async T=>{try{await t.setItem(i,JSON.stringify({v:1,entries:T}))}catch{}},f=async()=>p(await a(i));return{indexKey:i,safeGet:a,safeRemove:l,enqueue:g,loadIndex:f,saveIndex:m,evict:async(T,_)=>{let b=[...T].sort((y,w)=>y.u-w.u),O=b.reduce((y,w)=>y+w.b,0);for(;b.length>r||O>s;){let y=b.findIndex(x=>x.s!==_);if(y===-1)break;let[w]=b.splice(y,1);O-=w.b,await l(`${n}${w.s}`)}return b},touch:T=>{g(async()=>{let _=await f(),b=_.find(O=>O.s===T);b&&(b.u=o(),await m(_))})},forgetScope:T=>g(async()=>{await l(`${n}${T}`);let _=await f(),b=_.filter(O=>O.s!==T);b.length!==_.length&&await m(b)})}}function jw(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 Dw=12,Lw=15e5,$w=3e5,Uw=336*60*60*1e3,Ip="kortix.saved-copy";function Fw(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 Nw(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var Bw={paintable:jw,fit:Fw,capturedAt:Nw};function oL(e){let t=Tp(e,Bw),n=Tp({...e,namespace:`${e.namespace??Ip}.log`},kp),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 vp(r,n,t.remove),r}function Tp(e,t){let{storage:n,userId:r,maxSessions:s=Dw,maxBytes:o=Lw,maxEnvelopeBytes:i=$w,maxAgeMs:a=Uw,namespace:l=Ip,now:p=()=>Date.now()}=e,d=`${l}:${r}:`,g=Rp({storage:n,prefix:d,maxSessions:s,maxBytes:o,now:p}),{indexKey:m,safeGet:f,safeRemove:h,enqueue:P,loadIndex:v,saveIndex:T,evict:_,touch:b,forgetScope:O}=g,y=(x,k)=>`${d}${x}/${k}`,w=x=>{try{let k=n.removeItem(x);jr(k)&&k.catch(()=>{})}catch{}};return{keyFor:y,read(x,k){let C=`${x}/${k}`;return Ap(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):(b(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 le=t.capturedAt(C);return P(async()=>{let j=await v(),q=j.find(ct=>ct.s===D);if(q&&le>0&&q.c>le)return;let W=j.filter(ct=>ct.s!==D),K={s:D,b:L.length,u:p(),c:le},Me=await _([...W,K],D),Zs=y(x,k);try{await n.setItem(Zs,L)}catch{let ct=Me.filter(lt=>lt.s!==D).sort((lt,gx)=>lt.u-gx.u)[0];ct&&(await h(`${d}${ct.s}`),Me=Me.filter(lt=>lt.s!==ct.s));try{await n.setItem(Zs,L)}catch{await h(Zs),Me=Me.filter(lt=>lt.s!==D)}}await T(Me)})},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 Ep=null;function iL(e){Ep=e}function Mp(){return Ep}var Kw=new Set;function Op(e){for(let t of Kw)try{t(e)}catch{}}var qw=new Set;function jp(e){for(let t of qw)try{t(e)}catch{}}var dn=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},Gw=40;var Ww="session_log_missing";async function Hw(e,t,n,r,s){try{let o=await e(t,n,r,s);return jt(o)?o:null}catch(o){return o?.code===Ww?"missing":null}}function Dp(e,t,n,r){return Hw(e,t,n,{limit:Gw},r)}function bL(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 SL=50,Vw=200,PL=Vw;function Lp(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 $p(e,t){let n=await c.get(`/projects/${e}/sessions${Lp(t)}`,{showErrors:!1});return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Dt(e,t){return u(await c.get(`/projects/${e}/sessions${Lp(t)}`))}async function Up(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Fp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Np(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function Bp(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Kp(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function qp(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function xL(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 wL(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 Gp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function Wp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Hp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Vp(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}function Mo(e,t,n){return`/projects/${e}/sessions/${t}/turns/${encodeURIComponent(n)}/share`}async function kL(e,t,n){return u(await c.get(Mo(e,t,n),{showErrors:!1}))}async function vL(e,t,n,r){return u(await c.put(Mo(e,t,n),{include_prompt:r?.include_prompt===!0},{showErrors:!1}))}async function AL(e,t,n){return u(await c.delete(Mo(e,t,n),{showErrors:!1}))}async function Lt(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return!t?.initial_prompt&&!t?.fork_from_session_id&&Or(n?.session_id),n}async function zp(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||Or(r.session.session_id),r}async function Yp(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Or(n.session_id),n}async function Dr(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Jp(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 Qp(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 Lr(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 Xp(e,t,n={},r){let s;try{s=await dn(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!jt(s))throw new Error("The response is not a session log page");return s}async function $r(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function RL(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 zw(e){if(e)return e==="interrupt"?"transcript":"composer"}async function Ur(e,t,n){let r=n.placement??zw(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 Zp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function ed(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function td(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function nd(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function rd(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function sd(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function od(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function id(e,t){let n=u(await c.delete(`/projects/${e}/sessions/${t}`));return Mp()?.remove(e,t),jp(t),n}async function ad(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function cd(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Fr(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Nr(e,t){let n=u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}));return Op(t),n}async function ld(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function Yw(e){let t=e.split(`
|
|
8
8
|
`).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).replace(/^ /,""));if(t.length===0)return null;try{return JSON.parse(t.join(`
|
|
9
|
-
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function
|
|
9
|
+
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function ud(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function pd(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 S(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=Vw(f);if(h){if(r(h),h.type==="error")throw new S(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 ud(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function pd(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function dd(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Nr(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function gd(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function md(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function wL(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 fd(e){return u(await c.get(`/projects/${e}/triggers`))}async function yd(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function hd(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function _d(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function RL(e){return u(await c.get(`/accounts/${e}/automations`))}async function CL(e,t){return u(await c.patch(`/accounts/${e}/automations`,{paused:t},{showErrors:!1}))}async function bd(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function Sd(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 Pd(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 xd(e,t,n){return u(await c.get(`/projects/${e}/triggers/${t}/runs${Sd(n)}`))}async function wd(e,t){return u(await c.get(`/projects/${e}/trigger-runs${Sd(t)}`))}async function vd(e,t,n,r){return u(await c.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function kd(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 Ad(e){return u(await c.get(`/projects/${e}/triggers/event-apps`))}var Xe=new Map;function Eo(e,t){return`${e}::${t}`}function Rd(e,t){Xe.delete(e),Xe.set(e,t)}function Cd(e,t){let n=Eo(e,t),r=Xe.get(n);return r&&Rd(n,r),r}function Br(e,t,n){let r=Eo(e,t);if(!Xe.has(r)&&Xe.size>=512){let s=Xe.keys().next().value;s!==void 0&&Xe.delete(s)}Rd(r,n)}function Td(e,t){Xe.delete(Eo(e,t))}function zw(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function dn(){return zw(I().backendUrl||"http://localhost:8008/v1")}function Id(){let e=I().sandboxId;return e?`${dn()}/p/${e}/8000`:""}function Yw(e,t=8e3){return`${dn()}/p/${e}/${t}`}function Fe(e,t=8e3){return Yw(e,t)}function Ed(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 Mo=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 $L(e){return e instanceof Error&&e.name==="SessionStartError"}function Jw(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 Mo(s,{status:n,code:r,terminal:!0}):null}function Md(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 mt(e,t,n){let r=await Md(e,t,n);if(!r.success||!r.data){let s=Jw(r.error);if(s&&!(s.status===404&&hp(t)))throw s;return null}return jd(e,t,r.data)}async function Od(e,t,n){let r=await Md(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return jd(e,t,r.data)}function jd(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Br(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Fe(r),sandboxId:r}),n}function UL(e,t){return["session-start",e,t]}async function Dd(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function Ld(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function $d(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 WL(e,t){return u(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Ud(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Qw(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Kr(e){let t=e.connectors_required?Ud(e.connectors_required):void 0,n=e.connectors_personal?Ud(e.connectors_personal):void 0;if(t&&n&&!Qw(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 Fd(e,t,n){let r=Kr(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function t$(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Oo(n.block):null}}async function n$(e,t,n){let r=Oo(n,!0),s=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Oo(s.block):null}}function Oo(e,t=!1){let n=Kr(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 r$(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Nd(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}var qr="Use setBillingPlan().",Bd="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Kd(){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 Xw(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function c$(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??Kd(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:Xw(r),label:s,sublabel:null,monthlyUsd:null}}function Zw(e){return!!e&&e.can_manage_billing!==!1}function l$(e){return e?.subscription?.can_purchase_credits===!0&&Zw(e)}async function qd(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?Kd():t.data}function Gd(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 Wd(e){return qd(`/billing/account-state${Gd(e)}`)}async function Hd(e){return qd(`/billing/account-state/minimal${Gd(e)}`)}async function Vd(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 zd(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 Yd(){return u(await c.get("/billing/credit-breakdown"))}async function Jd(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function Qd(){return u(await c.get("/billing/tier-configurations"))}async function u$(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return At(e,`/v1/billing/account-state${t}`)}async function Xd(e){throw N("createCheckoutSession",qr)}async function Zd(e,t){throw N("confirmCheckoutSession",qr)}async function eg(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function tg(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function ng(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function rg(e,t,n){throw N("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function sg(e){throw N("cancelScheduledChange",Bd)}async function og(e,t){throw N("getProrationPreview",Bd)}async function ig(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 ag(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 p$(e){return u(await c.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function cg(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 d$(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 lg(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 ug(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 pg(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 dg(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 g$(e){throw N("createPerSeatCheckout",qr)}async function m$(e){throw N("claimPerSeatBilling",qr)}async function f$(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function gg(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 jo(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Gr(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Wr(e){return e.size>0?`?${e}`:""}async function fg(e={}){let t=new URLSearchParams;return jo(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Gr(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${Wr(t)}`))}async function Hr(e,t={}){let n=new URLSearchParams;return jo(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Wr(n)}`))}async function P$(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Gr(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${Wr(t)}`))}async function x$(e={}){let t=new URLSearchParams;return jo(t,e),e.sessionId&&t.set("session_id",e.sessionId),Gr(t,e),u(await c.get(`/usage/cost-summary${Wr(t)}`))}function mg(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)}Gr(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 w$(e,t={}){let n=mg(e==="projects"?"projects":"sessions",t),r=await Oe(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 yg(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function R$(e){return yg("slack",e)}function C$(e){return yg("teams",e)}async function hg(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function T$(e){return hg("slack",e)}function I$(e){return hg("teams",e)}async function _g(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function bg(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var ev={oauth_available:!1,install_url:null};async function Sg(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?ev:t.data}async function Pg(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 xg(e,t){return Pg("slack",e,t)}function wg(e,t){return Pg("teams",e,t)}async function vg(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function kg(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 E$(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/telegram/installation`,{showErrors:!1});return t.success?t.data??null:null}async function M$(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/telegram/connect`,t,{showErrors:!1}),"Failed to connect Telegram")}async function O$(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 j$(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 Ag(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 Rg(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 Do(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 tv={provider:"agentmail",managed_available:!1};async function Cg(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?Do(r.data):null}async function Tg(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?tv:t.data}async function Ig(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return Do(n)}async function Eg(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 Mg(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 Do(r)}async function D$(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function L$(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 Og(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function jg(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Dg(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Lg(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function $g(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 Ug(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Fg(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ng(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Bg(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Kg(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function qg(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Gg(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Wg(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Hg(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Vg(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function zg(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Yg(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Jg(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 N$(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function q$(){throw N("getReferralCode")}async function G$(){throw N("refreshReferralCode")}async function W$(e){throw N("validateReferralCode")}async function H$(){throw N("getReferralStats")}async function V$(e={}){throw N("listReferrals")}async function z$(e){throw N("sendReferralEmails")}var Lo="call:";function Xg(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Lo)&&e.length>Lo.length?{type:"connector_call",executionId:e.slice(Lo.length)}:{type:"review_item",reviewItemId:e}}function nv(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function J$(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[nv(n.status)]+=1;return t}function Q$(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 $o(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Zg(e){let t=e.indexOf(".");return t<=0?$o(e):`(${$o(e.slice(0,t))}) ${$o(e.slice(t+1))}`}function rv(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Lt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},$=e=>typeof e=="string"&&e?e:void 0,Ce=e=>Array.isArray(e)?e:void 0,Qg=e=>typeof e=="number"?e:0,sv=e=>e.split(`
|
|
14
|
-
`).map(t=>t.trim()).filter(Boolean);function ov(e,t){let n=Lt(e.advanced),r=$(e.description),s=Ce(e.whatChanged)??(r?sv(r):t.summary?[t.summary]:[]);return{crId:$(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:$(e.impact)??"",verification:Ce(e.verification)??[],previewUrl:$(e.previewUrl)??$(e.preview_url),conflicts:Ce(e.conflicts),requestedChanges:Ce(e.requested_changes)??[],advanced:{headRef:$(n.headRef)??$(e.head_ref)??"",baseRef:$(n.baseRef)??$(e.base_ref)??"",headSha:$(n.headSha)??$(e.head_sha)??$(e.head_commit_sha)??"",baseSha:$(n.baseSha)??$(e.base_sha)??"",additions:Qg(n.additions),deletions:Qg(n.deletions),files:Ce(n.files)??[],mergeMode:$(n.mergeMode)??"merge"}}}function iv(e,t){let n=Ce(e.actions);if(n)return{actions:n.map((l,p)=>({id:$(l.id)??`${t.review_item_id}-${p}`,title:$(l.title)??"Action",connector:$(l.connector)??"",action:$(l.action)??"",consequence:$(l.consequence)??"",risk:$(l.risk)??t.risk,icon:$(l.icon)??"generic",argsPreview:Ce(l.argsPreview)??[],policySource:$(l.policySource)??"Requires approval",decided:l.decided==="approved"||l.decided==="denied"?l.decided:void 0}))};let r=$(e.action_path)??"",{connector:s,action:o}=rv(r),i=Lt(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:$(e.execution_id)??t.review_item_id,title:r?Zg(r):t.title||"Run action",connector:s,connectorName:$(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:$(e.approval_context),...Object.keys(Lt(e.resolved_preview)).length>0?{resolvedPreview:Lt(e.resolved_preview)}:{},...$(e.resolved_error)?{resolvedError:$(e.resolved_error)}:{},connectorRisk:$(e.risk)??null,policySource:"Requires approval",expiresAt:$(t.expires_at)}]}}function av(e,t){return{artifactKind:$(e.artifactKind)??"document",artifactLabel:$(e.artifactLabel)??"Output",previewUrl:$(e.previewUrl)??$(e.preview_url),preview:$(e.preview),files:Ce(e.files),note:$(e.note)??t.summary??""}}function cv(e,t){return{question:$(e.question)??t.title??"",context:$(e.context),options:Ce(e.options)??[]}}function lv(e,t){return{note:$(e.note)??t.summary??"",children:Ce(e.children)??[]}}function uv(e){let t=Lt(e.detail);switch(e.kind){case"change":return ov(t,e);case"approval":return iv(t,e);case"output":return av(t,e);case"decision":return cv(t,e);case"batch":return lv(t,e)}}function pv(e,t){let n=typeof e.number=="number"?e.number:void 0,r=$(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function X$(e,t={}){let n=Lt(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?$(n.action_path):void 0,i=e.kind==="change"?pv(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?Zg(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:$(e.expires_at),detail:uv(e)}}var Z={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"},t0=[Z.PROJECT_WRITE,Z.PROJECT_TRIGGER_CREATE,Z.PROJECT_TRIGGER_FIRE,Z.PROJECT_TRIGGER_UPDATE,Z.PROJECT_TRIGGER_DELETE];function n0(e){let t=r=>e[r]?.allowed===!0,n=t(Z.PROJECT_WRITE);return{canCreate:n&&t(Z.PROJECT_TRIGGER_CREATE),canFire:t(Z.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(Z.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(Z.PROJECT_TRIGGER_DELETE)}}var r0=[Z.PROJECT_WRITE,Z.PROJECT_GITOPS_PUSH,Z.PROJECT_GITOPS_MERGE,Z.PROJECT_REVIEW_ACT];function dv(e){let t=r=>e[r]?.allowed===!0,n=t(Z.PROJECT_WRITE);return{canOpen:n&&t(Z.PROJECT_GITOPS_PUSH),canMerge:n&&t(Z.PROJECT_GITOPS_MERGE),canClose:n}}function s0(e,t,n){let r=Xg(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 dv(n).canMerge}return n[Z.PROJECT_WRITE]?.allowed===!0&&n[Z.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 em(e){return A(await F(`/accounts/${e}/iam/groups`)).groups}async function tm(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}`))}async function nm(e,t){return A(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function rm(e,t,n){return A(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function sm(e,t){return A(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function om(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/members`)).members}async function im(e,t,n){return A(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function p0(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function am(e,t,n){return A(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function d0(e,t){return A(await F(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function g0(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 Ze(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function _0(e,t={}){let n=Ze({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 w0(e,t={}){let n=Ze({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 v0(e,t){return A(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function k0(e,t,n){return A(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function A0(e,t){return A(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function R0(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function C0(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function cm(e){return A(await F(`/accounts/${e}/iam/roles`)).roles}async function lm(e){return A(await F(`/accounts/${e}/iam/agent-identities`)).agents}async function um(e){return A(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function pm(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/permissions`))}async function M0(e){return A(await F(`/accounts/${e}/iam/actions`)).actions}async function dm(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/usage`))}async function gm(e,t){return A(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function mm(e,t,n){return A(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function fm(e,t,n){return A(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function ym(e,t){return A(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function O0(e,t,n){return A(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function $0(e){return A(await F(`/accounts/${e}/iam/scim/tokens`)).tokens}async function U0(e,t){return A(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function F0(e,t){return A(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function q0(e){return A(await F(`/accounts/${e}/iam/mfa-required`))}async function G0(e){return A(await F(`/accounts/${e}/iam/mfa-required/preview`))}async function W0(e,t){return A(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function H0(e){return A(await F(`/accounts/${e}/iam/session-oversight`))}async function V0(e,t){return A(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function Q0(e){return A(await F(`/accounts/${e}/iam/sso/provider`)).provider}async function X0(e,t){return A(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function Z0(e,t){return A(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function eU(e){return A(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function tU(e){return A(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function nU(e){return A(await F(`/accounts/${e}/iam/sso/mappings`)).mappings}async function rU(e,t){return A(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function sU(e,t){return A(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function cU(e){return A(await F(`/accounts/${e}/iam/session-policy`))}async function lU(e,t){return A(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function uU(e){return A(await F(`/accounts/${e}/iam/sessions`)).sessions}async function pU(e,t){return A(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function dU(e){return A(await F(`/accounts/${e}/iam/pat-policy`))}async function gU(e,t){return A(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function hU(e){return A(await F(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function _U(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function bU(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function SU(e,t){return A(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function kU(e){return A(await F(`/accounts/${e}/audit/webhooks`)).webhooks}async function AU(e,t){return A(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function RU(e,t,n){return A(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function CU(e,t){return A(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function TU(e,t={}){let n=Ze({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return A(await F(`/accounts/${e}/audit${n}`))}async function hm(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 _m(e,t,n){return n.length===0?[]:A(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function LU(e){return A(await F(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function $U(e,t){return A(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function bm(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function Sm(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function Pm(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function xm(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function wm(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function vm(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function gv(e){return Ze({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function km(e,t){return u(await F(`/accounts/${e}/iam/assignments${gv(t)}`)).assignments}async function Am(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 Rm(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function Cm(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await F(`/accounts/${e}/iam/permissions${n}`)).permissions}async function YU(){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 JU(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function QU(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function XU(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function ZU(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function rF(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function sF(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function oF(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function iF(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function aF(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function cF(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function lF(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var Tm="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function dF(e){throw N("getGoogleAuthUrl",Tm)}async function gF(e,t){throw N("convertPresentationToGoogleSlides",Tm)}async function Im(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 Em(e){return u(await c.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function Mm(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function Om(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function jm(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function Dm(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}async function Lm(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function $m(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 Um(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 Uo=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Fm(e,t=""){return`${dn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Nm(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 Uo(s,t.status)}return r}async function xF(e){return Nm(Fm(e))}async function wF(e){return Nm(Fm(e,"/messages"))}async function Bm(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function Km(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Fo(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function No(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}async function qm(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders/${n}/run`,{}))}var mv=4;async function Gm(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(mv,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 Wm(e,t,n){return Gm(t,r=>Fo(e,r.sessionId,r.reminderId,n))}function Hm(e,t){return Gm(t,n=>No(e,n.sessionId,n.reminderId))}async function Vr(e){return u(await c.get(`/projects/${e}/reminders`))}var Pe=e=>`/projects/${e}/rooms`;function Bo(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 Vm(e,t={}){return u(await c.get(`${Pe(e)}${Bo({name:t.name,archived:t.archived,mine:t.mine})}`))}async function zm(e,t){return u(await c.post(Pe(e),t))}async function Ym(e,t){return u(await c.get(`${Pe(e)}/${t}`))}async function Jm(e,t,n){return u(await c.patch(`${Pe(e)}/${t}`,n))}async function Qm(e,t,n={}){return u(await c.get(`${Pe(e)}/${t}/messages${Bo({after:n.after,before:n.before,limit:n.limit,top:n.top,thread:n.thread})}`))}async function Xm(e,t,n){return u(await c.post(`${Pe(e)}/${t}/messages`,n))}async function Zm(e,t,n){return u(await c.post(`${Pe(e)}/${t}/read`,n===void 0?{}:{seq:n}))}async function ef(e,t,n,r={}){return u(await c.put(`${Pe(e)}/${t}/members/sessions/${n}`,r))}async function tf(e,t,n){return u(await c.delete(`${Pe(e)}/${t}/members/sessions/${n}`))}async function nf(e,t,n,r={}){return u(await c.put(`${Pe(e)}/${t}/members/people/${n}`,r))}async function rf(e,t,n){return u(await c.delete(`${Pe(e)}/${t}/members/people/${n}`))}async function sf(e,t){return u(await c.get(`${Pe(e)}/people${Bo({q:t})}`))}async function of(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 OF(e){return u(await c.post("/cli/device/decide",{user_code:e,approve:!0}))}async function af(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 cf(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 lf(){return u(await c.get("/oauth/grants")).grants}async function uf(e){return u(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function jF(){return u(await c.get("/accounts/me/devices")).devices}async function DF(e){return u(await c.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function pf(e){return u(await c.get(`/projects/${e}/cli-token`))}async function df(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function gf(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}function $t(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 Ko(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 mf(e,t){let n=$t(Ko(t)).toString();return u(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function ff(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 yf(e,t){let n=$t(Ko({...t,projectId:void 0})).toString();return u(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function hf(e,t){let n=$t(Ko(t)).toString();return u(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function _f(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function bf(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function Sf(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Pf(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function xf(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 wf(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 GF(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function vf(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 kf(){return u(await c.get("/marketplace/marketplaces"))}async function Af(){return u(await c.get("/marketplace/marketplaces/featured"))}async function Rf(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Cf(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Tf(){return u(await c.get("/marketplace/sources"))}async function If(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Ef(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function zF(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function QF(e){throw N("getTemplate")}async function XF(e,t){throw N("installTemplate")}async function Mf(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Of(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function qo(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function jf(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Df(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Lf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function $f(e,t){let n=await qo(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 Uf(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Ff(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 Nf(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Bf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Go(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Wo(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function fv(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function yv(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 Kf(e,t,n={}){let r=await fv(t),s=n.mediaType??"application/gzip",o=await Go(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),Wo(e,o.artifact.artifact_id,{sha256:await yv(r),size_bytes:r.byteLength})}async function qf(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Gf(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Wf(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Hf(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 Vf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function zf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Yf(e,t,n){return u(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Jf(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var ye=(e,t)=>`/projects/${e}/apps/${t}`;async function Qf(e,t){return u(await c.get(`${ye(e,t)}/machines`),"Failed to list machines").machines}async function Ho(e,t,n,r){return u(await c.post(`${ye(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var Xf=(e,t,n)=>Ho(e,t,n,"start"),Zf=(e,t,n)=>Ho(e,t,n,"stop"),ey=(e,t,n)=>Ho(e,t,n,"restart");async function ty(e,t,n){return u(await c.delete(`${ye(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function ny(e,t,n,r={}){return u(await c.put(`${ye(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function ry(e,t,n){return u(await c.post(`${ye(e,t)}/exec`,n),"Failed to run the command")}async function sy(e,t){return u(await c.get(`${ye(e,t)}/volumes`),"Failed to list volumes").volumes}async function oy(e,t,n){return u(await c.post(`${ye(e,t)}/volumes`,n),"Failed to create the volume")}async function iy(e,t,n,r){return u(await c.patch(`${ye(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function ay(e,t,n,r){u(await c.delete(`${ye(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function cy(e,t,n){return u(await c.get(`${ye(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function ly(e,t,n){return u(await c.post(`${ye(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function uy(e,t,n,r){return u(await c.post(`${ye(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function py(e,t,n,r){return u(await c.post(`${ye(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function pe(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 dy(e){let t=u(await c.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new S("Files not found",{status:404});return t[0]}async function gN(e,t){return u(await c.get(`${ge(e)}/access?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load sharing")}async function mN(e,t){return u(await c.put(`${ge(e)}/access`,t),"Failed to share folder")}async function fN(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 yN(e){return u(await c.get(`${ge(e)}/principals`),"Failed to load people")}async function hN(e){return u(await c.get(`${ge(e)}/conflicts`),"Failed to load conflicts").conflicts}async function _N(e,t){u(await c.post(`${ge(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function bN(e,t="/"){return(await Vo(e,t)).entries}async function Vo(e,t="/"){return u(await c.get(`${ge(e)}/files?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load files")}function gy(e,t,n){let r=pe(I().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${ge(e)}/files/content?${new URLSearchParams(s)}`}async function SN(e,t,n){let r=await U(gy(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new S(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function my(e,t,n){let r=await U(gy(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new S(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function PN(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 hv(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 hv(e,t,n,r,s,o){let i=`${pe(I().backendUrl)}${t}`,{headers:a,rejected:l}=await kt(i,{"Content-Type":"application/octet-stream",...r});return new Promise((p,d)=>{let g=new e,m=()=>new S("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 S(P?.message||"Failed to upload file",{status:g.status,code:P?.code,url:i}))},g.onerror=()=>{h(),d(new S("Network error while uploading",{name:"TypeError",url:i}))},g.onabort=()=>{h(),d(m())},g.send(n)})}async function xN(e,t){return u(await c.post(`${ge(e)}/files/mkdir`,{path:t},{showErrors:!1}),"Failed to create folder")}async function wN(e,t,n){return u(await c.post(`${ge(e)}/files/move`,{from:t,to:n},{showErrors:!1}),"Failed to move")}async function vN(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 kN(e){return u(await c.get(`${ge(e)}/versions`),"Failed to load versions").versions}async function AN(e,t){u(await c.post(`${ge(e)}/restore`,{versionId:t}),"Failed to restore version")}var _v=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function RN(e,t){return(await bv(e,t)).drives}async function bv(e,t){return u(await c.get(_v(e,t)),"Failed to load session files")}var Sv=new Set(["done","abandoned"]),Pv=15*6e4,xv=24*36e5;function wv(e,t,n=Date.now()){if(!e)return{state:"attention",issues:["unreadable"]};if(Sv.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-Pv&&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-xv&&r.push("verification_stalled")}return{state:r.length?"attention":"healthy",issues:r}}async function vv(e,t){try{let{entries:n}=await Vo(e,t);return n.filter(r=>r.type==="dir").map(r=>r.path)}catch(n){if(n instanceof S&&n.status===404)return[];throw n}}async function zr(e,t){try{return await(await my(e,t)).blob.text()}catch(n){if(n instanceof S&&n.status===404)return null;throw n}}function kv(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 Av(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 MN(e,t){let n=await dy(e).catch(l=>{if(l instanceof S&&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 vv(n.driveId,l.path)).sort().map(p=>({...l,folder:p}))))).flat();if(s.length===0)return[];let[{reminders:o},i]=await Promise.all([Vr(e),Promise.all(s.map(l=>zr(n.driveId,`${l.folder}/goal.json`).then(kv)))]),a=t?.now??Date.now();return s.map((l,p)=>{let d=i[p]??null,g=l.folder.split("/").at(-1)??l.folder,m=Av(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:wv(d,m,a)}})}async function ON(e,t){let[n,r,s]=await Promise.all([zr(e,`${t}/log.md`),zr(e,`${t}/notes.md`),zr(e,`${t}/evidence/verification.md`)]);return{log:n,notes:r,verification:s}}function et(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}var tt={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function nt(){let e=et("BACKEND_URL")||I().backendUrl;return e||"http://localhost:8008/v1"}function Ne(e){let t=pe(e);return t.endsWith("/v1")?t:`${t}/v1`}function gn(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=gn(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return gn(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function Rv(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 Yr(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?`${nt()}/p/${n.external_id}/${tt.KORTIX_MASTER}`:""),status:Rv(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 zo(){let e=await Rt(),t=[];for(let n of e){let r=await jt(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Yr(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 Yo(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 Jr(e){let t=await Yo(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await mn(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function mn(e){let t=await zo();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 fy(e){return u(await c.post("/notifications/device-token",e))}async function yy(e,t){return u(await c.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}async function hy(e,t){let n=I().fetch??((o,i)=>fetch(o,i)),r=Ne(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 S(`Device token release failed (HTTP ${s.status})`,{status:s.status,response:s});return{ok:!0}}var YN=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered","message"];async function _y(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 by(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 JN={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 Sy(){return u(await c.get("/notifications/preferences",{showErrors:!1}))}async function Py(e){return u(await c.put("/notifications/preferences",e))}async function xy(){return u(await c.get("/notifications/web-push/key",{showErrors:!1}))}async function wy(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 vy(e,t){return u(await c.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function Qr(e){return u(await c.get(`/projects/${e}/model-access`))}async function Xr(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}async function Zr(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/custom-providers`)).providers}async function es(e,t,n){return u(await c.put(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,n))}var ky=e=>e?.status===404;async function ts(e,t){let n=await c.delete(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,{showErrors:!1});if(!n.success&&!ky(n.error))throw n.error??new Error("Failed to delete the custom provider");let r=`CUSTOM_${t.toUpperCase().replace(/-/g,"_")}_API_KEY`;await wr(e,r).catch(s=>{if(!ky(s))throw s})}function oB(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 Jo(e){return typeof e=="string"&&e.trim().length>0}function Ay(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Jo(t)||Jo(n)||Jo(r)}function Cv(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 ns(e){if(!e)return!0;let t=Cv(e.items);return t?!t.some(Ay):!Ay(e)}var Te="kortix.transcript.v1",Tv=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function Ry(e){return typeof e=="string"&&Tv.includes(e)}var aB=["once","always","reject"],cB=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var Iy="kortix-v1-import",Iv={harness:Iy,harness_version:Te,adapter_version:"1"},Qo={schema:ue,v:1},Ev={opencode:"[Tool execution was interrupted]",pi:"No result provided"},Mv="[Old tool result content cleared]",Ov="The following tool was executed by the user",jv=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"})),Dv=e=>jv.get(e)??(e.includes("_")?"mcp":"other"),Lv=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),$v=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Q=e=>typeof e=="string"?e:void 0,Be=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,is=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,Ey=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Ut=e=>Be(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Ft=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function Xo(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)=>Xo(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=>Xo(e[r],is(t,r)))}function ss(e,t){if(Xo(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=ss(is(e,r),is(t,r));s&&Ey(n,r,s)}return{sub:n}}function os(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=os(is(n,r),s);o===void 0?delete n[r]:Ey(n,r,o)}return n}var fn=e=>Object.values(e??{}).find(t=>t.version===Te),as=(e,t)=>({[e]:{version:Te,...t}}),My=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},Cy=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),Uv=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),Fv=e=>{if(B(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==Te&&B(n.data?.details));return t?t.data.details:{}};function Nv(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=Ft(e.started_at)??t.created,i=Ft(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:Cy(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,...My(d,t)}]:[]),p=Ft(r?.cleared_at);return{status:"completed",...s,output:Cy(r?.content),title:e.title??"",metadata:{...Fv(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...l.length&&{attachments:l}}}function Oy(e,t){let n=Uv(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},...My(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:Nv(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 Bv(e){return Ry(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function jy(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:$v.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:Ft(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:Bv(e.error)},...n}}function Dy(e,t){return e.role==="assistant"?jy(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 Ly(e,t,n){let r=`${e.message_id}-summary`;return{info:jy({...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 Kv(e,t,n){let r=n||e.producer.harness===Iy;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=fn(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:Ft(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=Oy(d,i);return g===void 0?[]:[os(g,fn(d.ext)?.data)]}),l=[{runtime_session_id:o,info:os(Dy(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=os(Ly(e,p,i),s?.summary);l.push({runtime_session_id:o,info:d.info,parts:d.parts})}return l}var Zo=e=>Be(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,rs=e=>String(B(e.info)?e.info.id:""),$y=(e,t)=>Zo(e)-Zo(t)||(rs(e)<rs(t)?-1:rs(e)>rs(t)?1:0),Ty=e=>{let t=fn(e.ext);return t?t.native_id??null:e.thread_id};function cs(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=>Kv(a,Ty(i),fn(i.ext)!==void 0))),s=fn(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?Ty(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort($y)}}function qv(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=Q(t.p),r=Q(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...Q(t.v)!==void 0&&{variant:t.v}}}function Gv(e){if(!B(e.tokens))return null;let t=e.tokens,n=B(t.cache)?t.cache:{};return{input:Be(t.input)??0,output:Be(t.output)??0,cache_read:Be(n.read)??0,cache_write:Be(n.write)??0,...Be(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Be(e.cost)!==void 0&&{cost:e.cost}}}var Wv=e=>({code:Q(e.code)||Q(e.name)||"UnknownError",message:Q(B(e.data)?e.data.message:void 0)??""});function Uy(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:Q(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...Q(e.url)!==void 0&&{url:e.url}}}function Hv(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)&&Be(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}=Uy(h,n,r);return{type:"attachment",...k}}),f=Ut(o.compacted);a="complete",l={content:[...Q(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:Mv}],cleared_at:f}}}else if(s.status==="error"){let m=Q(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"&&Q(s.raw)&&!(B(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=Ev[n.h];a="error",l={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=Ut(o.start),g=Ut(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:Dv(e.tool),input:p,status:a,...l&&{result:l},...Q(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function Vv(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:Ov}});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,...Uy(e,s,o),...Q(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&B(e.state)?Hv(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:Q(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(Q(e.type)||"unknown")}}function zv(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 Yv(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)?Ut(g.time.completed):null,P=o.live?"streaming":"interrupted",k=g?m?f?"aborted":"error":h?"complete":P:l?P:"complete",T=Ut(B(i.time)?i.time.created:void 0)??"",_=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(R=>B(R)&&R.type==="text"&&typeof R.text=="string"?[R.text]:[]).join(""):null,b={tool_input:0,cut_point:0,attachment:0},O=zv(a),y=a.map((R,L)=>Vv(R,O[L],l,_,o,b)),w=y.some(R=>R.type==="text"||R.type==="attachment"||R.type==="tool_call"||R.type==="harness"&&R.model_visible),x=!s&&d!=="system"&&(l?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)&&Q(l.tail_start_id)===void 0&&b.cut_point++,{m:{...Qo,message_id:Q(i.id)??"",thread_id:n,seq:r,role:d,kind:l?"compaction":"turn",status:v,in_context:x,...C&&{hidden_reason:C},agent:Q(i.agent)??null,...d==="assistant"&&{reply_to:Q(i.parentID)??null},model:qv(i),usage:g?Gv(g):null,finish:!g||l?null:f?"aborted":m?"error":Lv.get(i.finish)??null,error:m?Wv(m):null,created_at:T,completed_at:g||l?h:T||null,producer:Iv,blocks:y},lost:b}}function Jv(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:Ft(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=ss(t.parts[d],Oy(p,i));g&&(p.ext=as(s,{data:g}))}):o.parts=t.parts;let a=ss(t.info,Dy(e,i));a&&(o.info=a);let l=e.blocks.find(p=>p.type==="compaction");if(n&&l){let p=ss({info:n.info,parts:n.parts},Ly(e,l,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=as(s,{data:o}))}function Qv(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 ls(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($y),s=new Map;for(let b of r){let O=s.get(b.runtime_session_id);O?O.push(b):s.set(b.runtime_session_id,[b])}let o=e.root_id,i=s.has(o),a=new Map,l=b=>a.get(b)??(a.set(b,JSON.stringify(b)),a.get(b)),p=new Map;for(let b of s.keys()){let O=i&&b===o?void 0:Qv(r,b,l);O&&p.set(b,O)}let d=[...r].reverse().find(b=>b.runtime_session_id===null||!p.has(b.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=b=>b!==null&&p.has(b)?b:m,h=Ut(r.map(Zo).find(Number.isFinite))??"",P=[];for(let[b,O]of s){if(b!==g&&(b===null||!p.has(b)))continue;let y=b===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}=Yv(j,q,y?m:b,R.length+1,v.has(j),n);if(Jv(W,j,q,b,n.h),W.in_context)for(let Me of["tool_input","cut_point","attachment"])n.counts[Me]+=K[Me];R.push(W)}let L=b===null?void 0:p.get(b),le=R.find(j=>j.role==="user"&&j.kind==="turn");P.push({...Qo,thread_id:y?m:b,parent_thread_id:L?f(L.row.runtime_session_id):null,spawned_by:L&&typeof L.part.callID=="string"?{message_id:Q(L.row.info?.id)??"",call_id:L.part.callID}:null,agent:le?.agent??null,title:null,created_at:R[0]?.created_at||h,messages:R,ext:as(n.h,b===null?{}:{native_id:b})})}P.sort((b,O)=>b.parent_thread_id===null?-1:O.parent_thread_id===null?1:_(b)-_(O));let k=P[0]?.messages.filter(b=>b.role==="user"&&b.kind==="turn").at(-1),T=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...Qo,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:as(n.h,{data:{root_id:o}})}};function _(b){return r.findIndex(O=>O.runtime_session_id===b.thread_id)}}var ei={schema:ue,v:1},Xv=Object.freeze({}),Fy=new WeakMap;function us(e){let t=Fy.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=ls({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return Fy.set(e,{state:e.state,block:o}),o}var ti=new WeakMap;function ni(e){if(ti.has(e))return ti.get(e);let t={...ei,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:Te}},messages:[{...ei,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}=cs({...ei,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 ti.set(e,r),r}function se(e){return ni(e)}var me=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",Ke=e=>me(e)?se(e):e;function Zv(e){let t=se(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:Xv}var By=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function ek(e){return e.status==="complete"?"completed":e.status}var Ny=new WeakMap;function tk(e){if(e.status!=="complete")return"";let t=Ny.get(e);return t===void 0&&Ny.set(e,t=By(e)),t}function nk(e){return e.status==="error"?e.result?.error?.message||By(e):void 0}function he(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function bB(e){return he(e)==="bash"}function Ky(e){let t=he(e);return t==="question"||t==="ask"}function SB(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var rk=new Set(["show","show_user"]);function qy(e){return rk.has(he(e))}function PB(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Gy(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||ri(e))}function ri(e){let t=me(e)?se(e):e,n=he(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:ns(t.state?.input)}var sk=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Wy(e){return sk.has(he(e))}var ok=50*1024*1024,si="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",ik=new RegExp(`^kortix-attachment://(${si})/(${si})/(${si})$`);function ii(e){if(typeof e!="string")return null;let t=ik.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function CB(e){return ii(e)!==null}var oi=new WeakMap;async function Hy(e,t,n,r={}){if(n.size>ok)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:oi.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=oi.get(n)??new Map;l.set(s,i),oi.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 Vy(e,t){let n=ii(e);if(!n)throw new Error("Invalid attachment reference");let r=I().backendUrl.replace(/\/$/,""),s=await U(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new S("Could not load attachment",{status:s.status});return s.blob()}var ak=new Set(["show","show_user"]);function ck(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 qe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),yn=e=>typeof e=="string"&&e.length>0?e:null,zy=e=>typeof e=="string"?yn(e.split("/").pop()):null;function ps(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function lk(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 uk(e){let t=e.blocks.filter(qe).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"&&qe(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function pk(e,t){for(let n of ck(e))t(ps(n,"attachment"),ps(n,"filename")??zy(ps(n,"path")),ps(n,"mime"))}function dk(e,t){for(let n of[e,...lk(e.items)])qe(n)&&t(n.attachment,zy(n.path),null)}function TB(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=qe(r)&&Array.isArray(r.blocks)?uk(r):r;if(!qe(s)||!qe(s.info)||!Array.isArray(s.parts))continue;let o=yn(s.info.id);if(!o)continue;let i=yn(s.info.role)??"unknown",a=(l,p,d)=>{let g=ii(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)qe(l)&&(l.type==="file"?a(l.url,yn(l.filename),yn(l.mime)):l.type==="text"&&typeof l.text=="string"?pk(l.text,a):l.type==="tool"&&typeof l.tool=="string"&&ak.has(he(l.tool))&&qe(l.state)&&qe(l.state.input)&&dk(l.state.input,a))}return t}function gk(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 OB(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 ai(e,t,n){return e!==void 0?e:gk(et(t),n)}var Yy={get disableMobileAdvertising(){return ai(I().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return ai(I().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return ai(I().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var mk=new Set(["project-manager"]);function ci(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Yy.enableProjects||!mk.has(e.name)}function LB(e){let t=e.agents.filter(ci),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 Jy(){return{projects:{list:Rt,listForAccount:Oc,get:Ct,detail:_r,create:$c,createRepo:Uc,provision:Fc,update:Pr,archive:xr,llmCatalog:br,modelPicker:Sr,modelAccess:Qr,setModelAccess:Xr,customLlmProviders:Zr,setCustomLlmProvider:es,deleteCustomLlmProvider:ts,sandboxHealth:Ar,sandboxTemplates:Mu,sessions:jt,createSession:Dt},github:{linkRepository:Hc,replaceProjectRepository:Vc,getInstallation:zc,listInstallations:Yc,listLinkableInstallations:Jc,listRepositories:Qc,listRepositoryBranches:Xc,linkInstallation:el,saveInstallation:Zc,deleteInstallation:nl,storeUserToken:tl},gitBackend:{get:rl,repositories:sl},connectStatus:vu,marketplace:{items:o=>vf(o),item:o=>Rf(o),itemFile:(o,i)=>Cf(o,i),marketplaces:()=>kf(),featured:()=>Af(),sources:{list:()=>Tf(),add:o=>If(o),remove:o=>Ef(o)}}}}function Qy(){return{billing:{accountState:Wd,accountStateMinimal:Hd,transactions:Vd,transactionsSummary:zd,creditBreakdown:Yd,usageHistory:Jd,usageRollup:gg,sessionCosts:{list:fg,get:Hr},tierConfigurations:Qd,setPlan:ug,previewPlan:lg,acceptEnterpriseOffer:pg,contactSales:dg,checkout:{createSession:n=>Xd(n),confirmSession:(n,r)=>Zd(n,r)},subscription:{createPortalSession:(n,r)=>eg(n,r),cancel:(n,r)=>tg(n,r),reactivate:n=>ng(n),scheduleDowngrade:(n,r,s)=>rg(n,r,s),cancelScheduledChange:n=>sg(n),prorationPreview:(n,r)=>og(n,r)},credits:{purchase:n=>ig(n),autoTopupSettings:n=>ag(n),configureAutoTopup:n=>cg(n)}},sandboxShares:{list:Lm,create:$m,revoke:Um}}}var hn=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function oe(e,t,n){let r=n?.fetch??I().fetch??((p,d)=>fetch(p,d)),s=pe(n?.backendUrl??I().backendUrl??"");if(!s)throw new hn("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(`${Ne(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 hn(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 li(e,t){return oe("/auth/signup",{body:e},t)}function ui(e,t){return oe("/auth/sign-in/password",{body:e},t)}function pi(e,t){return oe("/auth/sign-in/magic-link",{body:e},t)}function di(e,t){return oe("/auth/verify-otp",{body:e},t)}function gi(e,t){return oe("/auth/sign-in/oauth",{body:e},t)}function mi(e,t){return oe("/auth/oauth/exchange",{body:e},t)}function _n(e,t){return oe("/auth/refresh",{body:e},t)}function fi(e,t){return oe("/auth/password/reset",{body:e},t)}function yi(e,t,n){return oe("/auth/password/update",{body:e,bearer:t},n)}function hi(e,t){return oe("/auth/user",{bearer:e},t)}function _i(e,t,n){return oe("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function bi(e,t){return oe("/auth/sign-in/sso",{body:e},t)}var Si={enroll:(e,t,n)=>oe("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function Pi(e,t={},n){return oe("/auth/sign-out",{body:t,bearer:e},n)}function xi(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 _=JSON.parse(T);_.session?.access_token&&_.session?.refresh_token&&(r=_.session,s=_.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=_n({refresh_token:P},e.request).then(async _=>(k!==l||(r=_.session,_.user&&(s=_.user),await m()),r)).catch(async _=>{if(k!==l)return r;let b=_&&typeof _=="object"&&"status"in _?_.status:0;if(b>=400&&b<500)return r=null,s=null,await m(),null;throw _}).finally(()=>{a===T&&(a=null)});a=T}return a}return{subscribe(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 Xy(){return{list:uc,get:dc,create:pc,secretResources:{list:Dl,create:Ll,rotate:$l,retry:Ul,remove:Fl,grant:Nl,revoke:Bl,setAccess:Kl},updateName:gc,branding:{get:mc,update:fc,uploadAsset:yc,removeAsset:hc,reset:_c},leave:Ic,members:bc,invite:Sc,removeMember:Cc,updateMemberRole:Tc,invites:Pc,cancelInvite:xc,resendInvite:wc,tokens:{list:of,create:af,revoke:cf},connectedApps:{list:lf,revoke:uf},audit:{log:mf,export:hf,activity:ff,webhooks:{list:_f,create:bf,update:Sf,remove:Pf}}}}function Zy(){return{assignments:{list:km,create:Am,revoke:Rm},permissions:{list:Cm,forRole:pm},roles:{list:cm,create:gm,update:mm,setPermissions:fm,remove:ym,usage:dm},groups:{list:em,get:tm,create:nm,update:rm,remove:sm,members:{list:om,add:im,remove:am}},agentIdentities:lm,oauthClients:{list:bm,get:Sm,create:Pm,update:xm,rotateSecret:wm,remove:vm},can:hm,canBatch:_m}}function eh(){let e={signUp:li,signInWithPassword:ui,sendMagicLink:pi,verifyOtp:di,signInWithProvider:gi,exchangeCode:mi,refresh:_n,resetPassword:fi,updatePassword:yi,updateUserMetadata:_i,signInWithSso:bi,mfa:Si,user:hi,signOut:Pi,session:xi},t=Xy(),n=Zy();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:vc,describe:kc,accept:uo,acceptAndLand:Ac,decline:Rc}}}var bn=new Map,wi=new Map;function vi(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function th(e){return bn.get(vi(e))??null}function nh(){return[...bn.values()].filter(e=>typeof e=="string")}function rh(e){return bn.has(vi(e))}async function ft(e){let t=vi(e),n=bn.get(t);if(n!==void 0)return n;let r=wi.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 bn.set(t,i),i}catch{return null}finally{wi.delete(t)}})();return wi.set(t,s),s}function sh(e){let{apiBaseUrl:t}=e;return rh(t)||ft(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:th(t)}}function oh(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 S(`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),sh({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function ih(e,t){let n=null;async function r(){n||(n=jr(e,t,{showErrors:!1}).then(s=>{let o=Nr(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 Nt={url:null,sandboxId:null,dbSandboxId:null,version:0},yk=new Set;function ds(e,t=null,n=null){if(!(Nt.url===e&&Nt.sandboxId===t&&Nt.dbSandboxId===n)){Nt={url:e,sandboxId:t,dbSandboxId:n,version:Nt.version+1};for(let r of yk)r()}}function ah(){return Nt.url}var Sn=new Map;function ch(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 Bt=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 lh(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await mt(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 mt(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 S(ch(i),{code:"RUNTIME_UNAVAILABLE"});let l=i.sandbox.external_id;if(!l)throw new S("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Fe(l);return ds(p,l),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:l}}return n}function uh(e,t,n){let r=null;function s(){if(r)return r;let p=Cd(e,t);return p&&(r=p),r}let o=lh(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=ft(I().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?Ed(p.session):null,h=f?.sandbox?.external_id,P=f?.runtime_session_id;if(h&&P){let b=Fe(h);return ds(b,h),r={runtimeSessionId:P,opencodeSessionId:P,runtimeUrl:b,sandboxId:h},Br(e,t,r),await m,r}let k=`${e}
|
|
15
|
-
${t}`,T=Sn.get(
|
|
13
|
+
`);let h=Yw(f);if(h){if(r(h),h.type==="error")throw new S(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 dd(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function gd(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function md(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Br(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function fd(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function yd(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function TL(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 hd(e){return u(await c.get(`/projects/${e}/triggers`))}async function _d(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function bd(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function Sd(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function OL(e){return u(await c.get(`/accounts/${e}/automations`))}async function jL(e,t){return u(await c.patch(`/accounts/${e}/automations`,{paused:t},{showErrors:!1}))}async function Pd(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function xd(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 wd(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 kd(e,t,n){return u(await c.get(`/projects/${e}/triggers/${t}/runs${xd(n)}`))}async function vd(e,t){return u(await c.get(`/projects/${e}/trigger-runs${xd(t)}`))}async function Ad(e,t,n,r){return u(await c.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function Rd(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 Cd(e){return u(await c.get(`/projects/${e}/triggers/event-apps`))}var Xe=new Map;function Oo(e,t){return`${e}::${t}`}function Td(e,t){Xe.delete(e),Xe.set(e,t)}function Id(e,t){let n=Oo(e,t),r=Xe.get(n);return r&&Td(n,r),r}function Kr(e,t,n){let r=Oo(e,t);if(!Xe.has(r)&&Xe.size>=512){let s=Xe.keys().next().value;s!==void 0&&Xe.delete(s)}Td(r,n)}function Ed(e,t){Xe.delete(Oo(e,t))}function Jw(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function mt(){return Jw(I().backendUrl||"http://localhost:8008/v1")}function Md(){let e=I().sandboxId;return e?`${mt()}/p/${e}/8000`:""}function Qw(e,t=8e3){return`${mt()}/p/${e}/${t}`}function Fe(e,t=8e3){return Qw(e,t)}function Od(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 jo=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 qL(e){return e instanceof Error&&e.name==="SessionStartError"}function Xw(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 jo(s,{status:n,code:r,terminal:!0}):null}function jd(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 ft(e,t,n){let r=await jd(e,t,n);if(!r.success||!r.data){let s=Xw(r.error);if(s&&!(s.status===404&&bp(t)))throw s;return null}return Ld(e,t,r.data)}async function Dd(e,t,n){let r=await jd(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return Ld(e,t,r.data)}function Ld(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Kr(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Fe(r),sandboxId:r}),n}function GL(e,t){return["session-start",e,t]}async function $d(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function Ud(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function Fd(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 QL(e,t){return u(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Nd(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Zw(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function qr(e){let t=e.connectors_required?Nd(e.connectors_required):void 0,n=e.connectors_personal?Nd(e.connectors_personal):void 0;if(t&&n&&!Zw(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 Bd(e,t,n){let r=qr(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function a$(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Do(n.block):null}}async function c$(e,t,n){let r=Do(n,!0),s=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Do(s.block):null}}function Do(e,t=!1){let n=qr(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 l$(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Kd(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}var Gr="Use setBillingPlan().",qd="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Gd(){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 ek(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function m$(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??Gd(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:ek(r),label:s,sublabel:null,monthlyUsd:null}}function tk(e){return!!e&&e.can_manage_billing!==!1}function f$(e){return e?.subscription?.can_purchase_credits===!0&&tk(e)}async function Wd(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?Gd():t.data}function Hd(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 Vd(e){return Wd(`/billing/account-state${Hd(e)}`)}async function zd(e){return Wd(`/billing/account-state/minimal${Hd(e)}`)}async function Yd(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 Jd(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 Qd(){return u(await c.get("/billing/credit-breakdown"))}async function Xd(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function Zd(){return u(await c.get("/billing/tier-configurations"))}async function y$(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Rt(e,`/v1/billing/account-state${t}`)}async function eg(e){throw N("createCheckoutSession",Gr)}async function tg(e,t){throw N("confirmCheckoutSession",Gr)}async function ng(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function rg(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function sg(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function og(e,t,n){throw N("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function ig(e){throw N("cancelScheduledChange",qd)}async function ag(e,t){throw N("getProrationPreview",qd)}async function cg(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 lg(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 h$(e){return u(await c.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function ug(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 _$(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 pg(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 dg(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 gg(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 mg(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 b$(e){throw N("createPerSeatCheckout",Gr)}async function S$(e){throw N("claimPerSeatBilling",Gr)}async function P$(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function fg(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 Lo(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Wr(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Hr(e){return e.size>0?`?${e}`:""}async function hg(e={}){let t=new URLSearchParams;return Lo(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Wr(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/session-costs${Hr(t)}`))}async function Vr(e,t={}){let n=new URLSearchParams;return Lo(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Hr(n)}`))}async function R$(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Wr(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/cost-by-project${Hr(t)}`))}async function C$(e={}){let t=new URLSearchParams;return Lo(t,e),e.sessionId&&t.set("session_id",e.sessionId),Wr(t,e),u(await c.get(`/usage/cost-summary${Hr(t)}`))}function yg(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)}Wr(n,t),t.sort&&n.set("sort",t.sort),n.set("format","csv");let r=e==="projects"?"/usage/cost-by-project":"/usage/session-costs";return`${I().backendUrl||""}${r}?${n}`}async function T$(e,t={}){let n=yg(e==="projects"?"projects":"sessions",t),r=await Oe(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 _g(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function O$(e){return _g("slack",e)}function j$(e){return _g("teams",e)}async function bg(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function D$(e){return bg("slack",e)}function L$(e){return bg("teams",e)}async function Sg(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function Pg(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var nk={oauth_available:!1,install_url:null};async function xg(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?nk:t.data}async function wg(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 kg(e,t){return wg("slack",e,t)}function vg(e,t){return wg("teams",e,t)}async function Ag(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Rg(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 $$(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/telegram/installation`,{showErrors:!1});return t.success?t.data??null:null}async function U$(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/telegram/connect`,t,{showErrors:!1}),"Failed to connect Telegram")}async function F$(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 N$(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 Cg(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 Tg(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 $o(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 rk={provider:"agentmail",managed_available:!1};async function Ig(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?$o(r.data):null}async function Eg(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?rk:t.data}async function Mg(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return $o(n)}async function Og(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 jg(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 $o(r)}async function B$(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function K$(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 Dg(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Lg(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function $g(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Ug(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Fg(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 Ng(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Bg(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Kg(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function qg(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Gg(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Wg(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Hg(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Vg(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function zg(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Yg(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Jg(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Qg(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Xg(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 H$(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function Y$(){throw N("getReferralCode")}async function J$(){throw N("refreshReferralCode")}async function Q$(e){throw N("validateReferralCode")}async function X$(){throw N("getReferralStats")}async function Z$(e={}){throw N("listReferrals")}async function e0(e){throw N("sendReferralEmails")}var Uo="call:";function em(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Uo)&&e.length>Uo.length?{type:"connector_call",executionId:e.slice(Uo.length)}:{type:"review_item",reviewItemId:e}}function sk(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function n0(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[sk(n.status)]+=1;return t}function r0(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 Fo(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function tm(e){let t=e.indexOf(".");return t<=0?Fo(e):`(${Fo(e.slice(0,t))}) ${Fo(e.slice(t+1))}`}function ok(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var $t=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},$=e=>typeof e=="string"&&e?e:void 0,Ce=e=>Array.isArray(e)?e:void 0,Zg=e=>typeof e=="number"?e:0,ik=e=>e.split(`
|
|
14
|
+
`).map(t=>t.trim()).filter(Boolean);function ak(e,t){let n=$t(e.advanced),r=$(e.description),s=Ce(e.whatChanged)??(r?ik(r):t.summary?[t.summary]:[]);return{crId:$(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:$(e.impact)??"",verification:Ce(e.verification)??[],previewUrl:$(e.previewUrl)??$(e.preview_url),conflicts:Ce(e.conflicts),requestedChanges:Ce(e.requested_changes)??[],advanced:{headRef:$(n.headRef)??$(e.head_ref)??"",baseRef:$(n.baseRef)??$(e.base_ref)??"",headSha:$(n.headSha)??$(e.head_sha)??$(e.head_commit_sha)??"",baseSha:$(n.baseSha)??$(e.base_sha)??"",additions:Zg(n.additions),deletions:Zg(n.deletions),files:Ce(n.files)??[],mergeMode:$(n.mergeMode)??"merge"}}}function ck(e,t){let n=Ce(e.actions);if(n)return{actions:n.map((l,p)=>({id:$(l.id)??`${t.review_item_id}-${p}`,title:$(l.title)??"Action",connector:$(l.connector)??"",action:$(l.action)??"",consequence:$(l.consequence)??"",risk:$(l.risk)??t.risk,icon:$(l.icon)??"generic",argsPreview:Ce(l.argsPreview)??[],policySource:$(l.policySource)??"Requires approval",decided:l.decided==="approved"||l.decided==="denied"?l.decided:void 0}))};let r=$(e.action_path)??"",{connector:s,action:o}=ok(r),i=$t(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:$(e.execution_id)??t.review_item_id,title:r?tm(r):t.title||"Run action",connector:s,connectorName:$(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:$(e.approval_context),...Object.keys($t(e.resolved_preview)).length>0?{resolvedPreview:$t(e.resolved_preview)}:{},...$(e.resolved_error)?{resolvedError:$(e.resolved_error)}:{},connectorRisk:$(e.risk)??null,policySource:"Requires approval",expiresAt:$(t.expires_at)}]}}function lk(e,t){return{artifactKind:$(e.artifactKind)??"document",artifactLabel:$(e.artifactLabel)??"Output",previewUrl:$(e.previewUrl)??$(e.preview_url),preview:$(e.preview),files:Ce(e.files),note:$(e.note)??t.summary??""}}function uk(e,t){return{question:$(e.question)??t.title??"",context:$(e.context),options:Ce(e.options)??[]}}function pk(e,t){return{note:$(e.note)??t.summary??"",children:Ce(e.children)??[]}}function dk(e){let t=$t(e.detail);switch(e.kind){case"change":return ak(t,e);case"approval":return ck(t,e);case"output":return lk(t,e);case"decision":return uk(t,e);case"batch":return pk(t,e)}}function gk(e,t){let n=typeof e.number=="number"?e.number:void 0,r=$(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function s0(e,t={}){let n=$t(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?$(n.action_path):void 0,i=e.kind==="change"?gk(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?tm(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:$(e.expires_at),detail:dk(e)}}var Z={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"},a0=[Z.PROJECT_WRITE,Z.PROJECT_TRIGGER_CREATE,Z.PROJECT_TRIGGER_FIRE,Z.PROJECT_TRIGGER_UPDATE,Z.PROJECT_TRIGGER_DELETE];function c0(e){let t=r=>e[r]?.allowed===!0,n=t(Z.PROJECT_WRITE);return{canCreate:n&&t(Z.PROJECT_TRIGGER_CREATE),canFire:t(Z.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(Z.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(Z.PROJECT_TRIGGER_DELETE)}}var l0=[Z.PROJECT_WRITE,Z.PROJECT_GITOPS_PUSH,Z.PROJECT_GITOPS_MERGE,Z.PROJECT_REVIEW_ACT];function mk(e){let t=r=>e[r]?.allowed===!0,n=t(Z.PROJECT_WRITE);return{canOpen:n&&t(Z.PROJECT_GITOPS_PUSH),canMerge:n&&t(Z.PROJECT_GITOPS_MERGE),canClose:n}}function u0(e,t,n){let r=em(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 mk(n).canMerge}return n[Z.PROJECT_WRITE]?.allowed===!0&&n[Z.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 nm(e){return A(await F(`/accounts/${e}/iam/groups`)).groups}async function rm(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}`))}async function sm(e,t){return A(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function om(e,t,n){return A(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function im(e,t){return A(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function am(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/members`)).members}async function cm(e,t,n){return A(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function h0(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function lm(e,t,n){return A(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function _0(e,t){return A(await F(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function b0(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 Ze(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function k0(e,t={}){let n=Ze({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 T0(e,t={}){let n=Ze({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 I0(e,t){return A(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function E0(e,t,n){return A(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function M0(e,t){return A(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function O0(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function j0(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function um(e){return A(await F(`/accounts/${e}/iam/roles`)).roles}async function pm(e){return A(await F(`/accounts/${e}/iam/agent-identities`)).agents}async function dm(e){return A(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function gm(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/permissions`))}async function U0(e){return A(await F(`/accounts/${e}/iam/actions`)).actions}async function mm(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/usage`))}async function fm(e,t){return A(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function ym(e,t,n){return A(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function hm(e,t,n){return A(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function _m(e,t){return A(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function F0(e,t,n){return A(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function q0(e){return A(await F(`/accounts/${e}/iam/scim/tokens`)).tokens}async function G0(e,t){return A(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function W0(e,t){return A(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function Y0(e){return A(await F(`/accounts/${e}/iam/mfa-required`))}async function J0(e){return A(await F(`/accounts/${e}/iam/mfa-required/preview`))}async function Q0(e,t){return A(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function X0(e){return A(await F(`/accounts/${e}/iam/session-oversight`))}async function Z0(e,t){return A(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function rU(e){return A(await F(`/accounts/${e}/iam/sso/provider`)).provider}async function sU(e,t){return A(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function oU(e,t){return A(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function iU(e){return A(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function aU(e){return A(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function cU(e){return A(await F(`/accounts/${e}/iam/sso/mappings`)).mappings}async function lU(e,t){return A(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function uU(e,t){return A(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function mU(e){return A(await F(`/accounts/${e}/iam/session-policy`))}async function fU(e,t){return A(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function yU(e){return A(await F(`/accounts/${e}/iam/sessions`)).sessions}async function hU(e,t){return A(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function _U(e){return A(await F(`/accounts/${e}/iam/pat-policy`))}async function bU(e,t){return A(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function wU(e){return A(await F(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function kU(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function vU(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function AU(e,t){return A(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function EU(e){return A(await F(`/accounts/${e}/audit/webhooks`)).webhooks}async function MU(e,t){return A(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function OU(e,t,n){return A(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function jU(e,t){return A(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function DU(e,t={}){let n=Ze({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return A(await F(`/accounts/${e}/audit${n}`))}async function bm(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 Sm(e,t,n){return n.length===0?[]:A(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function KU(e){return A(await F(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function qU(e,t){return A(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function Pm(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function xm(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function wm(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function km(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function vm(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Am(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function fk(e){return Ze({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function Rm(e,t){return u(await F(`/accounts/${e}/iam/assignments${fk(t)}`)).assignments}async function Cm(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 Tm(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function Im(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await F(`/accounts/${e}/iam/permissions${n}`)).permissions}async function tF(){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 nF(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function rF(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function sF(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function oF(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function lF(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function uF(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function pF(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function dF(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function gF(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function mF(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function fF(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var Em="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function _F(e){throw N("getGoogleAuthUrl",Em)}async function bF(e,t){throw N("convertPresentationToGoogleSlides",Em)}async function Mm(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 Om(e){return u(await c.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function jm(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function Dm(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function Lm(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function $m(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}async function Um(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Fm(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 Nm(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 No=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Bm(e,t=""){return`${mt()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Km(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 No(s,t.status)}return r}async function CF(e){return Km(Bm(e))}async function TF(e){return Km(Bm(e,"/messages"))}async function qm(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function Gm(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Bo(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Ko(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}async function Wm(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders/${n}/run`,{}))}var yk=4;async function Hm(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(yk,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 Vm(e,t,n){return Hm(t,r=>Bo(e,r.sessionId,r.reminderId,n))}function zm(e,t){return Hm(t,n=>Ko(e,n.sessionId,n.reminderId))}async function zr(e){return u(await c.get(`/projects/${e}/reminders`))}var Pe=e=>`/projects/${e}/rooms`;function qo(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 Ym(e,t={}){return u(await c.get(`${Pe(e)}${qo({name:t.name,archived:t.archived,mine:t.mine})}`))}async function Jm(e,t){return u(await c.post(Pe(e),t))}async function Qm(e,t){return u(await c.get(`${Pe(e)}/${t}`))}async function Xm(e,t,n){return u(await c.patch(`${Pe(e)}/${t}`,n))}async function Zm(e,t,n={}){return u(await c.get(`${Pe(e)}/${t}/messages${qo({after:n.after,before:n.before,limit:n.limit,top:n.top,thread:n.thread})}`))}async function ef(e,t,n){return u(await c.post(`${Pe(e)}/${t}/messages`,n))}async function tf(e,t,n){return u(await c.post(`${Pe(e)}/${t}/read`,n===void 0?{}:{seq:n}))}async function nf(e,t,n,r={}){return u(await c.put(`${Pe(e)}/${t}/members/sessions/${n}`,r))}async function rf(e,t,n){return u(await c.delete(`${Pe(e)}/${t}/members/sessions/${n}`))}async function sf(e,t,n,r={}){return u(await c.put(`${Pe(e)}/${t}/members/people/${n}`,r))}async function of(e,t,n){return u(await c.delete(`${Pe(e)}/${t}/members/people/${n}`))}async function af(e,t){return u(await c.get(`${Pe(e)}/people${qo({q:t})}`))}async function cf(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 FF(e){return u(await c.post("/cli/device/decide",{user_code:e,approve:!0}))}async function lf(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 uf(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 pf(){return u(await c.get("/oauth/grants")).grants}async function df(e){return u(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function NF(){return u(await c.get("/accounts/me/devices")).devices}async function BF(e){return u(await c.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function gf(e){return u(await c.get(`/projects/${e}/cli-token`))}async function mf(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function ff(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}function Ut(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,s]of Object.entries(e))n.includes(` ${r} `)&&s!=null&&s!==""&&t.set(r,String(s));return t}function Go(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 yf(e,t){let n=Ut(Go(t)).toString();return u(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function hf(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 _f(e,t){let n=Ut(Go({...t,projectId:void 0})).toString();return u(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function bf(e,t){let n=Ut(Go(t)).toString();return u(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function Sf(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function Pf(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function xf(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function wf(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function kf(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 vf(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 JF(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function Af(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 Rf(){return u(await c.get("/marketplace/marketplaces"))}async function Cf(){return u(await c.get("/marketplace/marketplaces/featured"))}async function Tf(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function If(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Ef(){return u(await c.get("/marketplace/sources"))}async function Mf(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Of(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function eN(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function rN(e){throw N("getTemplate")}async function sN(e,t){throw N("installTemplate")}async function jf(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Df(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Wo(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Lf(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function $f(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Uf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function Ff(e,t){let n=await Wo(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 Nf(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Bf(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 Kf(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function qf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Ho(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function Vo(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function hk(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function _k(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 Gf(e,t,n={}){let r=await hk(t),s=n.mediaType??"application/gzip",o=await Ho(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),Vo(e,o.artifact.artifact_id,{sha256:await _k(r),size_bytes:r.byteLength})}async function Wf(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Hf(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Vf(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function zf(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 Yf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Jf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Qf(e,t,n){return u(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Xf(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var ye=(e,t)=>`/projects/${e}/apps/${t}`;async function Zf(e,t){return u(await c.get(`${ye(e,t)}/machines`),"Failed to list machines").machines}async function zo(e,t,n,r){return u(await c.post(`${ye(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var ey=(e,t,n)=>zo(e,t,n,"start"),ty=(e,t,n)=>zo(e,t,n,"stop"),ny=(e,t,n)=>zo(e,t,n,"restart");async function ry(e,t,n){return u(await c.delete(`${ye(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function sy(e,t,n,r={}){return u(await c.put(`${ye(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function oy(e,t,n){return u(await c.post(`${ye(e,t)}/exec`,n),"Failed to run the command")}async function iy(e,t){return u(await c.get(`${ye(e,t)}/volumes`),"Failed to list volumes").volumes}async function ay(e,t,n){return u(await c.post(`${ye(e,t)}/volumes`,n),"Failed to create the volume")}async function cy(e,t,n,r){return u(await c.patch(`${ye(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function ly(e,t,n,r){u(await c.delete(`${ye(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function uy(e,t,n){return u(await c.get(`${ye(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function py(e,t,n){return u(await c.post(`${ye(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function dy(e,t,n,r){return u(await c.post(`${ye(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function gy(e,t,n,r){return u(await c.post(`${ye(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function pe(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 my(e){let t=u(await c.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new S("Files not found",{status:404});return t[0]}async function bN(e,t){return u(await c.get(`${ge(e)}/access?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load sharing")}async function SN(e,t){return u(await c.put(`${ge(e)}/access`,t),"Failed to share folder")}async function PN(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 xN(e){return u(await c.get(`${ge(e)}/principals`),"Failed to load people")}async function wN(e){return u(await c.get(`${ge(e)}/conflicts`),"Failed to load conflicts").conflicts}async function kN(e,t){u(await c.post(`${ge(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function vN(e,t="/"){return(await Yo(e,t)).entries}async function Yo(e,t="/"){return u(await c.get(`${ge(e)}/files?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load files")}function fy(e,t,n){let r=pe(I().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${ge(e)}/files/content?${new URLSearchParams(s)}`}async function AN(e,t,n){let r=await U(fy(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new S(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function yy(e,t,n){let r=await U(fy(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new S(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function RN(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 bk(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 bk(e,t,n,r,s,o){let i=`${pe(I().backendUrl)}${t}`,{headers:a,rejected:l}=await At(i,{"Content-Type":"application/octet-stream",...r});return new Promise((p,d)=>{let g=new e,m=()=>new S("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 S(P?.message||"Failed to upload file",{status:g.status,code:P?.code,url:i}))},g.onerror=()=>{h(),d(new S("Network error while uploading",{name:"TypeError",url:i}))},g.onabort=()=>{h(),d(m())},g.send(n)})}async function CN(e,t){return u(await c.post(`${ge(e)}/files/mkdir`,{path:t},{showErrors:!1}),"Failed to create folder")}async function TN(e,t,n){return u(await c.post(`${ge(e)}/files/move`,{from:t,to:n},{showErrors:!1}),"Failed to move")}async function IN(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 EN(e){return u(await c.get(`${ge(e)}/versions`),"Failed to load versions").versions}async function MN(e,t){u(await c.post(`${ge(e)}/restore`,{versionId:t}),"Failed to restore version")}var Sk=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function ON(e,t){return(await Pk(e,t)).drives}async function Pk(e,t){return u(await c.get(Sk(e,t)),"Failed to load session files")}var xk=new Set(["done","abandoned"]),wk=15*6e4,kk=24*36e5;function vk(e,t,n=Date.now()){if(!e)return{state:"attention",issues:["unreadable"]};if(xk.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-wk&&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-kk&&r.push("verification_stalled")}return{state:r.length?"attention":"healthy",issues:r}}async function Ak(e,t){try{let{entries:n}=await Yo(e,t);return n.filter(r=>r.type==="dir").map(r=>r.path)}catch(n){if(n instanceof S&&n.status===404)return[];throw n}}async function Yr(e,t){try{return await(await yy(e,t)).blob.text()}catch(n){if(n instanceof S&&n.status===404)return null;throw n}}function Rk(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 Ck(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 UN(e,t){let n=await my(e).catch(l=>{if(l instanceof S&&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 Ak(n.driveId,l.path)).sort().map(p=>({...l,folder:p}))))).flat();if(s.length===0)return[];let[{reminders:o},i]=await Promise.all([zr(e),Promise.all(s.map(l=>Yr(n.driveId,`${l.folder}/goal.json`).then(Rk)))]),a=t?.now??Date.now();return s.map((l,p)=>{let d=i[p]??null,g=l.folder.split("/").at(-1)??l.folder,m=Ck(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:vk(d,m,a)}})}async function FN(e,t){let[n,r,s]=await Promise.all([Yr(e,`${t}/log.md`),Yr(e,`${t}/notes.md`),Yr(e,`${t}/evidence/verification.md`)]);return{log:n,notes:r,verification:s}}function et(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}var tt={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function nt(){let e=et("BACKEND_URL")||I().backendUrl;return e||"http://localhost:8008/v1"}function Ne(e){let t=pe(e);return t.endsWith("/v1")?t:`${t}/v1`}function gn(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=gn(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return gn(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function Tk(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 Jr(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?`${nt()}/p/${n.external_id}/${tt.KORTIX_MASTER}`:""),status:Tk(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 Jo(){let e=await Ct(),t=[];for(let n of e){let r=await Dt(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Jr(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 Qo(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 Qr(e){let t=await Qo(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await mn(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function mn(e){let t=await Jo();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 hy(e){return u(await c.post("/notifications/device-token",e))}async function _y(e,t){return u(await c.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}async function by(e,t){let n=I().fetch??((o,i)=>fetch(o,i)),r=Ne(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 S(`Device token release failed (HTTP ${s.status})`,{status:s.status,response:s});return{ok:!0}}var tB=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered","message"];async function Sy(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 Py(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 nB={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 xy(){return u(await c.get("/notifications/preferences",{showErrors:!1}))}async function wy(e){return u(await c.put("/notifications/preferences",e))}async function ky(){return u(await c.get("/notifications/web-push/key",{showErrors:!1}))}async function vy(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 Ay(e,t){return u(await c.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function Xr(e){return u(await c.get(`/projects/${e}/model-access`))}async function Zr(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}async function es(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/custom-providers`)).providers}async function ts(e,t,n){return u(await c.put(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,n))}var Ry=e=>e?.status===404;async function ns(e,t){let n=await c.delete(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,{showErrors:!1});if(!n.success&&!Ry(n.error))throw n.error??new Error("Failed to delete the custom provider");let r=`CUSTOM_${t.toUpperCase().replace(/-/g,"_")}_API_KEY`;await kr(e,r).catch(s=>{if(!Ry(s))throw s})}function pB(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 Xo(e){return typeof e=="string"&&e.trim().length>0}function Cy(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Xo(t)||Xo(n)||Xo(r)}function Ik(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 rs(e){if(!e)return!0;let t=Ik(e.items);return t?!t.some(Cy):!Cy(e)}var Te="kortix.transcript.v1",Ek=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function Ty(e){return typeof e=="string"&&Ek.includes(e)}var gB=["once","always","reject"],mB=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var My="kortix-v1-import",Mk={harness:My,harness_version:Te,adapter_version:"1"},Zo={schema:ue,v:1},Ok={opencode:"[Tool execution was interrupted]",pi:"No result provided"},jk="[Old tool result content cleared]",Dk="The following tool was executed by the user",Lk=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"})),$k=e=>Lk.get(e)??(e.includes("_")?"mcp":"other"),Uk=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),Fk=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,Be=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,as=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,Oy=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Ft=e=>Be(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Nt=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function ei(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)=>ei(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=>ei(e[r],as(t,r)))}function os(e,t){if(ei(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=os(as(e,r),as(t,r));s&&Oy(n,r,s)}return{sub:n}}function is(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=is(as(n,r),s);o===void 0?delete n[r]:Oy(n,r,o)}return n}var fn=e=>Object.values(e??{}).find(t=>t.version===Te),cs=(e,t)=>({[e]:{version:Te,...t}}),jy=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},Iy=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),Nk=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),Bk=e=>{if(B(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==Te&&B(n.data?.details));return t?t.data.details:{}};function Kk(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=Nt(e.started_at)??t.created,i=Nt(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:Iy(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,...jy(d,t)}]:[]),p=Nt(r?.cleared_at);return{status:"completed",...s,output:Iy(r?.content),title:e.title??"",metadata:{...Bk(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...l.length&&{attachments:l}}}function Dy(e,t){let n=Nk(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},...jy(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:Kk(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 qk(e){return Ty(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function Ly(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:Fk.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:Nt(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:qk(e.error)},...n}}function $y(e,t){return e.role==="assistant"?Ly(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 Uy(e,t,n){let r=`${e.message_id}-summary`;return{info:Ly({...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 Gk(e,t,n){let r=n||e.producer.harness===My;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=fn(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:Nt(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=Dy(d,i);return g===void 0?[]:[is(g,fn(d.ext)?.data)]}),l=[{runtime_session_id:o,info:is($y(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=is(Uy(e,p,i),s?.summary);l.push({runtime_session_id:o,info:d.info,parts:d.parts})}return l}var ti=e=>Be(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,ss=e=>String(B(e.info)?e.info.id:""),Fy=(e,t)=>ti(e)-ti(t)||(ss(e)<ss(t)?-1:ss(e)>ss(t)?1:0),Ey=e=>{let t=fn(e.ext);return t?t.native_id??null:e.thread_id};function ls(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=>Gk(a,Ey(i),fn(i.ext)!==void 0))),s=fn(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?Ey(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(Fy)}}function Wk(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 Hk(e){if(!B(e.tokens))return null;let t=e.tokens,n=B(t.cache)?t.cache:{};return{input:Be(t.input)??0,output:Be(t.output)??0,cache_read:Be(n.read)??0,cache_write:Be(n.write)??0,...Be(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Be(e.cost)!==void 0&&{cost:e.cost}}}var Vk=e=>({code:X(e.code)||X(e.name)||"UnknownError",message:X(B(e.data)?e.data.message:void 0)??""});function Ny(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 zk(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)&&Be(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}=Ny(h,n,r);return{type:"attachment",...v}}),f=Ft(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:jk}],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=Ok[n.h];a="error",l={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=Ft(o.start),g=Ft(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:$k(e.tool),input:p,status:a,...l&&{result:l},...X(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function Yk(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:Dk}});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,...Ny(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)?zk(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 Jk(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 Qk(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)?Ft(g.time.completed):null,P=o.live?"streaming":"interrupted",v=g?m?f?"aborted":"error":h?"complete":P:l?P:"complete",T=Ft(B(i.time)?i.time.created:void 0)??"",_=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(R=>B(R)&&R.type==="text"&&typeof R.text=="string"?[R.text]:[]).join(""):null,b={tool_input:0,cut_point:0,attachment:0},O=Jk(a),y=a.map((R,L)=>Yk(R,O[L],l,_,o,b)),w=y.some(R=>R.type==="text"||R.type==="attachment"||R.type==="tool_call"||R.type==="harness"&&R.model_visible),x=!s&&d!=="system"&&(l?v==="complete":!m||f&&w),k=o.live&&x&&v!=="streaming"&&y.some(R=>R.type==="tool_call"&&(R.status==="pending"||R.status==="running"))?"streaming":v,C=s?"superseded":x||!m?void 0:f?"aborted":"failed_attempt";return l&&B(l)&&X(l.tail_start_id)===void 0&&b.cut_point++,{m:{...Zo,message_id:X(i.id)??"",thread_id:n,seq:r,role:d,kind:l?"compaction":"turn",status:k,in_context:x,...C&&{hidden_reason:C},agent:X(i.agent)??null,...d==="assistant"&&{reply_to:X(i.parentID)??null},model:Wk(i),usage:g?Hk(g):null,finish:!g||l?null:f?"aborted":m?"error":Uk.get(i.finish)??null,error:m?Vk(m):null,created_at:T,completed_at:g||l?h:T||null,producer:Mk,blocks:y},lost:b}}function Xk(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:Nt(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=os(t.parts[d],Dy(p,i));g&&(p.ext=cs(s,{data:g}))}):o.parts=t.parts;let a=os(t.info,$y(e,i));a&&(o.info=a);let l=e.blocks.find(p=>p.type==="compaction");if(n&&l){let p=os({info:n.info,parts:n.parts},Uy(e,l,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=cs(s,{data:o}))}function Zk(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 us(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(Fy),s=new Map;for(let b of r){let O=s.get(b.runtime_session_id);O?O.push(b):s.set(b.runtime_session_id,[b])}let o=e.root_id,i=s.has(o),a=new Map,l=b=>a.get(b)??(a.set(b,JSON.stringify(b)),a.get(b)),p=new Map;for(let b of s.keys()){let O=i&&b===o?void 0:Zk(r,b,l);O&&p.set(b,O)}let d=[...r].reverse().find(b=>b.runtime_session_id===null||!p.has(b.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=b=>b!==null&&p.has(b)?b:m,h=Ft(r.map(ti).find(Number.isFinite))??"",P=[];for(let[b,O]of s){if(b!==g&&(b===null||!p.has(b)))continue;let y=b===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}=Qk(j,q,y?m:b,R.length+1,k.has(j),n);if(Xk(W,j,q,b,n.h),W.in_context)for(let Me of["tool_input","cut_point","attachment"])n.counts[Me]+=K[Me];R.push(W)}let L=b===null?void 0:p.get(b),le=R.find(j=>j.role==="user"&&j.kind==="turn");P.push({...Zo,thread_id:y?m:b,parent_thread_id:L?f(L.row.runtime_session_id):null,spawned_by:L&&typeof L.part.callID=="string"?{message_id:X(L.row.info?.id)??"",call_id:L.part.callID}:null,agent:le?.agent??null,title:null,created_at:R[0]?.created_at||h,messages:R,ext:cs(n.h,b===null?{}:{native_id:b})})}P.sort((b,O)=>b.parent_thread_id===null?-1:O.parent_thread_id===null?1:_(b)-_(O));let v=P[0]?.messages.filter(b=>b.role==="user"&&b.kind==="turn").at(-1),T=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...Zo,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:cs(n.h,{data:{root_id:o}})}};function _(b){return r.findIndex(O=>O.runtime_session_id===b.thread_id)}}var ni={schema:ue,v:1},ev=Object.freeze({}),By=new WeakMap;function ps(e){let t=By.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=us({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return By.set(e,{state:e.state,block:o}),o}var ri=new WeakMap;function si(e){if(ri.has(e))return ri.get(e);let t={...ni,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:Te}},messages:[{...ni,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}=ls({...ni,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 ri.set(e,r),r}function se(e){return si(e)}var me=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",Ke=e=>me(e)?se(e):e;function tv(e){let t=se(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:ev}var qy=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function nv(e){return e.status==="complete"?"completed":e.status}var Ky=new WeakMap;function rv(e){if(e.status!=="complete")return"";let t=Ky.get(e);return t===void 0&&Ky.set(e,t=qy(e)),t}function sv(e){return e.status==="error"?e.result?.error?.message||qy(e):void 0}function he(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function vB(e){return he(e)==="bash"}function Gy(e){let t=he(e);return t==="question"||t==="ask"}function AB(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var ov=new Set(["show","show_user"]);function Wy(e){return ov.has(he(e))}function RB(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Hy(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||oi(e))}function oi(e){let t=me(e)?se(e):e,n=he(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:rs(t.state?.input)}var iv=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Vy(e){return iv.has(he(e))}var av=50*1024*1024,ii="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",cv=new RegExp(`^kortix-attachment://(${ii})/(${ii})/(${ii})$`);function ci(e){if(typeof e!="string")return null;let t=cv.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function jB(e){return ci(e)!==null}var ai=new WeakMap;async function zy(e,t,n,r={}){if(n.size>av)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:ai.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=ai.get(n)??new Map;l.set(s,i),ai.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 Yy(e,t){let n=ci(e);if(!n)throw new Error("Invalid attachment reference");let r=I().backendUrl.replace(/\/$/,""),s=await U(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new S("Could not load attachment",{status:s.status});return s.blob()}var lv=new Set(["show","show_user"]);function uv(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 qe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),yn=e=>typeof e=="string"&&e.length>0?e:null,Jy=e=>typeof e=="string"?yn(e.split("/").pop()):null;function ds(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function pv(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 dv(e){let t=e.blocks.filter(qe).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"&&qe(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function gv(e,t){for(let n of uv(e))t(ds(n,"attachment"),ds(n,"filename")??Jy(ds(n,"path")),ds(n,"mime"))}function mv(e,t){for(let n of[e,...pv(e.items)])qe(n)&&t(n.attachment,Jy(n.path),null)}function DB(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=qe(r)&&Array.isArray(r.blocks)?dv(r):r;if(!qe(s)||!qe(s.info)||!Array.isArray(s.parts))continue;let o=yn(s.info.id);if(!o)continue;let i=yn(s.info.role)??"unknown",a=(l,p,d)=>{let g=ci(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)qe(l)&&(l.type==="file"?a(l.url,yn(l.filename),yn(l.mime)):l.type==="text"&&typeof l.text=="string"?gv(l.text,a):l.type==="tool"&&typeof l.tool=="string"&&lv.has(he(l.tool))&&qe(l.state)&&qe(l.state.input)&&mv(l.state.input,a))}return t}function fv(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 FB(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 li(e,t,n){return e!==void 0?e:fv(et(t),n)}var Qy={get disableMobileAdvertising(){return li(I().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return li(I().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return li(I().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var yv=new Set(["project-manager"]);function ui(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Qy.enableProjects||!yv.has(e.name)}function KB(e){let t=e.agents.filter(ui),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 Xy(){return{projects:{list:Ct,listForAccount:Dc,get:Tt,detail:br,create:Fc,createRepo:Nc,provision:Bc,update:xr,archive:wr,llmCatalog:Sr,modelPicker:Pr,modelAccess:Xr,setModelAccess:Zr,customLlmProviders:es,setCustomLlmProvider:ts,deleteCustomLlmProvider:ns,sandboxHealth:Rr,sandboxTemplates:ju,sessions:Dt,createSession:Lt},github:{linkRepository:zc,replaceProjectRepository:Yc,getInstallation:Jc,listInstallations:Qc,listLinkableInstallations:Xc,listRepositories:Zc,listRepositoryBranches:el,linkInstallation:nl,saveInstallation:tl,deleteInstallation:sl,storeUserToken:rl},gitBackend:{get:ol,repositories:il},connectStatus:Au,marketplace:{items:o=>Af(o),item:o=>Tf(o),itemFile:(o,i)=>If(o,i),marketplaces:()=>Rf(),featured:()=>Cf(),sources:{list:()=>Ef(),add:o=>Mf(o),remove:o=>Of(o)}}}}function Zy(){return{billing:{accountState:Vd,accountStateMinimal:zd,transactions:Yd,transactionsSummary:Jd,creditBreakdown:Qd,usageHistory:Xd,usageRollup:fg,sessionCosts:{list:hg,get:Vr},tierConfigurations:Zd,setPlan:dg,previewPlan:pg,acceptEnterpriseOffer:gg,contactSales:mg,checkout:{createSession:n=>eg(n),confirmSession:(n,r)=>tg(n,r)},subscription:{createPortalSession:(n,r)=>ng(n,r),cancel:(n,r)=>rg(n,r),reactivate:n=>sg(n),scheduleDowngrade:(n,r,s)=>og(n,r,s),cancelScheduledChange:n=>ig(n),prorationPreview:(n,r)=>ag(n,r)},credits:{purchase:n=>cg(n),autoTopupSettings:n=>lg(n),configureAutoTopup:n=>ug(n)}},sandboxShares:{list:Um,create:Fm,revoke:Nm}}}var hn=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function oe(e,t,n){let r=n?.fetch??I().fetch??((p,d)=>fetch(p,d)),s=pe(n?.backendUrl??I().backendUrl??"");if(!s)throw new hn("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(`${Ne(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 hn(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 pi(e,t){return oe("/auth/signup",{body:e},t)}function di(e,t){return oe("/auth/sign-in/password",{body:e},t)}function gi(e,t){return oe("/auth/sign-in/magic-link",{body:e},t)}function mi(e,t){return oe("/auth/verify-otp",{body:e},t)}function fi(e,t){return oe("/auth/sign-in/oauth",{body:e},t)}function yi(e,t){return oe("/auth/oauth/exchange",{body:e},t)}function _n(e,t){return oe("/auth/refresh",{body:e},t)}function hi(e,t){return oe("/auth/password/reset",{body:e},t)}function _i(e,t,n){return oe("/auth/password/update",{body:e,bearer:t},n)}function bi(e,t){return oe("/auth/user",{bearer:e},t)}function Si(e,t,n){return oe("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function Pi(e,t){return oe("/auth/sign-in/sso",{body:e},t)}var xi={enroll:(e,t,n)=>oe("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function wi(e,t={},n){return oe("/auth/sign-out",{body:t,bearer:e},n)}function ki(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 _=JSON.parse(T);_.session?.access_token&&_.session?.refresh_token&&(r=_.session,s=_.user??null)}catch{r=null}return o=!0,r})();i=v,v.then(()=>{i===v&&(i=null)},()=>{i===v&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let P=r.refresh_token,v=l,T=_n({refresh_token:P},e.request).then(async _=>(v!==l||(r=_.session,_.user&&(s=_.user),await m()),r)).catch(async _=>{if(v!==l)return r;let b=_&&typeof _=="object"&&"status"in _?_.status:0;if(b>=400&&b<500)return r=null,s=null,await m(),null;throw _}).finally(()=>{a===T&&(a=null)});a=T}return a}return{subscribe(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 eh(){return{list:dc,get:mc,create:gc,secretResources:{list:$l,create:Ul,rotate:Fl,retry:Nl,remove:Bl,grant:Kl,revoke:ql,setAccess:Gl},updateName:fc,branding:{get:yc,update:hc,uploadAsset:_c,removeAsset:bc,reset:Sc},leave:Mc,members:Pc,invite:xc,removeMember:Ic,updateMemberRole:Ec,invites:wc,cancelInvite:kc,resendInvite:vc,tokens:{list:cf,create:lf,revoke:uf},connectedApps:{list:pf,revoke:df},audit:{log:yf,export:bf,activity:hf,webhooks:{list:Sf,create:Pf,update:xf,remove:wf}}}}function th(){return{assignments:{list:Rm,create:Cm,revoke:Tm},permissions:{list:Im,forRole:gm},roles:{list:um,create:fm,update:ym,setPermissions:hm,remove:_m,usage:mm},groups:{list:nm,get:rm,create:sm,update:om,remove:im,members:{list:am,add:cm,remove:lm}},agentIdentities:pm,oauthClients:{list:Pm,get:xm,create:wm,update:km,rotateSecret:vm,remove:Am},can:bm,canBatch:Sm}}function nh(){let e={signUp:pi,signInWithPassword:di,sendMagicLink:gi,verifyOtp:mi,signInWithProvider:fi,exchangeCode:yi,refresh:_n,resetPassword:hi,updatePassword:_i,updateUserMetadata:Si,signInWithSso:Pi,mfa:xi,user:bi,signOut:wi,session:ki},t=eh(),n=th();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Ac,describe:Rc,accept:po,acceptAndLand:Cc,decline:Tc}}}var bn=new Map,vi=new Map;function Ai(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function rh(e){return bn.get(Ai(e))??null}function sh(){return[...bn.values()].filter(e=>typeof e=="string")}function oh(e){return bn.has(Ai(e))}async function yt(e){let t=Ai(e),n=bn.get(t);if(n!==void 0)return n;let r=vi.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 bn.set(t,i),i}catch{return null}finally{vi.delete(t)}})();return vi.set(t,s),s}function ih(e){let{apiBaseUrl:t}=e;return oh(t)||yt(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:rh(t)}}function ah(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 S(`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),ih({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function ch(e,t){let n=null;async function r(){n||(n=Dr(e,t,{showErrors:!1}).then(s=>{let o=Br(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 Bt={url:null,sandboxId:null,dbSandboxId:null,version:0},_v=new Set;function gs(e,t=null,n=null){if(!(Bt.url===e&&Bt.sandboxId===t&&Bt.dbSandboxId===n)){Bt={url:e,sandboxId:t,dbSandboxId:n,version:Bt.version+1};for(let r of _v)r()}}function lh(){return Bt.url}var Sn=new Map;function uh(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 Kt=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 ph(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await ft(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 ft(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 S(uh(i),{code:"RUNTIME_UNAVAILABLE"});let l=i.sandbox.external_id;if(!l)throw new S("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Fe(l);return gs(p,l),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:l}}return n}function dh(e,t,n){let r=null;function s(){if(r)return r;let p=Id(e,t);return p&&(r=p),r}let o=ph(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=yt(I().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?Od(p.session):null,h=f?.sandbox?.external_id,P=f?.runtime_session_id;if(h&&P){let b=Fe(h);return gs(b,h),r={runtimeSessionId:P,opencodeSessionId:P,runtimeUrl:b,sandboxId:h},Kr(e,t,r),await m,r}let v=`${e}
|
|
15
|
+
${t}`,T=Sn.get(v);if(T)return r=await T,await m,r;let _=o(g);Sn.set(v,_);try{return r=await _,await m,r}finally{Sn.get(v)===_&&Sn.delete(v)}}function a(p){let d=s();if(!d)throw new Kt(p);return d}function l(){r=null,Ed(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:l}}var G=["directory","workspace"],gh=["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}),bv={"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,gh),"session.promptAsync":E("POST","/session/{sessionID}/prompt_async",G,gh),"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 Sv(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 Pv(e,t,n={},r={}){let s=bv[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}${Sv(s,n)}`,{method:s.method,headers:l,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function xv(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 wv(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=xv(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 Ri(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*xk(e,t,n){let r=e.eventTransport??ki(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 Pn(e){let t=s=>(o,i)=>Pk(e,bk(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:xk(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 dh=200;async function wk(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 rt(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 S(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function gh(e){let t=e.runtimeUrl.replace(/\/$/,""),n=Pn({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 S(`Reading the session transcript failed: ${await wk(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,dh),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,dh),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=>rt(i,"Reading the session status failed")),n.permission.list().then(i=>rt(i,"Reading permission requests failed")),n.question.list().then(i=>rt(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{rt(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){rt(await n.question.reject({requestID:r}),"Dismissing the question failed");return}rt(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 S("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});let i=rt(await n.session.status(),"Reading the session status failed")?.[e.rootId];if(i&&i.type!=="idle")throw new S("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 S("Compaction has not finished. Check the session status before trying again.",{code:"LONG_TURN_PROXY_TIMEOUT",status:a.response?.status});return rt(a,"Compacting the session failed"),s}}}function mh(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return gh({runtimeUrl:r,rootId:n,fetch:U})}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 fh(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await dd(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var xn=BigInt(4096),st=BigInt(0xffffffffffff),yh=st+BigInt(1),vk=yh/BigInt(2),yt=BigInt(3600*1e3)*xn,Ai=120*1e3,kk=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,Ak=/^msg_([0-9a-f]{12})/,hh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Kt(e){let t=Ak.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function wn(e){return BigInt(Math.trunc(e))*xn&st}function qt(e,t){let n=e-t&st;return n>=vk&&(n-=yh),n}function _h(e){let t=null;for(let n of e)n!=null&&(t===null||qt(n,t)>BigInt(0))&&(t=n);return t}function Rk(e,t){let n=Kt(e);return n===null?!1:qt(n,wn(t))>yt}function Ck(e,t){let n=t===void 0?null:wn(t);return bh(e,r=>n===null||qt(r,n)<=yt)}function bh(e,t){let n=[];for(let r of e){let s=Kt(r);s!==null&&t(s)&&n.push(s)}return _h(n)}function Tk(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=hh[n%62])}return e}function Sh(e){let t=e.random,n=wn(e.nowMs-(e.backdateMs??Ai)),r=e.newestKnownTime??null;if(r!==null){let o=qt(r,n);o>=BigInt(0)&&o<=yt&&(n=r+BigInt(1)&st)}let s="";if(t)for(let o=0;o<14;o++)s+=hh[Math.min(61,Math.floor(t()*62))];else s=Tk();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function Ri(e={}){let t=e.nowMs??Date.now(),n=wn(t-Ai),r=bh(e.after??[],s=>{let o=qt(s,n);return o>=BigInt(0)&&o<=yt});return Sh({nowMs:t,newestKnownTime:r}).id}function Ph(e){return{scope:()=>ud(e.projectId,e.sessionId),providerSecretPool:{list:()=>Gl(e.projectId,e.sessionId),get:t=>ql(e.projectId,e.sessionId,t),set:(t,n)=>Wl(e.projectId,e.sessionId,t,n)},rescope:t=>pd(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=Ri(),p=await $r(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 S("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var xh=async function*(e){let t=I().eventStreamTransport;if(!t){yield*ki(((s,o)=>U(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await kt(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function Ge(){let e=ah();return e||(I().billingEnabled??!1?"":Id())}async function Ci(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Ti(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function wh(e){let t=Ti(e),n=await U(`${t}/env`);if(!n.ok)throw new Error(await Ci(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function vh(e,t,n){let r=Ti(e),s=await U(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await Ci(s,"Failed to save secret"))}async function kh(e,t){let n=Ti(e),r=await U(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Ci(r,"Failed to delete secret"))}var Ik={list:wh,set:vh,delete:kh};async function Ek(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await U(`${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 gs(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function vn(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return pe(e)}async function Ah(e){let t=vn(e),n=await U(`${t}/kortix/pty`);if(!n.ok)throw new Error(await gs(n,"Failed to list terminals"));return n.json()}async function Rh(e,t){let n=vn(e),r=await U(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await gs(r,"Failed to create terminal"));return r.json()}async function Ch(e,t,n){let r=vn(e),s=await U(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await gs(s,"Failed to update terminal"));return s.json()}async function Th(e,t){let n=vn(e),r=await U(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await gs(r,"Failed to remove terminal"))}async function Ih(e,t,n){let r=vn(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:"),pe(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await sn();a&&i.set("token",a),n?.wake&&i.set("wake","1");let l=i.toString();return l?`${o}${o.includes("?")?"&":"?"}${l}`:o}function Mk(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 ot="\x1B",Eh="\x07",Ok="\0",Ii=`(?:${Eh}|${ot}\\\\)`,jk=[new RegExp(`${ot}\\]697;[^${Eh}${ot}]*${Ii}`,"g"),new RegExp(`${Ok}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${ot}\\][0-9]+;rgb:[0-9a-fA-F/]+${Ii}`,"g"),new RegExp(`${ot}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Ii}`,"g"),new RegExp(`${ot}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${ot}\\[\\d+;\\d+R`,"g"),new RegExp(`${ot}\\[\\?[0-9;]*c`,"g")];function Dk(e){let t=e;for(let n of jk)t=t.replace(n,"");return t}var Lk={list:Ah,create:Rh,update:Ch,remove:Th,webSocketUrl:Ih};async function M(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await U(`${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 ZK(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 eq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function tq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function nq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function rq(e,t){return M(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function sq(e,t,n){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function oq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function iq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function aq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function cq(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return M(e,`/kortix/tickets${n}`)}async function lq(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function uq(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function pq(e,t){return M(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function dq(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function gq(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function mq(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function fq(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function yq(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function hq(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function _q(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function bq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function Sq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function Pq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function xq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function wq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function vq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function kq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function Aq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function Rq(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function Cq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Tq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function Iq(e,t,n=200){return M(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function Eq(e){return M(e,"/kortix/projects")}async function Mq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function Oq(e,t){return M(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function jq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function Dq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Lq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function $q(e,t,n="all"){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function Uq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function Fq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function Nq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function Bq(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function Kq(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function qq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function Gq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Wq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function Hq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function Vq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function zq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function Yq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var $k=1e4,Uk={retryOnAuthError:!1};function Gt(e,t,n){return M(e,t,{signal:AbortSignal.timeout($k),...n},Uk)}async function Jq(e,t=!1){return(await Gt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function Qq(e){return(await Gt(e,"/kortix/services/templates")).templates??[]}async function Xq(e,t){return(await Gt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function Zq(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return Gt(e,s,{method:r?"DELETE":"POST"})}async function eG(e,t){return Gt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function tG(e,t){return Gt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var We=new Map,Fk=256,kn=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function ht(){let e=Ge();if(!e)throw new kn;return He(e)}function He(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=We.get(e);if(t)return We.delete(e),We.set(e,t),t;if(!to())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=Pn({baseUrl:e,fetch:U,eventTransport:xh});return We.set(e,n),We.size>Fk&&We.delete(We.keys().next().value),n}function lG(e){We.delete(e)}function uG(){We.clear()}var ms=new Map;function pG(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=ms.get(e);if(t)return t;let n=Pn({baseUrl:e,fetch});return ms.set(e,n),n}function dG(e){ms.delete(e)}function gG(){ms.clear()}async function Nk(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 mG(e){let t=Ge();if(!t)throw new S("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await U(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new S(`System reload failed (${r.status}): ${await Nk(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new S(`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 S(`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 Mh="frontend";function fs(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Mh}] ${t}`,...n?[n]:[]);try{ht().app.log({service:Mh,level:e,message:t,extra:n})}catch{}}var Ve={debug:(e,t)=>fs("debug",e,t),info:(e,t)=>fs("info",e,t),warn:(e,t)=>fs("warn",e,t),error:(e,t)=>fs("error",e,t)};var Bk=16,Kk=8,Oh=6e4,qk=250,Gk=1e3,Wk=3e4,Hk=5,Vk=.5,zk=3e3,Yk=3e4,jh=2e4,Jk=2e3,Dh=8;function Qk(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function Xk(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 Lh(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,Bk-l))};return{push(l){let p=Xk(n[n.length-1]?.event,l);if(p)n[n.length-1]={type:p.type,event:p};else{let d=Qk(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 $h(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 Ei(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 Zk(e,t,n,r){return new Promise((s,o)=>{let i=!1,a=t.setTimeout(()=>{i||(i=!0,Ve.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:zk,sseMaxRetryDelay:Yk,sseMaxRetryAttempts:1}).then(l=>{i||(i=!0,t.clearTimeout(a),s(l))},l=>{i||(i=!0,t.clearTimeout(a),o(l))})})}async function eA(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=$h(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<Kk)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return o}function Uh(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<Jk)}function Fh(e,t,n){Ve.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),Ei(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function Nh(e,t,n){let r=t?qk:Math.min(Gk*2**Math.min(e-1,Hk),Wk);return Math.round(r*(1+Vk*(n.random?.()??0)))}function Bh(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 Kh(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=$h(o);P.promise.then(()=>h.abort());try{let{stream:k}=await Zk(t,n,r,h);l();let T=()=>{n.clearTimeout(m),m=n.setTimeout(()=>{Ve.warn("SSE heartbeat timeout, forcing reconnect"),h.abort()},s)};T(),d=await eA(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),_=tn(k)||tn(k?.cause);if(Ve.error("SSE event stream error",{error:T,retryCount:i,isAuthError:_}),_)try{yo(),await fo(),Ve.info("SSE: refreshed auth token after auth error")}catch(b){Ve.error("SSE: failed to refresh auth token",{error:String(b)})}}finally{n.clearTimeout(m),h.abort(),P.cleanup(),p.flush()}return{streamHadWork:d,stableConnection:g,error:f}}function tA(e){return{type:"heartbeat-gap",gapMs:e}}function nA(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 rA={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},sA=5e3,oA=1e4,iA=4,An=new WeakMap;function aA(e,t,n){let r=t.timers??rA,s=t.connectTimeoutMs??jh,o=t.heartbeatTimeoutMs??Oh,i=t.maxConsecutiveHardFailures??Dh,a=new AbortController,l=(k,...T)=>Ei(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=Lh(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>sA)&&l(_=>_.onGapRehydrate,k)}m=r.now()},coalescer:h};return(async()=>{let k=0,T=0,_=0;for(;!a.signal.aborted;){let b=r.now(),O=await Kh({...P,retryCount:k});if(a.signal.aborted)break;let y=O.error,{streamHadWork:w,stableConnection:x}=O,v=r.now()-b;if(T=Uh(w,y,v)?T+1:0,T>=i){Fh(n,T,y),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||w},_=x&&v<oA?_+1:0;let R=x&&_<=iA;R?k=0:(k++,k>1&&Ve.warn("SSE event stream reconnecting",{retryCount:k})),await Bh(r,a.signal,Nh(k,R,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),h.clearTimer()}}}function Mi(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?He(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=An.get(i);if(l?.isParked()&&(An.delete(i),l=void 0),!l)l=aA(i,e,new Set([a])),An.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(),An.get(i)===p&&An.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function qh(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return He(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return He(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return He(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return Mi({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Wh(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 S(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Di(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 ae(e){let t=(e??Ge()).trim();if(!t)throw new kn;return t}async function En(e,t){let n=await U(`${ae(t)}${e}`);if(!n.ok)throw new S(await Di(n),{status:n.status,response:n});return n.json()}async function Li(e,t,n,r,s){let o=await U(`${ae(s)}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new S(`${r} failed (${o.status}): ${await Di(o)}`,{status:o.status,response:o});return o.json()}var $i=["/workspace","/tmp","/home","/opt"],cA=$i.filter(e=>e!=="/workspace");function Hh(e){return $i.some(t=>e===t||e.startsWith(`${t}/`))}function Mn(e){return Hh(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function _t(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(cA.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Vh=_t;async function On(e,t){let n=ae(t),r=_t(e)||".";return(await En(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function jn(e,t){let n=_t(e);return En(`/file/content?path=${encodeURIComponent(n)}`,t)}async function lA(e,t,n){let r=ae(n),s=_t(e),o=await U(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new S(await Di(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new S("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 uA=8,ys=0,zh=[];async function pA(){if(ys<uA){ys++;return}await new Promise(e=>zh.push(e)),ys++}function dA(){ys--,zh.shift()?.()}function gA(e,t){let n=ae(t);return Rr(`${n}/file/raw?path=${encodeURIComponent(_t(e))}`)}async function Dn(e,t){await pA();try{let n=ae(t);try{return await lA(e,void 0,n)}catch{}let r=await jn(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{dA()}}async function hs(e){return En("/file/status",ae(e))}async function _s(e,t,n){let r=ae(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),En(`/find/file?${s.toString()}`,r)}async function bs(e,t){let n=ae(t);return(await En(`/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 Rn=[400,1200],mA=e=>e===408||e===429||e===502||e===503||e===504,Gh=e=>new Promise(t=>setTimeout(t,e));function fA(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Oi=3e4,Yh=15*6e4,yA=256;function Cn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Oi;let t=Oi+e/yA;return Math.min(Yh,Math.max(Oi,Math.round(t)))}async function hA(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 Tn(e,t){let n;for(let s=0;s<=Rn.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,fA(a)||s===Rn.length)break;await Gh(Rn[s]);continue}if(o.ok)return o.json();let i=await hA(o);if(n=new S(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!mA(o.status)||s===Rn.length)throw n;await Gh(Rn[s])}if(n instanceof S)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new S(`Upload failed: ${r}`)}var ji=8*1024*1024;function _A(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new S(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Jh(e,t){try{e?.onProgress?.(t)}catch{}}function Qh(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 bA(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=ae(o),l=Cn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=ji){let d=await Tn(()=>Qh(e,t,p),g=>U(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:l}));return _A(d[0],e.size),Jh(i,{loadedBytes:e.size,totalBytes:e.size}),d}return SA(e,t,p,a,i)}async function SA(e,t,n,r,s){let i=(await Tn(()=>Qh(new Blob([],{type:e.type}),t,n),l=>U(`${r}/file/upload`,{method:"POST",body:l},{timeoutMs:Cn(0)})))[0]?.path;if(!i)throw new S("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=bA(i);if(!a.name)throw new S(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let l=0;l<e.size;l+=ji){let p=Math.min(e.size,l+ji),d=e.slice(l,p,e.type),g=await Tn(()=>{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=>U(`${r}/file/append`,{method:"POST",body:m},{timeoutMs:Cn(d.size)}));if(g.path!==i||g.size!==p)throw new S(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Jh(s,{loadedBytes:p,totalBytes:e.size})}}catch(l){throw await Wt(i,r).catch(()=>{}),l}return[{path:i,size:e.size}]}function PA(e,t,n){let r=ae(n);return Tn(()=>{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=>U(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:xA}))}var xA=Yh;function wA(e,t,n){let r=ae(n),s=Cn(t.size);return Tn(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>U(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var In=class extends S{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 Ss(e,t){let n=ae(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",l=Mn(`${a}/${i}`),p=[];try{p=await On(Xh(l),n)}catch(g){if(!(g instanceof S&&g.status===404))throw g}if(p.some(g=>g.name===Zh(l)))throw new In(l);let d=await e_(l,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function Ps(e,t,n){let r=ae(n);return wA(t,await Dn(e,r),r)}function vA(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Xh(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Zh(e){return e.slice(e.lastIndexOf("/")+1)}function kA(){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 xs(e,t,n){let r=ae(n),s=Mn(vA(e.trim()));return e_(s,t,r,{overwrite:!0})}async function e_(e,t,n,r){let s=Zh(e);if(!s)throw new S(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=Xh(e);await $n(o,n).catch(()=>{});let i=kA(),a=await Ln(t,o,`.${s}.kortix-write-${i}`,n),l=a[0]?.path;if(!l)throw new S(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=Mn(l);try{await t_(p,e,n,r.overwrite)}catch(g){throw await Wt(p,n).catch(()=>{}),!r.overwrite&&g instanceof S&&g.status===409?new In(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Wt(e,t){return Li("/file","DELETE",{path:e},"Delete",t)}async function $n(e,t){return Li("/file/mkdir","POST",{path:e},"Mkdir",t)}async function ws(e,t,n){return t_(e,t,ae(n),!0)}async function t_(e,t,n,r){return Li("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function n_(){return Wh(await ht().project.current())}async function Ui(){return Wh(await ht().global.health())}async function r_(){try{return(await Ui()).healthy===!0}catch{return!1}}var AA={list:On,read:jn,readBlob:Dn,status:hs,findFiles:_s,findText:bs,upload:Ln,write:xs,create:Ss,copy:Ps,remove:Wt,mkdir:$n,rename:ws,currentProject:n_,health:Ui,isReachable:r_,toDaemonPath:_t,toSandboxAbsolutePath:Mn,toWorkspaceRelative:Vh};function s_(e){return{list:async t=>On(t,(await e()).runtimeUrl),read:async t=>jn(t,(await e()).runtimeUrl),readBlob:async t=>Dn(t,(await e()).runtimeUrl),status:async()=>hs((await e()).runtimeUrl),findFiles:async(t,n)=>_s(t,n,(await e()).runtimeUrl),findText:async t=>bs(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>Ln(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>xs(t,n,(await e()).runtimeUrl),create:async t=>Ss(t,(await e()).runtimeUrl),copy:async(t,n)=>Ps(t,n,(await e()).runtimeUrl),remove:async t=>Wt(t,(await e()).runtimeUrl),mkdir:async t=>$n(t,(await e()).runtimeUrl),rename:async(t,n)=>ws(t,n,(await e()).runtimeUrl)}}function o_(e){return{get:t=>jr(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:()=>Hr(e.sessionId,{projectId:e.projectId}),update:t=>rd(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),sd(e.projectId,e.sessionId)),restore:()=>id(e.projectId,e.sessionId),recover:()=>od(e.projectId,e.sessionId),start:(...t)=>mt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Od(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Ur(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Fr(e.projectId,e.sessionId)),configState:()=>ad(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),cd(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),ld(e.projectId,e.sessionId,...t)),setSharing:t=>Lp(e.projectId,e.sessionId,t),previews:()=>Kp(e.projectId,e.sessionId),participants:()=>$p(e.projectId,e.sessionId),watch:()=>Up(e.projectId,e.sessionId),setWatch:t=>Fp(e.projectId,e.sessionId,t),setPinned:t=>Np(e.projectId,e.sessionId,t),setArchived:t=>Bp(e.projectId,e.sessionId,t),commit:t=>fp(e.projectId,e.sessionId,t),publicShares:{list:()=>qp(e.projectId,e.sessionId),create:(...t)=>Gp(e.projectId,e.sessionId,...t),revoke:(...t)=>Wp(e.projectId,e.sessionId,...t)}}}function i_(e){return{reminders:{list:()=>Bm(e.projectId,e.sessionId),create:t=>Km(e.projectId,e.sessionId,t),update:(t,n)=>Fo(e.projectId,e.sessionId,t,n),remove:t=>No(e.projectId,e.sessionId,t),run:t=>qm(e.projectId,e.sessionId,t)},audit:(t,n)=>zp(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Hy(e.projectId,e.sessionId,t,n),read:(t,n)=>Vy(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Yp(e.projectId,e.sessionId,t),messageAuthors:()=>gd(e.projectId,e.sessionId),modelUsage:()=>md(e.projectId,e.sessionId),transcriptSync:t=>Dr(e.projectId,e.sessionId,t),log:t=>Jp(e.projectId,e.sessionId,t),turn:()=>Lr(e.projectId,e.sessionId),prompts:{create:t=>$r(e.projectId,e.sessionId,t),list:()=>Qp(e.projectId,e.sessionId),remove:t=>Xp(e.projectId,e.sessionId,t),retry:t=>td(e.projectId,e.sessionId,t),edit:(t,n)=>Zp(e.projectId,e.sessionId,t,n),interrupt:t=>ed(e.projectId,e.sessionId,t),hold:t=>nd(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function CA(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var TA=["control_plane","provider_ingress","daemon","upstream_port"];function a_(e){return typeof e=="string"&&TA.includes(e)?e:null}function c_(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 l_(e,t){let n=(e===void 0?Ge():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await U(`${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=a_(r.headers.get("X-Kortix-Proxy-Hop"))??a_(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 u_=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,p_=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,d_=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,g_=new Set([22,4096,parseInt(tt.KORTIX_MASTER,10)]);function IA(e){return p_.test(e)}function vs(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 EA(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var MA=new Set(["'",'"',"`","<","(","["]),OA=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function jA(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&&MA.has(e[t]);)t++;for(;n>t&&OA.has(e[n-1]);)n--;return e.slice(t,n)}function DA(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var LA=/^\/proxy\/(\d{1,5})(\/.*)?$/,$A=/^\/(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 UA(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:$A.test(t.pathname)}catch{return!1}}function ks(e){if(!e)return null;let t=jA(EA(e.trim())),n=__(t);if(n){let r=vs(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(tt.KORTIX_MASTER,10);if(s===i){let l=r.pathname.match(LA);if(l){let p=parseInt(l[1],10);if(p>=1&&p<=65535)return s=p,o=vs(`${l[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=vs(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=DA(e);return r&&r!==e?ks(r):null}}function FA(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 NA(e,t){return t.some(([n,r])=>e>=n&&e<r)}function BA(e){let t=[],n=new Set,r=FA(e);u_.lastIndex=0;let s;for(;(s=u_.exec(e))!==null;){let o=ks(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:l}=o;a<1||a>65535||g_.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:NA(s.index,r)}))}return t}function zG(e){return BA(e).length>0}function KA(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function m_(e){return e.trim().toLowerCase().split("_").join("-")}function f_(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function qA(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(m_(n.sandboxId));return`${f_(s)}${t}`}function GA(e){return e.sandboxId.trim().length>0}function bt(e,t,n){let r=vs(t);if(!GA(n))return zA(e,r);let s=qA(e,r,n);return s||(KA(n.apiBaseUrl)?`http://p${e}-${m_(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${f_(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function YG(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return bt(3211,`/open?path=/workspace/${r}`,t)}function WA(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function JG(e){return`http://localhost:3211${WA(e)}`}function HA(){return"/health"}function QG(e){return bt(3211,HA(),e)}function XG(e,t){return bt(e,"/",t)}function VA(e){let t=ks(e);return!(!t||g_.has(t.port)||UA(e))}function y_(e,t){if(!e)return e;let n=ks(e);return n?VA(n.originalUrl)?bt(n.port,n.path,t):n.originalUrl:e}function zA(e,t="/"){return`http://localhost:${e}${t}`}var h_=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function __(e){let t=e.match(p_);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(d_);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(h_);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 ZG(e){try{let t=__(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function e1(e){return IA(e)||d_.test(e)||h_.test(e)}function t1(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Un="/web-proxy/";function n1(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Un}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(tt.KORTIX_MASTER,10);return`${bt(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function r1(e){try{let t=new URL(e),n=t.pathname.indexOf(Un);if(n===-1)return null;let s=t.pathname.slice(n+Un.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 s1(e){try{return new URL(e).pathname.includes(Un)}catch{return e.includes(Un)}}function o1(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 i1(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 b_(e){return{health:t=>l_(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>bt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>y_(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Fe(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Fi(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=ih(e,t),{ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g}=uh(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{...o_(m),...i_(m),...b_(m),...fh(m),...Ph(m),...qh(m),files:s_(l),...mh(m),get runtime(){return He(d("runtime").runtimeUrl)}}}function S_(e){return{apps:{list:()=>Mf(e),create:t=>Of(e,t),get:t=>qo(e,t),update:(...t)=>jf(e,...t),access:{get:(...t)=>Uf(e,...t),update:(...t)=>Nf(e,...t),session:(...t)=>Bf(e,...t),agents:t=>Ff(e,t)},remove:t=>Df(e,t),token:t=>Lf(e,t),authEnv:t=>$f(e,t),artifacts:{register:t=>Go(e,t),uploadArchive:(...t)=>Kf(e,...t),finalize:(...t)=>Wo(e,...t)},deployments:{create:(...t)=>qf(e,...t),list:t=>Gf(e,t),get:(...t)=>Wf(e,...t),logs:(...t)=>Hf(e,...t),remove:(...t)=>Yf(e,...t)},start:t=>Vf(e,t),stop:t=>zf(e,t),rollback:(...t)=>Jf(e,...t),machines:{list:t=>Qf(e,t),start:(t,n)=>Xf(e,t,n),stop:(t,n)=>Zf(e,t,n),restart:(t,n)=>ey(e,t,n),destroy:(t,n)=>ty(e,t,n)},scale:(...t)=>ny(e,...t),exec:(...t)=>ry(e,...t),volumes:{list:t=>sy(e,t),create:(...t)=>oy(e,...t),update:(...t)=>iy(e,...t),destroy:(...t)=>ay(e,...t),snapshots:(...t)=>cy(e,...t),snapshot:(...t)=>ly(e,...t),restore:(...t)=>uy(e,...t),fork:(...t)=>py(e,...t)}}}}function P_(e){return{list:()=>cl(e),invite:(...t)=>pl(e,...t),update:(...t)=>ll(e,...t),revoke:t=>ul(e,t),pendingInvites:()=>dl(e),resendInvite:(...t)=>ml(e,...t),revokeInvite:(...t)=>gl(e,...t),requests:()=>ol(e),approveRequest:(...t)=>il(e,...t),rejectRequest:(...t)=>al(e,...t),groupGrants:()=>fl(e),attachGroupGrant:(...t)=>yl(e,...t),updateGroupGrant:(...t)=>hl(e,...t),detachGroupGrant:t=>_l(e,t),resourceGrants:{list:()=>bl(e),create:t=>Sl(e,t),remove:t=>Pl(e,t)}}}function x_(e){return{tokens:{list:()=>pf(e),create:t=>df(e,t),revoke:t=>gf(e,t)},setupLinks:{requestSecret:t=>xf(e,t),requestConnector:t=>wf(e,t)},validateManifest:t=>Dc(e,t),gitToken:()=>Lc(e),agentIdentities:()=>um(e),secrets:{list:()=>kl(e),upsert:t=>Al(e,t),setStrategy:(...t)=>Rl(e,...t),broker:(...t)=>Cl(e,...t),remove:t=>wr(e,t),setPersonal:(...t)=>Ml(e,...t),removePersonal:t=>Ol(e,t),setGitCredential:t=>El(e,t),listProviderOAuth:()=>Tl(e),startProviderOAuth:(...t)=>po(e,...t),pollProviderOAuth:(...t)=>go(e,...t),removeProviderOAuth:t=>Il(e,t)},access:P_(e)}}function w_(e){return{list:()=>Vl(e),listAll:()=>zl(e),reconcile:(...t)=>Yl(e,...t),reconcileMember:(...t)=>Jl(e,...t),updateCredential:(...t)=>Ql(e,...t),revoke:(...t)=>Xl(e,...t),activate:(...t)=>Zl(e,...t),setDefault:(...t)=>eu(e,...t),rename:(...t)=>tu(e,...t),share:(...t)=>ru(e,...t),addComputer:(...t)=>nu(e,...t),pipedreamConnect:(...t)=>su(e,...t),pipedreamFinalize:(...t)=>ou(e,...t)}}function As(e){return{catalog:t=>on(e,t),tools:()=>ho(e),search:(...t)=>Hl(e,...t),describe:(...t)=>_o(e,...t),call:(...t)=>It(e,...t),callAction:(t,n,r,s)=>It(e,`${t}.${n}`,r,s),accounts:(...t)=>bo(e,...t),uploadAttachment:(...t)=>So(e,...t)}}function Ni(e,t){return{slug:t,run:(r,s,o)=>ko(e,t,r,s,o),call:(r,s,o)=>It(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?_o(e,`${t}.${r}`):(await on(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>bo(e,t),paginate:(r,s,o)=>Tu(e,t,r,s,o),uploadAttachment:(r,s)=>So(e,r,{...s,connector:t})}}var YA=100,v_=0,JA=new Set(["attachment_size_mismatch","attachment_failed"]),k_=()=>new S("Attachment expired. Attach the file again.",{code:"attachment_expired"});function Bi(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 QA(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+YA-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 A_(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,ln(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:k_()});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=QA(y,D,m);Er(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:Bi(L),receivedBytes:L.size})}).catch(L=>{L instanceof S&&JA.has(L.code??"")&&(y.upload=void 0),D()&&(y.item={...y.item,status:L instanceof S&&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-${++v_}`;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 _(y){let w=y.map(({attachment:v,file:C})=>{try{return{attachment:Bi(v),file:C}}catch{return}});h(w.flatMap(v=>v?[v.attachment.size]:[]));let x=w.map(v=>{if(!v)return;let C=`attachment-${++v_}`,{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 b(y){let w=r.get(y);!w||w.item.status==="ready"||(w.generation++,w.abort?.abort(),w.item={...w.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function O(y,{signal:w}={}){let x=[...y];return new Promise((v,C)=>{let D=()=>{o.delete(le),w?.removeEventListener("abort",L)},R=j=>{D(),C(j)},L=()=>R(ve()),le=()=>{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=Bi(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(le),w?.addEventListener("abort",L,{once:!0}),le()})}return{add:y=>T([y])[0],addMany:T,restore:_,retry(y){let w=r.get(y);if(w?.handedOff||f(),!(!w||w.item.status==="ready"||w.item.status==="uploading"||w.item.status==="processing"||w.item.status==="pending")){if(!w.item.file||w.upload&&Date.parse(w.upload.expires_at)<=Date.now())throw k_();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:b,submit(y){if(!a){for(let w of y){let x=r.get(w);x&&(x.handedOff=!0)}m()}},reclaim(y){if(!a){for(let w of y){let x=r.get(w);x&&(x.handedOff=!1)}m()}},whenReady:O,forget(y=d().map(w=>w.item.id)){for(let w of y){let x=r.get(w);x&&(x.generation++,x.abort?.abort(),r.delete(w))}m(),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&&ln(e,w).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(y){return s.add(y),()=>{s.delete(y)}}}}function R_(e){return{attachments:{upload:(...t)=>Er(e,...t),delete:(...t)=>ln(e,...t),createController:t=>A_(e,t)},get:t=>Ct(e,t),detail:()=>_r(e),skills:{remove:(...t)=>Wc(e,...t),create:(...t)=>Gc(e,...t)},audit:t=>yf(e,t),update:t=>Pr(e,t),archive:()=>xr(e),llmCatalog:()=>br(e),modelPicker:()=>Sr(e),modelAccess:()=>Qr(e),setModelAccess:t=>Xr(e,t),customLlmProviders:()=>Zr(e),setCustomLlmProvider:(t,n)=>es(e,t,n),deleteCustomLlmProvider:t=>ts(e,t),sandboxHealth:()=>Ar(e),onboardingComplete:(...t)=>qc(e,...t)}}function C_(e){return{sessions:{list:t=>jt(e,t),listPage:t=>Dp(e,t),create:t=>Dt(e,t),ensureWarm:()=>Hp(e),claimWarm:t=>Vp(e,t)},review:{list:t=>Im(e,t),summary:()=>Em(e),get:t=>Mm(e,t),submit:t=>Om(e,t),act:(...t)=>jm(e,...t),bulkAct:t=>Dm(e,t)},approvals:{list:t=>xl(e,t),resolve:(...t)=>vl(e,...t),sessionsNeedingInput:t=>wl(e,t)}}}function T_(e){return{files:{write:t=>Vu(e,t),list:t=>Bu(e,t),listDirectory:t=>Ku(e,t),read:(t,n)=>Gu(e,t,n),search:(...t)=>qu(e,...t),archive:(...t)=>Wu(e,...t),archiveRequest:(...t)=>Hu(e,...t),history:(...t)=>sp(e,...t)},git:{commits:()=>tp(e),commit:t=>np(e,t),commitDiff:t=>rp(e,t),branches:()=>ep(e),versionDiff:(...t)=>op(e,...t),inviteCollaborator:(...t)=>jc(e,...t)},changeRequests:{list:(...t)=>ip(e,...t),get:t=>ap(e,t),update:(...t)=>yp(e,...t),diff:t=>cp(e,t),mergePreview:t=>lp(e,t),open:(...t)=>up(e,...t),merge:(...t)=>pp(e,...t),close:(...t)=>dp(e,...t),reopen:(...t)=>gp(e,...t),requestChanges:(...t)=>mp(e,...t)},...C_(e)}}function I_(e){return{policies:{list:()=>Iu(e),set:(...t)=>Eu(e,...t)},reminders:{list:()=>Vr(e),updateMany:(...t)=>Wm(e,...t),removeMany:(...t)=>Hm(e,...t)},rooms:{list:(...t)=>Vm(e,...t),create:(...t)=>zm(e,...t),get:(...t)=>Ym(e,...t),update:(...t)=>Jm(e,...t),messages:(...t)=>Qm(e,...t),post:(...t)=>Xm(e,...t),markRead:(...t)=>Zm(e,...t),addSession:(...t)=>ef(e,...t),removeSession:(...t)=>tf(e,...t),addPerson:(...t)=>nf(e,...t),removePerson:(...t)=>rf(e,...t),people:(...t)=>sf(e,...t)},triggers:{list:()=>fd(e),eventApps:()=>Ad(e),eventTypes:(...t)=>kd(e,...t),create:(...t)=>yd(e,...t),update:(...t)=>hd(e,...t),remove:(...t)=>_d(e,...t),fire:((t,n)=>Pd(e,t,n)),runs:(...t)=>xd(e,...t),projectRuns:(...t)=>wd(e,...t),replay:(...t)=>vd(e,...t),setActivation:(...t)=>bd(e,...t)},...T_(e)}}function E_(e,t){return{connectors:{...As(e),list:()=>iu(e),config:(...n)=>gu(e,...n),create:(...n)=>yu(e,...n),remove:(...n)=>Su(e,...n),sync:()=>au(e),auth:{discover:(...n)=>hu(e,...n)},setName:(...n)=>mu(e,...n),setCredentialMode:(...n)=>cu(e,...n),setAuthorizationStrategy:(...n)=>lu(e,...n),setCredential:(...n)=>ku(e,...n),deleteCredential:(...n)=>Au(e,...n),setSensitive:(...n)=>uu(e,...n),connections:t,policies:{get:(...n)=>pu(e,...n),set:(...n)=>du(e,...n)},listMoves:()=>_u(e),move:(...n)=>bu(e,...n),pipedream:{listApps:(...n)=>Pu(e,...n),listSections:(...n)=>xu(e,...n),connect:(...n)=>fu(e,...n),finalize:(...n)=>Ru(e,...n)},discover:{list:(...n)=>Po(e,...n),sections:(...n)=>wu(e,...n),detail:(...n)=>xo(e,...n)}},...I_(e)}}function M_(e){return{gateway:{logs:t=>$g(e,t),log:t=>Ug(e,t),overview:t=>Fg(e,t),series:t=>Ng(e,t),breakdown:t=>Bg(e,t),sessions:t=>Kg(e,t),errors:t=>qg(e,t),budgets:()=>Gg(e),setBudget:t=>Wg(e,t),deleteBudget:t=>Hg(e,t),keys:()=>Vg(e),createKey:t=>zg(e,t),revokeKey:t=>Yg(e,t),routing:{get:()=>Og(e),set:t=>jg(e,t),reset:()=>Dg(e),preview:t=>Lg(e,t)},playground:(t,n,r)=>Jg(e,t,n,r)}}}function O_(e){return{modelDefaults:{get:()=>Dd(e),set:t=>Ld(e,t),clear:t=>$d(e,t)},setDefaultAgent:t=>Nd(e,t),sandbox:{list:()=>Nu(e),snapshots:()=>Ou(e),rebuildSnapshot:t=>ju(e,t),fixWithAgent:()=>Du(e),createTemplate:t=>Lu(e,t),updateTemplate:(...t)=>$u(e,...t),removeTemplate:t=>Uu(e,t),buildTemplate:t=>Fu(e,t),setProvider:t=>Kc(e,t)},setAgentScope:(...t)=>Fd(e,...t)}}function j_(e){return{channels:{slack:{installation:()=>_g(e),connect:t=>bg(e,t),mode:()=>Sg(e),completeInstall:t=>xg(e,t),manifest:()=>vg(e),disconnect:()=>kg(e),getFile:t=>Ag(e,t),uploadFile:t=>Rg(e,t)},teams:{completeInstall:t=>wg(e,t)},email:{installation:t=>Cg(e,t),mode:()=>Tg(e),connect:t=>Ig(e,t),disconnect:t=>Eg(e,t),updatePolicy:(...t)=>Mg(e,...t)}},updateFeatureFlag:(...t)=>Nc(e,...t),updateExperimentalFeature:(...t)=>Bc(e,...t),...O_(e)}}var z1=["screen","actions","audio"],Y1=["password_managers","messaging","banking"],J1={localHours:8760,remoteDays:3650},Q1=[500,1e3,2e3,5e3,1e4],X1=[720,1080,1440,2160],Z1={intervalMs:2e3,maxHeight:1440},XA=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function eW(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(/\.$/,""),XA.test(n)?n:null}function tW(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 oW(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var Y=e=>`/accounts/${e}/capture`;function ze(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 D_=e=>ze({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}),Ki=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function L_(e,t={}){return u(await c.get(`${Y(e)}/devices${ze({user_id:t.userId,scope:t.scope})}`))}async function $_(e,t){return u(await c.delete(`${Y(e)}/devices/${t}`))}async function U_(e,t,n){return u(await c.put(`${Y(e)}/devices/${t}/link`,{user_id:n}))}async function F_(e){return u(await c.get(`${Y(e)}/enrollment-tokens`))}async function N_(e,t){return u(await c.post(`${Y(e)}/enrollment-tokens`,t))}async function B_(e,t){return u(await c.delete(`${Y(e)}/enrollment-tokens/${t}`))}async function K_(e,t={}){return u(await c.get(`${Y(e)}/enrollments${ze({status:t.status})}`))}async function q_(e,t,n){return u(await c.post(`${Y(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function G_(e,t){return u(await c.post(`${Y(e)}/enrollments/${t}/deny`,{}))}async function W_(e){return u(await c.get(`${Y(e)}/policy`))}async function H_(e,t){return u(await c.put(`${Y(e)}/policy`,{policy:t}))}async function V_(e){return u(await c.get(`${Y(e)}/storage`))}async function z_(e,t){return u(await c.put(`${Y(e)}/storage`,t))}async function Y_(e,t={}){return u(await c.get(`${Y(e)}/timeline${ze(Ki(t))}`))}async function J_(e,t={}){return u(await c.get(`${Y(e)}/timeline/items${ze(Ki(t))}`))}async function Q_(e,t={}){return u(await c.get(`${Y(e)}/days${ze({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function X_(e,t){return u(await c.get(`${Y(e)}/search${D_(t)}`))}async function Z_(e,t,n={}){return u(await c.get(`${Y(e)}/frames/${t}${ze({user_id:n.userId,device_id:n.deviceId})}`))}async function eb(e,t,n={}){return u(await c.get(`${Y(e)}/chunks/${t}/media${ze({user_id:n.userId,device_id:n.deviceId})}`))}async function tb(e,t,n){return u(await c.get(`${Y(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function nb(e){return u(await c.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function rb(e,t){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function sb(e){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function ob(e){return u(await c.get(Y(e)))}async function ib(e,t){return u(await c.patch(Y(e),{enabled:t}))}async function ab(e){return u(await c.get(`/capture/me/search${D_(e)}`))}async function cb(e={}){return u(await c.get(`/capture/me/timeline${ze(Ki(e))}`))}async function lb(e){return u(await c.get(`/capture/me/frames/${e}`))}function eR(e){return{workspace:{get:()=>ob(e),setEnabled:t=>ib(e,t)},devices:{list:t=>L_(e,t),revoke:t=>$_(e,t),link:(t,n)=>U_(e,t,n),assetUrl:(t,n)=>tb(e,t,n)},enrollment:{tokens:{list:()=>F_(e),create:t=>N_(e,t),revoke:t=>B_(e,t)},list:t=>K_(e,t),approve:(t,n)=>q_(e,t,n),deny:t=>G_(e,t)},policy:{get:()=>W_(e),set:t=>H_(e,t)},storage:{get:()=>V_(e),set:t=>z_(e,t)},timeline:{get:t=>Y_(e,t),items:t=>J_(e,t),days:t=>Q_(e,t)},search:t=>X_(e,t),frame:(t,n)=>Z_(e,t,n),media:(t,n)=>eb(e,t,n)}}var ub={account:e=>eR(e),deviceGrant:nb,approveDevice:rb,denyDevice:sb,me:{search:ab,timeline:cb,frame:lb}};async function pb(e){let t=e?.fetch??I().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??I().backendUrl,r=await t(`${Ne(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new S(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var tR=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function pW(e,t){let n=o=>{let i=tR.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 nR(){return ht()}var db=null,gb=!1;function rR(e){let t=db;db=e,!(gb||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(gb=!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 sR(e,t){t?.global!==!1&&rR(e),eo(e,t);let n=oh(e),{auth:r,accounts:s,iam:o,accountInvites:i}=eh(),{billing:a,sandboxShares:l}=Qy(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=Jy();function h(P){let k=w_(P);return{...R_(P),...S_(P),...x_(P),...E_(P,k),...M_(P),...j_(P),connector:T=>Ni(P,T),session:T=>Fi(P,T,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:As(),connector:P=>Ni(void 0,P),project:h,session:(P,k)=>Fi(P,k,e,n),github:d,gitBackend:g,billing:a,sandboxShares:l,connectStatus:m,marketplace:f,capture:ub,notifications:{registerDeviceToken:fy,unregisterDeviceToken:yy,releaseDeviceToken:hy,list:_y,markRead:by,preferences:Sy,updatePreferences:Py,webPushPublicKey:xy,registerWebPushSubscription:wy,unregisterWebPushSubscription:vy},mobileClientPolicy:pb,validateToken:Ec,runtime:nR}}function oR(){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 iR(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Ht(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function aR(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function cR(e){if(Ht(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 lR(e){let t=Ht(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function uR(e,t){let n=Ht(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 pR(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 dR(e,t){return Ht(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 gR(e,t,n){return Ht(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 mR(e,t,n){let r=Ht(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 mb={thinking:!1,toolDetails:!0,assistantMetadata:!0};function fR(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function yR(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 hR(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
21
|
+
`)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*kv(e,t,n){let r=e.eventTransport??Ri(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 Pn(e){let t=s=>(o,i)=>wv(e,Pv(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:kv(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 mh=200;async function vv(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 rt(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 S(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function fh(e){let t=e.runtimeUrl.replace(/\/$/,""),n=Pn({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 S(`Reading the session transcript failed: ${await vv(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,mh),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,mh),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=>rt(i,"Reading the session status failed")),n.permission.list().then(i=>rt(i,"Reading permission requests failed")),n.question.list().then(i=>rt(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{rt(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){rt(await n.question.reject({requestID:r}),"Dismissing the question failed");return}rt(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 S("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});let i=rt(await n.session.status(),"Reading the session status failed")?.[e.rootId];if(i&&i.type!=="idle")throw new S("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 S("Compaction has not finished. Check the session status before trying again.",{code:"LONG_TURN_PROXY_TIMEOUT",status:a.response?.status});return rt(a,"Compacting the session failed"),s}}}function yh(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return fh({runtimeUrl:r,rootId:n,fetch:U})}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 hh(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await md(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var xn=BigInt(4096),st=BigInt(0xffffffffffff),_h=st+BigInt(1),Av=_h/BigInt(2),ht=BigInt(3600*1e3)*xn,Ci=120*1e3,Rv=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,Cv=/^msg_([0-9a-f]{12})/,bh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function qt(e){let t=Cv.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function wn(e){return BigInt(Math.trunc(e))*xn&st}function Gt(e,t){let n=e-t&st;return n>=Av&&(n-=_h),n}function Sh(e){let t=null;for(let n of e)n!=null&&(t===null||Gt(n,t)>BigInt(0))&&(t=n);return t}function Tv(e,t){let n=qt(e);return n===null?!1:Gt(n,wn(t))>ht}function Iv(e,t){let n=t===void 0?null:wn(t);return Ph(e,r=>n===null||Gt(r,n)<=ht)}function Ph(e,t){let n=[];for(let r of e){let s=qt(r);s!==null&&t(s)&&n.push(s)}return Sh(n)}function Ev(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=bh[n%62])}return e}function xh(e){let t=e.random,n=wn(e.nowMs-(e.backdateMs??Ci)),r=e.newestKnownTime??null;if(r!==null){let o=Gt(r,n);o>=BigInt(0)&&o<=ht&&(n=r+BigInt(1)&st)}let s="";if(t)for(let o=0;o<14;o++)s+=bh[Math.min(61,Math.floor(t()*62))];else s=Ev();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function Ti(e={}){let t=e.nowMs??Date.now(),n=wn(t-Ci),r=Ph(e.after??[],s=>{let o=Gt(s,n);return o>=BigInt(0)&&o<=ht});return xh({nowMs:t,newestKnownTime:r}).id}function wh(e){return{scope:()=>dd(e.projectId,e.sessionId),providerSecretPool:{list:()=>Hl(e.projectId,e.sessionId),get:t=>Wl(e.projectId,e.sessionId,t),set:(t,n)=>Vl(e.projectId,e.sessionId,t,n)},rescope:t=>gd(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=Ti(),p=await Ur(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 S("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var kh=async function*(e){let t=I().eventStreamTransport;if(!t){yield*Ri(((s,o)=>U(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await At(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function Ge(){let e=lh();return e||(I().billingEnabled??!1?"":Md())}async function Ii(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Ei(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function vh(e){let t=Ei(e),n=await U(`${t}/env`);if(!n.ok)throw new Error(await Ii(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Ah(e,t,n){let r=Ei(e),s=await U(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await Ii(s,"Failed to save secret"))}async function Rh(e,t){let n=Ei(e),r=await U(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Ii(r,"Failed to delete secret"))}var Mv={list:vh,set:Ah,delete:Rh};async function Ov(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await U(`${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 ms(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function kn(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return pe(e)}async function Ch(e){let t=kn(e),n=await U(`${t}/kortix/pty`);if(!n.ok)throw new Error(await ms(n,"Failed to list terminals"));return n.json()}async function Th(e,t){let n=kn(e),r=await U(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await ms(r,"Failed to create terminal"));return r.json()}async function Ih(e,t,n){let r=kn(e),s=await U(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await ms(s,"Failed to update terminal"));return s.json()}async function Eh(e,t){let n=kn(e),r=await U(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await ms(r,"Failed to remove terminal"))}async function Mh(e,t,n){let r=kn(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:"),pe(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await on();a&&i.set("token",a),n?.wake&&i.set("wake","1");let l=i.toString();return l?`${o}${o.includes("?")?"&":"?"}${l}`:o}function jv(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 ot="\x1B",Oh="\x07",Dv="\0",Mi=`(?:${Oh}|${ot}\\\\)`,Lv=[new RegExp(`${ot}\\]697;[^${Oh}${ot}]*${Mi}`,"g"),new RegExp(`${Dv}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${ot}\\][0-9]+;rgb:[0-9a-fA-F/]+${Mi}`,"g"),new RegExp(`${ot}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Mi}`,"g"),new RegExp(`${ot}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${ot}\\[\\d+;\\d+R`,"g"),new RegExp(`${ot}\\[\\?[0-9;]*c`,"g")];function $v(e){let t=e;for(let n of Lv)t=t.replace(n,"");return t}var Uv={list:Ch,create:Th,update:Ih,remove:Eh,webSocketUrl:Mh};async function M(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await U(`${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 oq(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 iq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function aq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function cq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function lq(e,t){return M(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function uq(e,t,n){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function pq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function dq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function gq(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function mq(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return M(e,`/kortix/tickets${n}`)}async function fq(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function yq(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function hq(e,t){return M(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function _q(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function bq(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function Sq(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function Pq(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function xq(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function wq(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function kq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function vq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function Aq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function Rq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function Cq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function Tq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function Iq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function Eq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function Mq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function Oq(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function jq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Dq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function Lq(e,t,n=200){return M(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function $q(e){return M(e,"/kortix/projects")}async function Uq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function Fq(e,t){return M(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function Nq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function Bq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Kq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function qq(e,t,n="all"){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function Gq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function Wq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function Hq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function Vq(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function zq(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function Yq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function Jq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function Qq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function Xq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function Zq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function eG(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function tG(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var Fv=1e4,Nv={retryOnAuthError:!1};function Wt(e,t,n){return M(e,t,{signal:AbortSignal.timeout(Fv),...n},Nv)}async function nG(e,t=!1){return(await Wt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function rG(e){return(await Wt(e,"/kortix/services/templates")).templates??[]}async function sG(e,t){return(await Wt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function oG(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return Wt(e,s,{method:r?"DELETE":"POST"})}async function iG(e,t){return Wt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function aG(e,t){return Wt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var We=new Map,Bv=256,vn=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function _t(){let e=Ge();if(!e)throw new vn;return He(e)}function He(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=We.get(e);if(t)return We.delete(e),We.set(e,t),t;if(!no())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=Pn({baseUrl:e,fetch:U,eventTransport:kh});return We.set(e,n),We.size>Bv&&We.delete(We.keys().next().value),n}function fG(e){We.delete(e)}function yG(){We.clear()}var fs=new Map;function hG(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=fs.get(e);if(t)return t;let n=Pn({baseUrl:e,fetch});return fs.set(e,n),n}function _G(e){fs.delete(e)}function bG(){fs.clear()}async function Kv(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 SG(e){let t=Ge();if(!t)throw new S("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await U(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new S(`System reload failed (${r.status}): ${await Kv(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new S(`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 S(`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 jh="frontend";function ys(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${jh}] ${t}`,...n?[n]:[]);try{_t().app.log({service:jh,level:e,message:t,extra:n})}catch{}}var Ve={debug:(e,t)=>ys("debug",e,t),info:(e,t)=>ys("info",e,t),warn:(e,t)=>ys("warn",e,t),error:(e,t)=>ys("error",e,t)};var qv=16,Gv=8,Dh=6e4,Wv=250,Hv=1e3,Vv=3e4,zv=5,Yv=.5,Jv=3e3,Qv=3e4,Lh=2e4,Xv=2e3,$h=8;function Zv(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function eA(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 Uh(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,qv-l))};return{push(l){let p=eA(n[n.length-1]?.event,l);if(p)n[n.length-1]={type:p.type,event:p};else{let d=Zv(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 Fh(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 Oi(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 tA(e,t,n,r){return new Promise((s,o)=>{let i=!1,a=t.setTimeout(()=>{i||(i=!0,Ve.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:Jv,sseMaxRetryDelay:Qv,sseMaxRetryAttempts:1}).then(l=>{i||(i=!0,t.clearTimeout(a),s(l))},l=>{i||(i=!0,t.clearTimeout(a),o(l))})})}async function nA(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=Fh(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<Gv)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return o}function Nh(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<Xv)}function Bh(e,t,n){Ve.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),Oi(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function Kh(e,t,n){let r=t?Wv:Math.min(Hv*2**Math.min(e-1,zv),Vv);return Math.round(r*(1+Yv*(n.random?.()??0)))}function qh(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 Gh(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=Fh(o);P.promise.then(()=>h.abort());try{let{stream:v}=await tA(t,n,r,h);l();let T=()=>{n.clearTimeout(m),m=n.setTimeout(()=>{Ve.warn("SSE heartbeat timeout, forcing reconnect"),h.abort()},s)};T(),d=await nA(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),_=nn(v)||nn(v?.cause);if(Ve.error("SSE event stream error",{error:T,retryCount:i,isAuthError:_}),_)try{ho(),await yo(),Ve.info("SSE: refreshed auth token after auth error")}catch(b){Ve.error("SSE: failed to refresh auth token",{error:String(b)})}}finally{n.clearTimeout(m),h.abort(),P.cleanup(),p.flush()}return{streamHadWork:d,stableConnection:g,error:f}}function rA(e){return{type:"heartbeat-gap",gapMs:e}}function sA(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 oA={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},iA=5e3,aA=1e4,cA=4,An=new WeakMap;function lA(e,t,n){let r=t.timers??oA,s=t.connectTimeoutMs??Lh,o=t.heartbeatTimeoutMs??Dh,i=t.maxConsecutiveHardFailures??$h,a=new AbortController,l=(v,...T)=>Oi(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=Uh(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>iA)&&l(_=>_.onGapRehydrate,v)}m=r.now()},coalescer:h};return(async()=>{let v=0,T=0,_=0;for(;!a.signal.aborted;){let b=r.now(),O=await Gh({...P,retryCount:v});if(a.signal.aborted)break;let y=O.error,{streamHadWork:w,stableConnection:x}=O,k=r.now()-b;if(T=Nh(w,y,k)?T+1:0,T>=i){Bh(n,T,y),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||w},_=x&&k<aA?_+1:0;let R=x&&_<=cA;R?v=0:(v++,v>1&&Ve.warn("SSE event stream reconnecting",{retryCount:v})),await qh(r,a.signal,Kh(v,R,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),h.clearTimer()}}}function ji(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?He(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=An.get(i);if(l?.isParked()&&(An.delete(i),l=void 0),!l)l=lA(i,e,new Set([a])),An.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(),An.get(i)===p&&An.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function Wh(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return He(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return He(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return He(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return ji({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Vh(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 S(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function $i(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 ae(e){let t=(e??Ge()).trim();if(!t)throw new vn;return t}async function En(e,t){let n=await U(`${ae(t)}${e}`);if(!n.ok)throw new S(await $i(n),{status:n.status,response:n});return n.json()}async function Ui(e,t,n,r,s){let o=await U(`${ae(s)}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new S(`${r} failed (${o.status}): ${await $i(o)}`,{status:o.status,response:o});return o.json()}var Fi=["/workspace","/tmp","/home","/opt"],uA=Fi.filter(e=>e!=="/workspace");function zh(e){return Fi.some(t=>e===t||e.startsWith(`${t}/`))}function Mn(e){return zh(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function bt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(uA.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Yh=bt;async function On(e,t){let n=ae(t),r=bt(e)||".";return(await En(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function jn(e,t){let n=bt(e);return En(`/file/content?path=${encodeURIComponent(n)}`,t)}async function pA(e,t,n){let r=ae(n),s=bt(e),o=await U(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new S(await $i(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new S("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 dA=8,hs=0,Jh=[];async function gA(){if(hs<dA){hs++;return}await new Promise(e=>Jh.push(e)),hs++}function mA(){hs--,Jh.shift()?.()}function fA(e,t){let n=ae(t);return Cr(`${n}/file/raw?path=${encodeURIComponent(bt(e))}`)}async function Dn(e,t){await gA();try{let n=ae(t);try{return await pA(e,void 0,n)}catch{}let r=await jn(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{mA()}}async function _s(e){return En("/file/status",ae(e))}async function bs(e,t,n){let r=ae(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),En(`/find/file?${s.toString()}`,r)}async function Ss(e,t){let n=ae(t);return(await En(`/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 Rn=[400,1200],yA=e=>e===408||e===429||e===502||e===503||e===504,Hh=e=>new Promise(t=>setTimeout(t,e));function hA(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Di=3e4,Qh=15*6e4,_A=256;function Cn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Di;let t=Di+e/_A;return Math.min(Qh,Math.max(Di,Math.round(t)))}async function bA(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 Tn(e,t){let n;for(let s=0;s<=Rn.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,hA(a)||s===Rn.length)break;await Hh(Rn[s]);continue}if(o.ok)return o.json();let i=await bA(o);if(n=new S(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!yA(o.status)||s===Rn.length)throw n;await Hh(Rn[s])}if(n instanceof S)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new S(`Upload failed: ${r}`)}var Li=8*1024*1024;function SA(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new S(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Xh(e,t){try{e?.onProgress?.(t)}catch{}}function Zh(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 PA(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=ae(o),l=Cn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Li){let d=await Tn(()=>Zh(e,t,p),g=>U(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:l}));return SA(d[0],e.size),Xh(i,{loadedBytes:e.size,totalBytes:e.size}),d}return xA(e,t,p,a,i)}async function xA(e,t,n,r,s){let i=(await Tn(()=>Zh(new Blob([],{type:e.type}),t,n),l=>U(`${r}/file/upload`,{method:"POST",body:l},{timeoutMs:Cn(0)})))[0]?.path;if(!i)throw new S("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=PA(i);if(!a.name)throw new S(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let l=0;l<e.size;l+=Li){let p=Math.min(e.size,l+Li),d=e.slice(l,p,e.type),g=await Tn(()=>{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=>U(`${r}/file/append`,{method:"POST",body:m},{timeoutMs:Cn(d.size)}));if(g.path!==i||g.size!==p)throw new S(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Xh(s,{loadedBytes:p,totalBytes:e.size})}}catch(l){throw await Ht(i,r).catch(()=>{}),l}return[{path:i,size:e.size}]}function wA(e,t,n){let r=ae(n);return Tn(()=>{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=>U(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:kA}))}var kA=Qh;function vA(e,t,n){let r=ae(n),s=Cn(t.size);return Tn(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>U(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var In=class extends S{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 Ps(e,t){let n=ae(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",l=Mn(`${a}/${i}`),p=[];try{p=await On(e_(l),n)}catch(g){if(!(g instanceof S&&g.status===404))throw g}if(p.some(g=>g.name===t_(l)))throw new In(l);let d=await n_(l,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function xs(e,t,n){let r=ae(n);return vA(t,await Dn(e,r),r)}function AA(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function e_(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function t_(e){return e.slice(e.lastIndexOf("/")+1)}function RA(){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 ws(e,t,n){let r=ae(n),s=Mn(AA(e.trim()));return n_(s,t,r,{overwrite:!0})}async function n_(e,t,n,r){let s=t_(e);if(!s)throw new S(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=e_(e);await $n(o,n).catch(()=>{});let i=RA(),a=await Ln(t,o,`.${s}.kortix-write-${i}`,n),l=a[0]?.path;if(!l)throw new S(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=Mn(l);try{await r_(p,e,n,r.overwrite)}catch(g){throw await Ht(p,n).catch(()=>{}),!r.overwrite&&g instanceof S&&g.status===409?new In(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Ht(e,t){return Ui("/file","DELETE",{path:e},"Delete",t)}async function $n(e,t){return Ui("/file/mkdir","POST",{path:e},"Mkdir",t)}async function ks(e,t,n){return r_(e,t,ae(n),!0)}async function r_(e,t,n,r){return Ui("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function s_(){return Vh(await _t().project.current())}async function Ni(){return Vh(await _t().global.health())}async function o_(){try{return(await Ni()).healthy===!0}catch{return!1}}var CA={list:On,read:jn,readBlob:Dn,status:_s,findFiles:bs,findText:Ss,upload:Ln,write:ws,create:Ps,copy:xs,remove:Ht,mkdir:$n,rename:ks,currentProject:s_,health:Ni,isReachable:o_,toDaemonPath:bt,toSandboxAbsolutePath:Mn,toWorkspaceRelative:Yh};function i_(e){return{list:async t=>On(t,(await e()).runtimeUrl),read:async t=>jn(t,(await e()).runtimeUrl),readBlob:async t=>Dn(t,(await e()).runtimeUrl),status:async()=>_s((await e()).runtimeUrl),findFiles:async(t,n)=>bs(t,n,(await e()).runtimeUrl),findText:async t=>Ss(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>Ln(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>ws(t,n,(await e()).runtimeUrl),create:async t=>Ps(t,(await e()).runtimeUrl),copy:async(t,n)=>xs(t,n,(await e()).runtimeUrl),remove:async t=>Ht(t,(await e()).runtimeUrl),mkdir:async t=>$n(t,(await e()).runtimeUrl),rename:async(t,n)=>ks(t,n,(await e()).runtimeUrl)}}function a_(e){return{get:t=>Dr(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:()=>Vr(e.sessionId,{projectId:e.projectId}),update:t=>od(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),id(e.projectId,e.sessionId)),restore:()=>cd(e.projectId,e.sessionId),recover:()=>ad(e.projectId,e.sessionId),start:(...t)=>ft(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Dd(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Fr(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Nr(e.projectId,e.sessionId)),configState:()=>ld(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),ud(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),pd(e.projectId,e.sessionId,...t)),setSharing:t=>Up(e.projectId,e.sessionId,t),previews:()=>Gp(e.projectId,e.sessionId),participants:()=>Fp(e.projectId,e.sessionId),watch:()=>Np(e.projectId,e.sessionId),setWatch:t=>Bp(e.projectId,e.sessionId,t),setPinned:t=>Kp(e.projectId,e.sessionId,t),setArchived:t=>qp(e.projectId,e.sessionId,t),commit:t=>hp(e.projectId,e.sessionId,t),publicShares:{list:()=>Wp(e.projectId,e.sessionId),create:(...t)=>Hp(e.projectId,e.sessionId,...t),revoke:(...t)=>Vp(e.projectId,e.sessionId,...t)}}}function c_(e){return{reminders:{list:()=>qm(e.projectId,e.sessionId),create:t=>Gm(e.projectId,e.sessionId,t),update:(t,n)=>Bo(e.projectId,e.sessionId,t,n),remove:t=>Ko(e.projectId,e.sessionId,t),run:t=>Wm(e.projectId,e.sessionId,t)},audit:(t,n)=>Jp(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>zy(e.projectId,e.sessionId,t,n),read:(t,n)=>Yy(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Qp(e.projectId,e.sessionId,t),messageAuthors:()=>fd(e.projectId,e.sessionId),modelUsage:()=>yd(e.projectId,e.sessionId),transcriptSync:t=>Lr(e.projectId,e.sessionId,t),log:t=>Xp(e.projectId,e.sessionId,t),turn:()=>$r(e.projectId,e.sessionId),prompts:{create:t=>Ur(e.projectId,e.sessionId,t),list:()=>Zp(e.projectId,e.sessionId),remove:t=>ed(e.projectId,e.sessionId,t),retry:t=>rd(e.projectId,e.sessionId,t),edit:(t,n)=>td(e.projectId,e.sessionId,t,n),interrupt:t=>nd(e.projectId,e.sessionId,t),hold:t=>sd(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function IA(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var EA=["control_plane","provider_ingress","daemon","upstream_port"];function l_(e){return typeof e=="string"&&EA.includes(e)?e:null}function u_(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 p_(e,t){let n=(e===void 0?Ge():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await U(`${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=l_(r.headers.get("X-Kortix-Proxy-Hop"))??l_(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 d_=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,g_=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,m_=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,f_=new Set([22,4096,parseInt(tt.KORTIX_MASTER,10)]);function MA(e){return g_.test(e)}function vs(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 OA(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var jA=new Set(["'",'"',"`","<","(","["]),DA=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function LA(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&&jA.has(e[t]);)t++;for(;n>t&&DA.has(e[n-1]);)n--;return e.slice(t,n)}function $A(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var UA=/^\/proxy\/(\d{1,5})(\/.*)?$/,FA=/^\/(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 NA(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:FA.test(t.pathname)}catch{return!1}}function As(e){if(!e)return null;let t=LA(OA(e.trim())),n=S_(t);if(n){let r=vs(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(tt.KORTIX_MASTER,10);if(s===i){let l=r.pathname.match(UA);if(l){let p=parseInt(l[1],10);if(p>=1&&p<=65535)return s=p,o=vs(`${l[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=vs(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=$A(e);return r&&r!==e?As(r):null}}function BA(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 KA(e,t){return t.some(([n,r])=>e>=n&&e<r)}function qA(e){let t=[],n=new Set,r=BA(e);d_.lastIndex=0;let s;for(;(s=d_.exec(e))!==null;){let o=As(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:l}=o;a<1||a>65535||f_.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:KA(s.index,r)}))}return t}function e1(e){return qA(e).length>0}function GA(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function y_(e){return e.trim().toLowerCase().split("_").join("-")}function h_(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function WA(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(y_(n.sandboxId));return`${h_(s)}${t}`}function HA(e){return e.sandboxId.trim().length>0}function St(e,t,n){let r=vs(t);if(!HA(n))return JA(e,r);let s=WA(e,r,n);return s||(GA(n.apiBaseUrl)?`http://p${e}-${y_(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${h_(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function t1(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return St(3211,`/open?path=/workspace/${r}`,t)}function VA(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function n1(e){return`http://localhost:3211${VA(e)}`}function zA(){return"/health"}function r1(e){return St(3211,zA(),e)}function s1(e,t){return St(e,"/",t)}function YA(e){let t=As(e);return!(!t||f_.has(t.port)||NA(e))}function __(e,t){if(!e)return e;let n=As(e);return n?YA(n.originalUrl)?St(n.port,n.path,t):n.originalUrl:e}function JA(e,t="/"){return`http://localhost:${e}${t}`}var b_=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function S_(e){let t=e.match(g_);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(m_);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(b_);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 o1(e){try{let t=S_(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function i1(e){return MA(e)||m_.test(e)||b_.test(e)}function a1(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Un="/web-proxy/";function c1(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Un}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(tt.KORTIX_MASTER,10);return`${St(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function l1(e){try{let t=new URL(e),n=t.pathname.indexOf(Un);if(n===-1)return null;let s=t.pathname.slice(n+Un.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 u1(e){try{return new URL(e).pathname.includes(Un)}catch{return e.includes(Un)}}function p1(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 d1(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 P_(e){return{health:t=>p_(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>St(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>__(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Fe(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Bi(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=ch(e,t),{ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g}=dh(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{...a_(m),...c_(m),...P_(m),...hh(m),...wh(m),...Wh(m),files:i_(l),...yh(m),get runtime(){return He(d("runtime").runtimeUrl)}}}function x_(e){return{apps:{list:()=>jf(e),create:t=>Df(e,t),get:t=>Wo(e,t),update:(...t)=>Lf(e,...t),access:{get:(...t)=>Nf(e,...t),update:(...t)=>Kf(e,...t),session:(...t)=>qf(e,...t),agents:t=>Bf(e,t)},remove:t=>$f(e,t),token:t=>Uf(e,t),authEnv:t=>Ff(e,t),artifacts:{register:t=>Ho(e,t),uploadArchive:(...t)=>Gf(e,...t),finalize:(...t)=>Vo(e,...t)},deployments:{create:(...t)=>Wf(e,...t),list:t=>Hf(e,t),get:(...t)=>Vf(e,...t),logs:(...t)=>zf(e,...t),remove:(...t)=>Qf(e,...t)},start:t=>Yf(e,t),stop:t=>Jf(e,t),rollback:(...t)=>Xf(e,...t),machines:{list:t=>Zf(e,t),start:(t,n)=>ey(e,t,n),stop:(t,n)=>ty(e,t,n),restart:(t,n)=>ny(e,t,n),destroy:(t,n)=>ry(e,t,n)},scale:(...t)=>sy(e,...t),exec:(...t)=>oy(e,...t),volumes:{list:t=>iy(e,t),create:(...t)=>ay(e,...t),update:(...t)=>cy(e,...t),destroy:(...t)=>ly(e,...t),snapshots:(...t)=>uy(e,...t),snapshot:(...t)=>py(e,...t),restore:(...t)=>dy(e,...t),fork:(...t)=>gy(e,...t)}}}}function w_(e){return{list:()=>ul(e),invite:(...t)=>gl(e,...t),update:(...t)=>pl(e,...t),revoke:t=>dl(e,t),pendingInvites:()=>ml(e),resendInvite:(...t)=>yl(e,...t),revokeInvite:(...t)=>fl(e,...t),requests:()=>al(e),approveRequest:(...t)=>cl(e,...t),rejectRequest:(...t)=>ll(e,...t),groupGrants:()=>hl(e),attachGroupGrant:(...t)=>_l(e,...t),updateGroupGrant:(...t)=>bl(e,...t),detachGroupGrant:t=>Sl(e,t),resourceGrants:{list:()=>Pl(e),create:t=>xl(e,t),remove:t=>wl(e,t)}}}function k_(e){return{tokens:{list:()=>gf(e),create:t=>mf(e,t),revoke:t=>ff(e,t)},setupLinks:{requestSecret:t=>kf(e,t),requestConnector:t=>vf(e,t)},validateManifest:t=>$c(e,t),gitToken:()=>Uc(e),agentIdentities:()=>dm(e),secrets:{list:()=>Rl(e),upsert:t=>Cl(e,t),setStrategy:(...t)=>Tl(e,...t),broker:(...t)=>Il(e,...t),remove:t=>kr(e,t),setPersonal:(...t)=>jl(e,...t),removePersonal:t=>Dl(e,t),setGitCredential:t=>Ol(e,t),listProviderOAuth:()=>El(e),startProviderOAuth:(...t)=>go(e,...t),pollProviderOAuth:(...t)=>mo(e,...t),removeProviderOAuth:t=>Ml(e,t)},access:w_(e)}}function v_(e){return{list:()=>Yl(e),listAll:()=>Jl(e),reconcile:(...t)=>Ql(e,...t),reconcileMember:(...t)=>Xl(e,...t),updateCredential:(...t)=>Zl(e,...t),revoke:(...t)=>eu(e,...t),activate:(...t)=>tu(e,...t),setDefault:(...t)=>nu(e,...t),rename:(...t)=>ru(e,...t),share:(...t)=>ou(e,...t),addComputer:(...t)=>su(e,...t),pipedreamConnect:(...t)=>iu(e,...t),pipedreamFinalize:(...t)=>au(e,...t)}}function Rs(e){return{catalog:t=>an(e,t),tools:()=>_o(e),search:(...t)=>zl(e,...t),describe:(...t)=>bo(e,...t),call:(...t)=>Et(e,...t),callAction:(t,n,r,s)=>Et(e,`${t}.${n}`,r,s),accounts:(...t)=>So(e,...t),uploadAttachment:(...t)=>Po(e,...t)}}function Ki(e,t){return{slug:t,run:(r,s,o)=>Ao(e,t,r,s,o),call:(r,s,o)=>Et(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?bo(e,`${t}.${r}`):(await an(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>So(e,t),paginate:(r,s,o)=>Eu(e,t,r,s,o),uploadAttachment:(r,s)=>Po(e,r,{...s,connector:t})}}var QA=100,A_=0,XA=new Set(["attachment_size_mismatch","attachment_failed"]),R_=()=>new S("Attachment expired. Attach the file again.",{code:"attachment_expired"});function qi(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 ZA(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+QA-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 C_(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,un(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:R_()});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=ZA(y,D,m);Mr(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:qi(L),receivedBytes:L.size})}).catch(L=>{L instanceof S&&XA.has(L.code??"")&&(y.upload=void 0),D()&&(y.item={...y.item,status:L instanceof S&&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-${++A_}`;return r.set(k,{generation:0,item:{id:k,file:x,filename:x.name,mime:x.type||"application/octet-stream",size:x.size,status:"pending",receivedBytes:0}}),k});return m(),v(),w}function _(y){let w=y.map(({attachment:k,file:C})=>{try{return{attachment:qi(k),file:C}}catch{return}});h(w.flatMap(k=>k?[k.attachment.size]:[]));let x=w.map(k=>{if(!k)return;let C=`attachment-${++A_}`,{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 b(y){let w=r.get(y);!w||w.item.status==="ready"||(w.generation++,w.abort?.abort(),w.item={...w.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function O(y,{signal:w}={}){let x=[...y];return new Promise((k,C)=>{let D=()=>{o.delete(le),w?.removeEventListener("abort",L)},R=j=>{D(),C(j)},L=()=>R(ke()),le=()=>{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=qi(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(le),w?.addEventListener("abort",L,{once:!0}),le()})}return{add:y=>T([y])[0],addMany:T,restore:_,retry(y){let w=r.get(y);if(w?.handedOff||f(),!(!w||w.item.status==="ready"||w.item.status==="uploading"||w.item.status==="processing"||w.item.status==="pending")){if(!w.item.file||w.upload&&Date.parse(w.upload.expires_at)<=Date.now())throw R_();w.item={...w.item,status:"pending",error:void 0},v()}},async remove(y){let w=r.get(y);if(!w)return;w.removed=!0,w.generation++,r.delete(y);let x=w.upload?.attachment_id??w.item.attachment?.attachment_id;x&&w.abort?.abort(),m(),v(),x&&g(w,x)},abort:b,submit(y){if(!a){for(let w of y){let x=r.get(w);x&&(x.handedOff=!0)}m()}},reclaim(y){if(!a){for(let w of y){let x=r.get(w);x&&(x.handedOff=!1)}m()}},whenReady:O,forget(y=d().map(w=>w.item.id)){for(let w of y){let x=r.get(w);x&&(x.generation++,x.abort?.abort(),r.delete(w))}m(),v()},dispose(){if(!a){a=!0,l&&clearTimeout(l);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let w=y.upload?.attachment_id??y.item.attachment?.attachment_id;w&&e&&un(e,w).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(y){return s.add(y),()=>{s.delete(y)}}}}function T_(e){return{attachments:{upload:(...t)=>Mr(e,...t),delete:(...t)=>un(e,...t),createController:t=>C_(e,t)},get:t=>Tt(e,t),detail:()=>br(e),skills:{remove:(...t)=>Vc(e,...t),create:(...t)=>Hc(e,...t)},audit:t=>_f(e,t),update:t=>xr(e,t),archive:()=>wr(e),llmCatalog:()=>Sr(e),modelPicker:()=>Pr(e),modelAccess:()=>Xr(e),setModelAccess:t=>Zr(e,t),customLlmProviders:()=>es(e),setCustomLlmProvider:(t,n)=>ts(e,t,n),deleteCustomLlmProvider:t=>ns(e,t),sandboxHealth:()=>Rr(e),onboardingComplete:(...t)=>Wc(e,...t)}}function I_(e){return{sessions:{list:t=>Dt(e,t),listPage:t=>$p(e,t),create:t=>Lt(e,t),ensureWarm:()=>zp(e),claimWarm:t=>Yp(e,t)},review:{list:t=>Mm(e,t),summary:()=>Om(e),get:t=>jm(e,t),submit:t=>Dm(e,t),act:(...t)=>Lm(e,...t),bulkAct:t=>$m(e,t)},approvals:{list:t=>kl(e,t),resolve:(...t)=>Al(e,...t),sessionsNeedingInput:t=>vl(e,t)}}}function E_(e){return{files:{write:t=>Yu(e,t),list:t=>qu(e,t),listDirectory:t=>Gu(e,t),read:(t,n)=>Hu(e,t,n),search:(...t)=>Wu(e,...t),archive:(...t)=>Vu(e,...t),archiveRequest:(...t)=>zu(e,...t),history:(...t)=>ip(e,...t)},git:{commits:()=>rp(e),commit:t=>sp(e,t),commitDiff:t=>op(e,t),branches:()=>np(e),versionDiff:(...t)=>ap(e,...t),inviteCollaborator:(...t)=>Lc(e,...t)},changeRequests:{list:(...t)=>cp(e,...t),get:t=>lp(e,t),update:(...t)=>_p(e,...t),diff:t=>up(e,t),mergePreview:t=>pp(e,t),open:(...t)=>dp(e,...t),merge:(...t)=>gp(e,...t),close:(...t)=>mp(e,...t),reopen:(...t)=>fp(e,...t),requestChanges:(...t)=>yp(e,...t)},...I_(e)}}function M_(e){return{policies:{list:()=>Mu(e),set:(...t)=>Ou(e,...t)},reminders:{list:()=>zr(e),updateMany:(...t)=>Vm(e,...t),removeMany:(...t)=>zm(e,...t)},rooms:{list:(...t)=>Ym(e,...t),create:(...t)=>Jm(e,...t),get:(...t)=>Qm(e,...t),update:(...t)=>Xm(e,...t),messages:(...t)=>Zm(e,...t),post:(...t)=>ef(e,...t),markRead:(...t)=>tf(e,...t),addSession:(...t)=>nf(e,...t),removeSession:(...t)=>rf(e,...t),addPerson:(...t)=>sf(e,...t),removePerson:(...t)=>of(e,...t),people:(...t)=>af(e,...t)},triggers:{list:()=>hd(e),eventApps:()=>Cd(e),eventTypes:(...t)=>Rd(e,...t),create:(...t)=>_d(e,...t),update:(...t)=>bd(e,...t),remove:(...t)=>Sd(e,...t),fire:((t,n)=>wd(e,t,n)),runs:(...t)=>kd(e,...t),projectRuns:(...t)=>vd(e,...t),replay:(...t)=>Ad(e,...t),setActivation:(...t)=>Pd(e,...t)},...E_(e)}}function O_(e,t){return{connectors:{...Rs(e),list:()=>cu(e),config:(...n)=>fu(e,...n),create:(...n)=>_u(e,...n),remove:(...n)=>xu(e,...n),sync:()=>lu(e),auth:{discover:(...n)=>bu(e,...n)},setName:(...n)=>yu(e,...n),setCredentialMode:(...n)=>uu(e,...n),setAuthorizationStrategy:(...n)=>pu(e,...n),setCredential:(...n)=>Ru(e,...n),deleteCredential:(...n)=>Cu(e,...n),setSensitive:(...n)=>du(e,...n),connections:t,policies:{get:(...n)=>gu(e,...n),set:(...n)=>mu(e,...n)},listMoves:()=>Su(e),move:(...n)=>Pu(e,...n),pipedream:{listApps:(...n)=>wu(e,...n),listSections:(...n)=>ku(e,...n),connect:(...n)=>hu(e,...n),finalize:(...n)=>Tu(e,...n)},discover:{list:(...n)=>xo(e,...n),sections:(...n)=>vu(e,...n),detail:(...n)=>wo(e,...n)}},...M_(e)}}function j_(e){return{gateway:{logs:t=>Fg(e,t),log:t=>Ng(e,t),overview:t=>Bg(e,t),series:t=>Kg(e,t),breakdown:t=>qg(e,t),sessions:t=>Gg(e,t),errors:t=>Wg(e,t),budgets:()=>Hg(e),setBudget:t=>Vg(e,t),deleteBudget:t=>zg(e,t),keys:()=>Yg(e),createKey:t=>Jg(e,t),revokeKey:t=>Qg(e,t),routing:{get:()=>Dg(e),set:t=>Lg(e,t),reset:()=>$g(e),preview:t=>Ug(e,t)},playground:(t,n,r)=>Xg(e,t,n,r)}}}function D_(e){return{modelDefaults:{get:()=>$d(e),set:t=>Ud(e,t),clear:t=>Fd(e,t)},setDefaultAgent:t=>Kd(e,t),sandbox:{list:()=>Ku(e),snapshots:()=>Du(e),rebuildSnapshot:t=>Lu(e,t),fixWithAgent:()=>$u(e),createTemplate:t=>Uu(e,t),updateTemplate:(...t)=>Fu(e,...t),removeTemplate:t=>Nu(e,t),buildTemplate:t=>Bu(e,t),setProvider:t=>Gc(e,t)},setAgentScope:(...t)=>Bd(e,...t)}}function L_(e){return{channels:{slack:{installation:()=>Sg(e),connect:t=>Pg(e,t),mode:()=>xg(e),completeInstall:t=>kg(e,t),manifest:()=>Ag(e),disconnect:()=>Rg(e),getFile:t=>Cg(e,t),uploadFile:t=>Tg(e,t)},teams:{completeInstall:t=>vg(e,t)},email:{installation:t=>Ig(e,t),mode:()=>Eg(e),connect:t=>Mg(e,t),disconnect:t=>Og(e,t),updatePolicy:(...t)=>jg(e,...t)}},updateFeatureFlag:(...t)=>Kc(e,...t),updateExperimentalFeature:(...t)=>qc(e,...t),...D_(e)}}var eW=["screen","actions","audio"],tW=["password_managers","messaging","banking"],nW={localHours:8760,remoteDays:3650},rW=[500,1e3,2e3,5e3,1e4],sW=[720,1080,1440,2160],oW={intervalMs:2e3,maxHeight:1440},eR=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function iW(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(/\.$/,""),eR.test(n)?n:null}function aW(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 pW(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var J=e=>`/accounts/${e}/capture`;function ze(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 $_=e=>ze({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}),Gi=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function U_(e,t={}){return u(await c.get(`${J(e)}/devices${ze({user_id:t.userId,scope:t.scope})}`))}async function F_(e,t){return u(await c.delete(`${J(e)}/devices/${t}`))}async function N_(e,t,n){return u(await c.put(`${J(e)}/devices/${t}/link`,{user_id:n}))}async function B_(e){return u(await c.get(`${J(e)}/enrollment-tokens`))}async function K_(e,t){return u(await c.post(`${J(e)}/enrollment-tokens`,t))}async function q_(e,t){return u(await c.delete(`${J(e)}/enrollment-tokens/${t}`))}async function G_(e,t={}){return u(await c.get(`${J(e)}/enrollments${ze({status:t.status})}`))}async function W_(e,t,n){return u(await c.post(`${J(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function H_(e,t){return u(await c.post(`${J(e)}/enrollments/${t}/deny`,{}))}async function V_(e){return u(await c.get(`${J(e)}/policy`))}async function z_(e,t){return u(await c.put(`${J(e)}/policy`,{policy:t}))}async function Y_(e){return u(await c.get(`${J(e)}/storage`))}async function J_(e,t){return u(await c.put(`${J(e)}/storage`,t))}async function Q_(e,t={}){return u(await c.get(`${J(e)}/timeline${ze(Gi(t))}`))}async function X_(e,t={}){return u(await c.get(`${J(e)}/timeline/items${ze(Gi(t))}`))}async function Z_(e,t={}){return u(await c.get(`${J(e)}/days${ze({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function eb(e,t){return u(await c.get(`${J(e)}/search${$_(t)}`))}async function tb(e,t,n={}){return u(await c.get(`${J(e)}/frames/${t}${ze({user_id:n.userId,device_id:n.deviceId})}`))}async function nb(e,t,n={}){return u(await c.get(`${J(e)}/chunks/${t}/media${ze({user_id:n.userId,device_id:n.deviceId})}`))}async function rb(e,t,n){return u(await c.get(`${J(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function sb(e){return u(await c.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function ob(e,t){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function ib(e){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function ab(e){return u(await c.get(J(e)))}async function cb(e,t){return u(await c.patch(J(e),{enabled:t}))}async function lb(e){return u(await c.get(`/capture/me/search${$_(e)}`))}async function ub(e={}){return u(await c.get(`/capture/me/timeline${ze(Gi(e))}`))}async function pb(e){return u(await c.get(`/capture/me/frames/${e}`))}function nR(e){return{workspace:{get:()=>ab(e),setEnabled:t=>cb(e,t)},devices:{list:t=>U_(e,t),revoke:t=>F_(e,t),link:(t,n)=>N_(e,t,n),assetUrl:(t,n)=>rb(e,t,n)},enrollment:{tokens:{list:()=>B_(e),create:t=>K_(e,t),revoke:t=>q_(e,t)},list:t=>G_(e,t),approve:(t,n)=>W_(e,t,n),deny:t=>H_(e,t)},policy:{get:()=>V_(e),set:t=>z_(e,t)},storage:{get:()=>Y_(e),set:t=>J_(e,t)},timeline:{get:t=>Q_(e,t),items:t=>X_(e,t),days:t=>Z_(e,t)},search:t=>eb(e,t),frame:(t,n)=>tb(e,t,n),media:(t,n)=>nb(e,t,n)}}var db={account:e=>nR(e),deviceGrant:sb,approveDevice:ob,denyDevice:ib,me:{search:lb,timeline:ub,frame:pb}};async function gb(e){let t=e?.fetch??I().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??I().backendUrl,r=await t(`${Ne(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new S(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var rR=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function hW(e,t){let n=o=>{let i=rR.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 sR(){return _t()}var mb=null,fb=!1;function oR(e){let t=mb;mb=e,!(fb||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(fb=!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 iR(e,t){t?.global!==!1&&oR(e),to(e,t);let n=ah(e),{auth:r,accounts:s,iam:o,accountInvites:i}=nh(),{billing:a,sandboxShares:l}=Zy(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=Xy();function h(P){let v=v_(P);return{...T_(P),...x_(P),...k_(P),...O_(P,v),...j_(P),...L_(P),connector:T=>Ki(P,T),session:T=>Bi(P,T,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:Rs(),connector:P=>Ki(void 0,P),project:h,session:(P,v)=>Bi(P,v,e,n),github:d,gitBackend:g,billing:a,sandboxShares:l,connectStatus:m,marketplace:f,capture:db,notifications:{registerDeviceToken:hy,unregisterDeviceToken:_y,releaseDeviceToken:by,list:Sy,markRead:Py,preferences:xy,updatePreferences:wy,webPushPublicKey:ky,registerWebPushSubscription:vy,unregisterWebPushSubscription:Ay},mobileClientPolicy:gb,validateToken:Oc,runtime:sR}}function aR(){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 cR(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Vt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function lR(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function uR(e){if(Vt(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 pR(e){let t=Vt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function dR(e,t){let n=Vt(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 gR(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 mR(e,t){return Vt(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 fR(e,t,n){return Vt(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 yR(e,t,n){let r=Vt(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 yb={thinking:!1,toolDetails:!0,assistantMetadata:!0};function hR(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function _R(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 bR(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
22
22
|
|
|
23
23
|
`;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
|
|
24
24
|
>
|
|
@@ -51,15 +51,15 @@ ${s}
|
|
|
51
51
|
${e.state.error}
|
|
52
52
|
\`\`\`
|
|
53
53
|
`),n+=`
|
|
54
|
-
`,n}return""}function
|
|
54
|
+
`,n}return""}function SR(e,t){if(!t)return`## Assistant
|
|
55
55
|
|
|
56
|
-
`;let n=e.agent?
|
|
56
|
+
`;let n=e.agent?hR(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=_R(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
|
|
57
57
|
|
|
58
58
|
`:`## ${n}
|
|
59
59
|
|
|
60
|
-
`}function
|
|
60
|
+
`}function PR(e,t,n){let r="";e.role==="user"?r+=`## User
|
|
61
61
|
|
|
62
|
-
`:r+=
|
|
62
|
+
`:r+=SR(e,n.assistantMetadata);for(let s of t)r+=bR(s,n);return r}function xR(e,t,n=yb){let r=`# ${e.title||"Untitled Session"}
|
|
63
63
|
|
|
64
64
|
`;r+=`**Session ID:** \`${e.id}\`
|
|
65
65
|
`,r+=`**Created:** ${new Date(e.time.created).toLocaleString()}
|
|
@@ -67,32 +67,32 @@ ${e.state.error}
|
|
|
67
67
|
|
|
68
68
|
`,r+=`---
|
|
69
69
|
|
|
70
|
-
`;for(let s of t)r+=
|
|
70
|
+
`;for(let s of t)r+=PR(s.info,s.parts,n),r+=`---
|
|
71
71
|
|
|
72
|
-
`;return r}function
|
|
72
|
+
`;return r}function wR(e,t){return`session-${e}.md`}var Wi="An error occurred";var kR=["message","error","detail","error_description","msg","errors","data"];function Hi(e){let t=e.trim();for(let n=0;n<4;n++){let r=t.replace(/^(?:\d{3}\s+)?(?:[A-Za-z_$][\w$]*)?Error:\s*/,"").trim();if(r===t)break;t=r}return t}function zt(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function vR(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=zt(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function AR(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=RR(e,t);if(n)return n;let r=TR(e,t);return r?r.slice(0,200):void 0}function Sb(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function hb(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function RR(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!Sb(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 CR=["script","style"];function TR(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=CR.find(i=>t.startsWith(`<${i}`,s)&&Sb(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:hb(e,i);continue}r=hb(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function IR(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 ER(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function _b(e,t,n){if(typeof e=="string")return Cs(e,t,n);if(e&&typeof e=="object")return Ts(e,t,n)}function Cs(e,t,n=new WeakSet){let r=Hi(e);if(!r)return;if(t>=4)return r;let s=IR(r);if(s)return s;let o=zt(r);if(o!==void 0)return typeof o=="string"?Cs(o,t+1,n):o&&typeof o=="object"?Ts(o,t+1,n):String(o);let i=Pb(r);if(i){let a=zt(i);if(a&&typeof a=="object"){let l=Ts(a,t+1,n);if(l)return l}}if(r.includes("{")){let a=vR(r);if(a)return Cs(a,t+1,n)??a}return AR(r)??r}function Ts(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=_b(i,t,n);if(a)return a}return}let r=e;for(let i of kR){let a=_b(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return ER(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function _e(e){return e?typeof e=="string"?Cs(e,0)??Wi:typeof e=="object"?Ts(e,0)??Wi:String(e):Wi}function Is(e){let t=MR(e)?.trim();if(!t)return;let n=_e(e);if(!(t===n||Hi(t)===n))return t}function MR(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:s}=n,o=[r,s].filter((i,a,l)=>typeof i=="string"&&i.trim()!==""&&l.indexOf(i)===a);if(o.length>0)return o.join(`
|
|
73
73
|
|
|
74
|
-
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function
|
|
75
|
-
`||e==="\r"||e==="\u2028"||e==="\u2029"}function
|
|
74
|
+
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function Pb(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function OR(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 jR(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 bb(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=jR(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||OR(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:i,...a?{requestedModel:a}:{},...l?{resolvedModel:l}:{}}}function xe(e){if(e==null)return;if(typeof e=="string"){let a=Hi(e),l=zt(a)??zt(Pb(a));return l!==void 0?xe(l):void 0}if(typeof e!="object")return;let t=e,n=bb(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=bb(s);if(a)return a}let o=t.data;if(o&&typeof o.responseBody=="string"){let a=zt(o.responseBody);if(a!==void 0){let l=xe(a);if(l)return l}}if(o&&typeof o.message=="string"){let a=xe(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=xe(a);if(l)return l}}return n}var xb={};function V(e,t){for(let n of t)xb[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 DR=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ce(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=xb[t];if(n)return n;for(let[r,s]of DR)if(t.startsWith(r))return s;return"other"}function Ie(e){for(let t of[e?.filePath,e?.file_path,e?.path,e?.notebook_path])if(typeof t=="string"&&t)return t}var LR=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function $R(){return new RegExp(`(^|\\s)([-+]?)(${LR.join("|")}):("[^"]*"|\\S+)`,"gi")}function UR(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function FR(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function NR(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function BR(e){return NR(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function wb(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Es(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace($R(),(s,o,i,a,l)=>{if(!i&&a.toLowerCase()==="site"){let p=BR(l);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(UR(),"$1").replace(FR(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${wb(n)}`:r:n.length>0?wb(n):t}var KR=/\s/,qR=/\w/;function fe(e){return e!==void 0&&KR.test(e)}function Fn(e){return e===`
|
|
75
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function Vi(e){return e!==void 0&&qR.test(e)}function Pt(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(GR(n.charCodeAt(0))):n;return t}function GR(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 Ye(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function kb(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Ye(e.slice(t))}function Nn(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 zi(e,t){let n=Nn(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 Vi(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 wb(e,t){let n=Vi(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function vb(e,t){let n=Vi(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 kb(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=Vi(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 Ab(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 Es(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&&fe(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function Rb(e,t,n){let r=St(t),s=St(n);for(let o of St(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 Cb(e,t){let n=St(e),r=t.map(St),s=e.length,o=l=>{let p=l;for(;p<s&&fe(e[p]);)p++;return p},i=l=>{for(let p=l;p<s;p++)if(Fn(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&&!Fn(e[m]);)m++;for(;m>g+1&&fe(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!Fn(e[m]))return e[m];return null}}a=i(l)}return null}function Tb(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=fe(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"||!fe(e[a-1]))continue;let l=a+1;if(fe(e[l])){for(;l<t&&fe(e[l]);)l++;Wi(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]+(Fn(e[a])?1:0);let o=(a,l)=>s[l]===s[a],i=a=>{let l=a+1;for(;fe(e[l]);)l++;let p=l;for(;p<t&&Wi(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&&fe(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(!Fn(e[g]))return{id:e.slice(a+2,l),title:e[g],status:i(d)}}}}return null}function zi(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&fe(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&fe(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!Wi(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&fe(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function Ib(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 Eb(e){return Ib(e,!0)}function Mb(e){return Ib(e,!1)}function qR(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Ob(e,t){let n=St(e),r=St(t),s=e.length,o=i=>{let a=i;for(;a<s&&fe(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(!fe(e[p])){p++;continue}let d=o(p);if(qR(e,d))return e.slice(l,p);p=d}return e.slice(l)}return null}var GR=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function qW(e){return GR.has(ce(e))}function GW(e){let t=0,n=0,r=0;for(let s of e){let o=ce(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function Yi(e){if(!e)return"";let t=Ye(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ms(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Ji(e){let t=Ke(e),r=(t.state??{}).input??{};switch(ee(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=Ie(r);return i?Yi(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?`"${Ms(String(i),40)}" in ${Yi(String(a))}`:i?`"${Ms(String(i),60)}"`:""}case"list":return r.path?Yi(String(r.path)):"";case"bash":return Ms(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 Ms(i==="query"&&Is(a)||a,60)}return""}var WR={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 WW(e,t={}){let n=me(e)?se(e):e,r={...WR,...t},s=ee(n.tool),o=Ji(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 Je(e){return e.type==="text"}function we(e){return e.type==="reasoning"}function te(e){return e.type==="tool"}function Db(e){return e.type==="file"}function QW(e){return e.type==="agent"}function XW(e){return e.type==="compaction"}function ZW(e){return e.type==="snapshot"}function eH(e){return e.type==="patch"}function tH(e){return e.type==="step-start"||e.type==="step-finish"}function nH(e){if(Je(e)||we(e))return e.text}function rH(e){if(!Db(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function sH(e){let t=[],n=[];for(let r of e)Db(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function oH(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function iH(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var HR=new Set(["todoread","context_info"]);function Kn(e){return!HR.has(me(e)?e.name:e.tool)}var VR=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 Os(e){let t=me(e)?se(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=ce(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 zR(n,t.state)}function zR(e,t){let n=ee(e);if(VR.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 aH(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return _e(n.error)}}function cH(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)te(r)&&Kn(r)&&t.push(r);return t}var YR={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=>ZR(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 lH(e,t={}){let n=YR[ee(e)];if(!n)return JR(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function JR(e,t){switch(ce(e)){case"read":return{icon:"glasses",title:"Read",subtitle:QR(Ie(t))};case"list":return{icon:"list",title:"List",subtitle:XR(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:jb(Ie(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:jb(Ie(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function QR(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function jb(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 XR(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function uH(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 Bn(e,t=120){if(typeof e!="string")return"";let n=e.split(`
|
|
78
|
-
`).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function
|
|
77
|
+
`)&&(n=n.slice(0,-1)),n)}function Yi(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 vb(e,t){let n=Yi(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function Ab(e,t){let n=Yi(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 Rb(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=Yi(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 Cb(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 Ms(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&&fe(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function Tb(e,t,n){let r=Pt(t),s=Pt(n);for(let o of Pt(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 Ib(e,t){let n=Pt(e),r=t.map(Pt),s=e.length,o=l=>{let p=l;for(;p<s&&fe(e[p]);)p++;return p},i=l=>{for(let p=l;p<s;p++)if(Fn(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&&!Fn(e[m]);)m++;for(;m>g+1&&fe(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!Fn(e[m]))return e[m];return null}}a=i(l)}return null}function Eb(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=fe(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"||!fe(e[a-1]))continue;let l=a+1;if(fe(e[l])){for(;l<t&&fe(e[l]);)l++;Vi(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]+(Fn(e[a])?1:0);let o=(a,l)=>s[l]===s[a],i=a=>{let l=a+1;for(;fe(e[l]);)l++;let p=l;for(;p<t&&Vi(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&&fe(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(!Fn(e[g]))return{id:e.slice(a+2,l),title:e[g],status:i(d)}}}}return null}function Ji(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&fe(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&fe(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!Vi(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&fe(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function Mb(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 Ob(e){return Mb(e,!0)}function jb(e){return Mb(e,!1)}function WR(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Db(e,t){let n=Pt(e),r=Pt(t),s=e.length,o=i=>{let a=i;for(;a<s&&fe(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(!fe(e[p])){p++;continue}let d=o(p);if(WR(e,d))return e.slice(l,p);p=d}return e.slice(l)}return null}var HR=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function YW(e){return HR.has(ce(e))}function JW(e){let t=0,n=0,r=0;for(let s of e){let o=ce(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function Qi(e){if(!e)return"";let t=Ye(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Os(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Xi(e){let t=Ke(e),r=(t.state??{}).input??{};switch(ee(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=Ie(r);return i?Qi(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?`"${Os(String(i),40)}" in ${Qi(String(a))}`:i?`"${Os(String(i),60)}"`:""}case"list":return r.path?Qi(String(r.path)):"";case"bash":return Os(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 Os(i==="query"&&Es(a)||a,60)}return""}var VR={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 QW(e,t={}){let n=me(e)?se(e):e,r={...VR,...t},s=ee(n.tool),o=Xi(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 Je(e){return e.type==="text"}function we(e){return e.type==="reasoning"}function te(e){return e.type==="tool"}function $b(e){return e.type==="file"}function rH(e){return e.type==="agent"}function sH(e){return e.type==="compaction"}function oH(e){return e.type==="snapshot"}function iH(e){return e.type==="patch"}function aH(e){return e.type==="step-start"||e.type==="step-finish"}function cH(e){if(Je(e)||we(e))return e.text}function lH(e){if(!$b(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function uH(e){let t=[],n=[];for(let r of e)$b(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function pH(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function dH(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var zR=new Set(["todoread","context_info"]);function Kn(e){return!zR.has(me(e)?e.name:e.tool)}var YR=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 js(e){let t=me(e)?se(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=ce(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 JR(n,t.state)}function JR(e,t){let n=ee(e);if(YR.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 gH(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return _e(n.error)}}function mH(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)te(r)&&Kn(r)&&t.push(r);return t}var QR={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=>tC(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 fH(e,t={}){let n=QR[ee(e)];if(!n)return XR(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function XR(e,t){switch(ce(e)){case"read":return{icon:"glasses",title:"Read",subtitle:ZR(Ie(t))};case"list":return{icon:"list",title:"List",subtitle:eC(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:Lb(Ie(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Lb(Ie(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function ZR(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Lb(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 eC(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function yH(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 Bn(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 tC(e){let t=Bn(e.description);if(t)return t;let n=Bn(e.title,80);if(n)return n;let r=Bn(e.message);if(r)return r;let s=Bn(e.prompt);if(s)return s;let o=Bn(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function hH(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function _H(e,t){return e.find(n=>n.tool?.callID===t)}function bH(e,t){return e.find(n=>n.tool?.callID===t)}var nC=/\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 Ub(e){return e?e.replace(nC,""):""}function Ds(e){let t=Fb(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let s=r&&typeof r=="object"?Fb(r):void 0;return s?[s]:[]})}function Fb(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 rC={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"},sC={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 oC(e){return e.replace(/^oc[-_]/,"")}function Nb(e){return oC(e).replace(/-/g,"_")}function Bb(e){return Nb(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Zi(e){return{label:rC[Nb(e)]??Bb(e),category:sC[ce(e)]}}var iC=256*1024;function aC(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function cC(e){if(e===void 0)return{};if(e.length>iC)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function lC(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,s=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!s))return s?_e(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var de=e=>typeof e=="string"?e:void 0,Ls=e=>typeof e=="number"?e:void 0,$s=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function ea(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var uC=new Set(["add","update","delete","move"]);function pC(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=$s(d),m=g&&(de(g.relativePath)||de(g.filePath));if(!g||!m)return[];let f=de(g.type);return[ea({path:m,type:f&&uC.has(f)?f:void 0,before:de(g.before),after:de(g.after),patch:de(g.patch)??de(g.diff),additions:Ls(g.additions),deletions:Ls(g.deletions),movePath:de(g.movePath)})]});return p.length?p:void 0}let r=Ie(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[ea({path:r,after:de(t.content)})];if(e!=="edit")return;let s=$s(n.filediff),o=s?void 0:de(n.patch),i=o?dC(o):void 0,a=s||o?[]:Ds(t);return[ea({path:r,before:de(s?.before)??(a.length?a.map(([l])=>l).join(`
|
|
79
79
|
`):void 0),after:de(s?.after)??(a.length?a.map(([,l])=>l).join(`
|
|
80
|
-
`):de(t.new_source)),patch:o,additions:
|
|
81
|
-
`))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function
|
|
82
|
-
|
|
83
|
-
`)}function YH(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function JH(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 QH(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=Eb(n),n=Mb(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 XH(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=Es(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 Wn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function sa(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(Wn(i[1]),Wn(i[2]),i[3]?Wn(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(Wn(i[2]),Wn(i[1])),n.length>=t)return n}return n}function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xb(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 Us(e){return e.filter(t=>it(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 Zb(e){if(!e)return[];let t=Xb(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(it(s)&&typeof s.query=="string"){let o=[];for(let i of r)!it(i)||typeof i.query!="string"||o.push({query:i.query,answer:i.answer||void 0,sources:Array.isArray(i.results)?Us(i.results):[],...i.success===!1?{error:typeof i.error=="string"&&i.error.trim()||"Search failed"}:{}});if(o.length>0)return o}else if(it(s)&&(s.title||s.url)){let o=Us(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?Us(r):[]}];if(Array.isArray(t)&&t.length>0){let s=t[0];if(it(s)&&(s.title||s.url)){let o=Us(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=sa(e);if(s.length>0)return[{query:"",sources:s.map(o=>({title:o.title,url:o.url,snippet:o.snippet}))}]}return[]}function oa(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function nV(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return oa(e)}}function rV(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function sV(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 LC(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 $C(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=Ob(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function oV(e,t){let n=UC(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?$C(r,LC(t)):[]}function UC(e){if(!e)return null;let t=Xb(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=>it(s)&&s.success!==!1).length,failed:n.failed??r.filter(s=>it(s)&&s.success===!1).length,results:r.map(s=>{let o=it(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=sa(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 FC(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 NC={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 Vn(e){return NC[ce(e)]}function Fs(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 BC={run:"Terminal",memory:"Memory"};function dV(e){let t=Vn(e);return(t==="hidden"?void 0:BC[t])??Fs(e)}function Hn(e,t,n){return e===1?t:n}function ia(e){return e.length===0?"":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function nS(e){return e.length?Ji(e[0]):""}function Ee(e){return(e.state??{}).input??{}}var KC={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 qC(e){let t=ee(e.tool);if(t==="agent_task_update"||t==="task_update")switch(Ee(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return KC[t]??"message"}function eS(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 GC(e){let t=ee(e.tool);if(t==="triggers"){let r=Ee(e).action||"list";return eS(r)}let n=t.match(/^trigger_(.+)$/);return eS(n?n[1]:"list")}var WC={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 HC(e){return WC[ee(e.tool)]??"read"}var VC={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function zC(e){return VC[ee(e.tool)]??"open"}function zt(e){return e.every(t=>t===e[0])}var YC={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function JC(e){if(ee(e.tool)!=="memory")return"read";let n=Ee(e).command;return n&&YC[n]||"unknown"}var QC={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},XC={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 ZC(e){let t=Ye(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function eT(e){let t=Ee(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 tT(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return ZC(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=FC(o);return i?oa(i):"a link"}return""}function tT(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function nT(e){let t=Ee(e).action;return t&&QC[t]||"Worked on an image"}function rT(e){let t=Ee(e).action;return t&&XC[t]||"Worked on a presentation"}function sT(e){return e.slice(0,e.indexOf(":"))}var oT={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},iT={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 aT(e){let t=ee(e.tool);if(t==="image_gen"){let n=Ee(e).action;return n&&oT[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=Ee(e).action;return n&&iT[n]||"presentation:unknown"}return"shown:result"}var cT=new Set(["create_slide","export_pdf","export_pptx"]);function gV(e){let t=Ke(e),n=ee(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=Ee(t).action;return r?cT.has(r)?"presentation":null:"presentation"}return null}var lT={"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`},tS={image:"image",video:"video",presentation:"presentation",shown:"result"};function uT(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[sT(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Hn(s,tS[r],`${tS[r]}s`)}`)}),`Worked on ${ia(n)}`}function Ns(e,t){let n=t.map(Ke),r=n.length,s=nS(n);switch(e){case"explore":{let o=n.filter(i=>ee(i.tool)==="read").length;return o===r?`Read ${r} ${Hn(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=>Ie(Ee(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} ${Hn(r,"query","queries")}`;if(i===0)return`Read ${r} ${Hn(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of Zb(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} ${Hn(l,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return nT(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return rT(i);let l=eT(i);return l?`Showed you ${l}`:"Showed you the result"}let o=n.map(aT);return zt(o)?lT[o[0]](r):uT(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(qC);if(zt(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(JC);if(zt(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(HC);if(zt(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(GC);if(zt(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(zC);if(zt(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 ${Fs(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>Fs(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${ia(o)}`}}}function rS(e,t){let n=t.map(Ke),r=nS(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let s=ee(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${s} ${r}`:`Couldn't ${s} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let s=n.filter(a=>a.state?.status==="error"),o=s.length?s:n,i=Array.from(new Set(o.map(a=>Fs(a.tool))));return`Couldn't finish using ${ia(i)}`}}}var pT=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),dT={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 gT(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Is(t)||t}function mT(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 gT(r,s.trim())}}function zn(e){let t=me(e)?se(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=he(t.tool),r=dT[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:mT(s,r.objectKeys),tier:pT.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function ca(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(zn(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)&&ra(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function aa(e){return`${e} ${e===1?"step":"steps"}`}function fT(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${aa(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${aa(n)}`:s===0?`${aa(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function sS(e){let t=new Map,n=0;for(let s of e){if(!te(s)||zn(s).tier==="plumbing")continue;let o=Vn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),ra(s)!=="ok"&&(n+=1))}if(t.size===0)return fT(ca(e),!1);let r=[...t].map(([s,o],i)=>{let a=Ns(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function kV(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 yT(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function hT(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 oS(e,t){let n=t.map(Ke),r=yT(n);return{id:n[0].callID,family:e,label:r==="error"?rS(e,n):Ns(e,n),parts:t,status:r,durationMs:r==="running"?void 0:hT(n)}}function iS(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(oS(n,r)),n=null,r=[]};for(let o of e){let i=Ke(o),a=Vn(i.tool);if(a!=="hidden"&&!ri(i)){if(qy(i.tool)){s(),t.push(oS(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function la(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function aS(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 iS(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=la(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 _T=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function bT(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 OV(e){let t=e.flatMap(s=>{let o=bT(s);return o?[o]:[]}).join(" ").trim();return t?_T.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function ST(e){return e?.info?.time??{}}function DV(e){let t=ST(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Bs=6e4,PT=10080*Bs,cS=1440;function lS(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function xT(e,t){let n=t.getTime()-e.getTime(),r=n/Bs,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<cS)return s(Math.round(r/60),"hour");let o=(n-(lS(t)-lS(e)))/Bs;return s(Math.round(o/cS),"day")}function dS(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 uS=new Map;function wT(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=uS.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),uS.set(r,s)),s}function Ks(e,t,n){return wT(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?vT(r.value,n):r.value).join("")}function vT(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function pS(e,t){return Ks(e,{year:"numeric"},t)}function LV(e,t,n={}){let r=dS(e);if(!r)return"";let s=i=>Ks(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<Bs?"just now":o<PT?xT(r,new Date(t)):s(pS(r,n)!==pS(new Date(t),n))}function $V(e,t={}){let n=dS(e);if(!n)return"";let r=Ks(n,{month:"long",day:"numeric",year:"numeric"},t),s=Ks(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function gS(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!Gy(o)){if(Je(o)){s(),n.push({kind:"text",part:o});continue}if(te(o)&&(Wy(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function kT(e){let t=he(e);return t==="show"||t==="show_user"}function fS(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"&&kT(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var AT=["title","description","path","url","content","language","aspect_ratio","attachment"];function mS(e,t){if(!t||typeof t!="object")return null;let n=t;if(ns(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of AT){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function RT(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 yS(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=RT(s.items),i=o?o.map(a=>mS(n.callID,a)).filter(a=>!!a):[mS(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 hS(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Yn=e=>"id"in e?e.id:e.userMessage.info.id,_S=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,CT=e=>e.time?.completed;function VV(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function TT(e,t){let n=Yn(e);return t.pendingTurnIds.has(n)||_S(e)===0&&t.pendingPromptIds.has(n)}function zV(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Yn(r)));if(t)return Yn(t);let n=e.turns.findIndex(r=>TT(r,e));return n<=0?null:Yn(e.turns[n-1])}function YV(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function JV(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 QV(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:hS({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function XV(e,t){for(let n=e.length-1;n>=0;n--){let r=Yn(e[n]);if(t(r))return _S(e[n])===0?r:null}return null}function bS(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(!CT(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 nz(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 rz(e,t){return!t||!e?!1:e.type!=="idle"}function sz(e,t){return!e&&!!t}function oz(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)?.message||_e(n.error)}}function iz(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Ts(n.error)}}function az(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)}}function SS(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(Je(e))return"Gathering thoughts..."}}var IT=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function ET(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=SS(n.parts[r]);if(s)return s}}}function MT(e,t){let n=te(e)?e:void 0;if(n&&IT.has(n.tool)&&n.state.status==="running"){let r=ET(t);return r||(t?.length?"Handing off to an agent...":void 0)}return SS(e)}function PS(e,t){for(let n=e.length-1;n>=0;n--){let r=MT(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function xS(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 wS=1.055;function vS(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 ua(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function kS(e,t,n,r){if(ua(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?vS(e.tokens,o):0}function AS(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function pa(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}=AS(d.info);n+=kS(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=RS(g,t),f=g.tokens&&ua(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*wS,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function RS(e,t){if(ua(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?vS({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function cz(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=AS(s),a=0,l=!1;for(let p of r.parts)p.type==="step-finish"&&(l=!0,a+=kS(p,o,i,t));l||(a+=RS(s,t)),n+=a}return n*wS}function lz(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function uz(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function pz(e){if(!e||e.type!=="retry")return;let t=e,n=_e(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:xe(t.message)}}function dz(e){if(!(!e||e.type!=="retry"))return _e(e.message)}function gz(e){return(e.info.summary?.diffs?.length??0)>0}function CS(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=he(e.part.tool);return t==="show"||t==="show_user"}function OT(e){return e.kind==="text"&&!e.part.text?.trim()}function TS(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(CS(o)||OT(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):CS(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function hz(e){let t=e==null?"":xS(e);return t?`Worked for ${t}`:"Worked"}function jT(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>Je(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 Sz(e){if(jT(e))return e.assistantMessages[0].parts[0]}function wz(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=kb(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 vz(e){return e?e.split(`
|
|
84
|
-
`).filter(n=>n.trim()).length<=3:!1}function
|
|
85
|
-
`).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function
|
|
86
|
-
`).filter(r=>r.trim());for(let r of n){let s=
|
|
87
|
-
`),r=n===-1?e:e.slice(0,n),s=n===-1?"":e.slice(n+1);if(
|
|
80
|
+
`):de(t.new_source)),patch:o,additions:Ls(s?.additions)??i?.additions,deletions:Ls(s?.deletions)??i?.deletions})]}function dC(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 gC(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function Kb(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=cC(r),i=aC(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=lC(s);m&&(i="error",a=m)}let l=ce(e),p=t.input??{},d="metadata"in t&&$s(t.metadata)||{},g=$s(d.diagnostics);return{name:e,kind:l,title:n||Zi(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:pC(l,p,d),diff:de(d.patch)??de(d.diff),diagnostics:g,answers:l==="question"?gC(d):void 0,childSessionId:js({tool:e,state:t})}}function qb(e){let t=me(e)?se(e):e;return Kb(t.tool,t.state)}function mC(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function fC(e){return{kind:"reasoning",id:e.id,text:e.text}}function yC(e){return{kind:"tool",id:e.id,tool:Kb(e.tool,e.state)}}function hC(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 _C(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function bC(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function SC(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function PC(e){return{kind:"agent",id:e.id,name:e.name}}function xC(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:_e(e.error),createdAt:e.time.created}}function wC(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function kC(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function vC(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Gb(e){switch(e.type){case"text":return mC(e);case"reasoning":return fC(e);case"tool":return yC(e);case"file":return hC(e);case"subtask":return _C(e);case"patch":return bC(e);case"snapshot":return SC(e);case"agent":return PC(e);case"retry":return xC(e);case"compaction":return wC(e);case"step-start":return kC(e);case"step-finish":return vC(e);default:return{kind:"unknown",raw:e}}}function AC(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=xe(e);return{name:t,message:n?.message||_e(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function RC(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function ta(e){let t=e.parts.map(Gb),n=e.info.role==="assistant"?e.info.error:void 0,r=AC(n),s=!r&&!t.some(RC);return{parts:t,error:r,isEmpty:s}}var na=st+BigInt(1),Wb=na/BigInt(2);function Us(e){return BigInt(Math.trunc(e))*xn}function ra(e,t){let r=t-(t&st)+e;return r-t>Wb?r-=na:t-r>Wb&&(r+=na),r}function Hb(e,t){let n=qt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return ra(n,t);let s=Us(r),o=ra(n,s);return(o>s?o-s:s-o)<=ht?o:s}function Vb(e){return qt(e)===null?1:0}function zb(e,t){return e<t?-1:e>t?1:0}function DH(e,t){return sa(e,t,Us(Date.now()))}function Yb(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 Us(t??Date.now())}function sa(e,t,n){let r=Vb(e.info.id),s=Vb(t.info.id);if(r!==s)return r-s;if(r===0){let a=Hb(e,n),l=Hb(t,n);return a!==l?a<l?-1:1:zb(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:zb(e.info.id,t.info.id)}function LH(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 $H(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 CC(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(...CC(e,s));return r}function BH(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=Yb(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:sa(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:IC(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 qn=new Map,TC=256;function IC(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=qn.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(qn.size>=TC){let a=qn.keys().next().value;a!==void 0&&qn.delete(a)}return qn.set(s,i),i}function KH(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function qH(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(Je(n)&&n.text?.trim())return n}}function GH(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function WH(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 EC(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function Jb(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&&EC(n.error)}return!1}function Gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xb(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 JH(e){return!!e&&(Xb(e)||Zb(e)!==null)}function oa(e){let t=me(e)?se(e):e,n=Qb.get(t);if(n&&n.state===t.state)return n.outcome;let r=MC(t);return Qb.set(t,{state:t.state,outcome:r}),r}var Qb=new WeakMap;function MC(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(Xb(n))return"failed";let r=OC(n);return r===void 0?"ok":jC(r)?"failed":DC(r)}function OC(e){try{return JSON.parse(e)}catch{return}}function jC(e){return Gn(e)&&e.success===!1&&typeof e.error=="string"}function DC(e){let t=Gn(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 Zb(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Gn(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=LC.exec(Ji(r.errorSummary));s&&(r.status=Number(s[1]));let o=Ms(r.errorSummary);if(o===null)return r;try{let i=JSON.parse(o),a=$C(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 LC=/^([1-5]\d{2}) Error\b/;function $C(e){let{message:t,error:n,detail:r}=e,s=[t,Gn(n)?n.message:void 0,Gn(r)?r.error:void 0,r];for(let o of s)if(typeof o=="string"&&o.trim())return o.trim()}function QH(e){return Ji(e).replace(/\s+/g," ").trim()||e.trim()}function XH(e){let t=Zb(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 tV(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function nV(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 rV(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=Ob(n),n=jb(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 sV(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=Ms(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 Wn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function ia(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(Wn(i[1]),Wn(i[2]),i[3]?Wn(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(Wn(i[2]),Wn(i[1])),n.length>=t)return n}return n}function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eS(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 Fs(e){return e.filter(t=>it(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 tS(e){if(!e)return[];let t=eS(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(it(s)&&typeof s.query=="string"){let o=[];for(let i of r)!it(i)||typeof i.query!="string"||o.push({query:i.query,answer:i.answer||void 0,sources:Array.isArray(i.results)?Fs(i.results):[],...i.success===!1?{error:typeof i.error=="string"&&i.error.trim()||"Search failed"}:{}});if(o.length>0)return o}else if(it(s)&&(s.title||s.url)){let o=Fs(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?Fs(r):[]}];if(Array.isArray(t)&&t.length>0){let s=t[0];if(it(s)&&(s.title||s.url)){let o=Fs(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=ia(e);if(s.length>0)return[{query:"",sources:s.map(o=>({title:o.title,url:o.url,snippet:o.snippet}))}]}return[]}function aa(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function cV(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return aa(e)}}function lV(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function uV(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 UC(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 FC(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=Db(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function pV(e,t){let n=NC(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?FC(r,UC(t)):[]}function NC(e){if(!e)return null;let t=eS(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=>it(s)&&s.success!==!1).length,failed:n.failed??r.filter(s=>it(s)&&s.success===!1).length,results:r.map(s=>{let o=it(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=ia(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 BC(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 KC={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 Vn(e){return KC[ce(e)]}function Ns(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 qC={run:"Terminal",memory:"Memory"};function _V(e){let t=Vn(e);return(t==="hidden"?void 0:qC[t])??Ns(e)}function Hn(e,t,n){return e===1?t:n}function ca(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 sS(e){return e.length?Xi(e[0]):""}function Ee(e){return(e.state??{}).input??{}}var GC={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 WC(e){let t=ee(e.tool);if(t==="agent_task_update"||t==="task_update")switch(Ee(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return GC[t]??"message"}function nS(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 HC(e){let t=ee(e.tool);if(t==="triggers"){let r=Ee(e).action||"list";return nS(r)}let n=t.match(/^trigger_(.+)$/);return nS(n?n[1]:"list")}var VC={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 zC(e){return VC[ee(e.tool)]??"read"}var YC={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function JC(e){return YC[ee(e.tool)]??"open"}function Yt(e){return e.every(t=>t===e[0])}var QC={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function XC(e){if(ee(e.tool)!=="memory")return"read";let n=Ee(e).command;return n&&QC[n]||"unknown"}var ZC={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},eT={create_slide:"Added a slide to a presentation",list_slides:"Checked a presentation's slides",list_presentations:"Checked your presentations",delete_slide:"Deleted a slide from a presentation",delete_presentation:"Deleted a presentation",validate_slide:"Checked a slide",export_pdf:"Exported a presentation to PDF",export_pptx:"Exported a presentation to PPTX",preview:"Previewed a presentation",serve:"Previewed a presentation"};function tT(e){let t=Ye(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function nT(e){let t=Ee(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 rT(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return tT(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=BC(o);return i?aa(i):"a link"}return""}function rT(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function sT(e){let t=Ee(e).action;return t&&ZC[t]||"Worked on an image"}function oT(e){let t=Ee(e).action;return t&&eT[t]||"Worked on a presentation"}function iT(e){return e.slice(0,e.indexOf(":"))}var aT={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},cT={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 lT(e){let t=ee(e.tool);if(t==="image_gen"){let n=Ee(e).action;return n&&aT[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=Ee(e).action;return n&&cT[n]||"presentation:unknown"}return"shown:result"}var uT=new Set(["create_slide","export_pdf","export_pptx"]);function bV(e){let t=Ke(e),n=ee(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=Ee(t).action;return r?uT.has(r)?"presentation":null:"presentation"}return null}var pT={"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`},rS={image:"image",video:"video",presentation:"presentation",shown:"result"};function dT(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[iT(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Hn(s,rS[r],`${rS[r]}s`)}`)}),`Worked on ${ca(n)}`}function Bs(e,t){let n=t.map(Ke),r=n.length,s=sS(n);switch(e){case"explore":{let o=n.filter(i=>ee(i.tool)==="read").length;return o===r?`Read ${r} ${Hn(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=>Ie(Ee(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} ${Hn(r,"query","queries")}`;if(i===0)return`Read ${r} ${Hn(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of tS(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} ${Hn(l,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return sT(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return oT(i);let l=nT(i);return l?`Showed you ${l}`:"Showed you the result"}let o=n.map(lT);return Yt(o)?pT[o[0]](r):dT(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(WC);if(Yt(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(XC);if(Yt(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(zC);if(Yt(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(HC);if(Yt(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(JC);if(Yt(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 ${Ns(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>Ns(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${ca(o)}`}}}function oS(e,t){let n=t.map(Ke),r=sS(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=>Ns(a.tool))));return`Couldn't finish using ${ca(i)}`}}}var gT=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),mT={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 fT(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Es(t)||t}function yT(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 fT(r,s.trim())}}function zn(e){let t=me(e)?se(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=he(t.tool),r=mT[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:yT(s,r.objectKeys),tier:gT.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function ua(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(zn(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)&&oa(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function la(e){return`${e} ${e===1?"step":"steps"}`}function hT(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${la(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${la(n)}`:s===0?`${la(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function iS(e){let t=new Map,n=0;for(let s of e){if(!te(s)||zn(s).tier==="plumbing")continue;let o=Vn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),oa(s)!=="ok"&&(n+=1))}if(t.size===0)return hT(ua(e),!1);let r=[...t].map(([s,o],i)=>{let a=Bs(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function EV(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 _T(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function bT(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let 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 aS(e,t){let n=t.map(Ke),r=_T(n);return{id:n[0].callID,family:e,label:r==="error"?oS(e,n):Bs(e,n),parts:t,status:r,durationMs:r==="running"?void 0:bT(n)}}function cS(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(aS(n,r)),n=null,r=[]};for(let o of e){let i=Ke(o),a=Vn(i.tool);if(a!=="hidden"&&!oi(i)){if(Wy(i.tool)){s(),t.push(aS(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function pa(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function lS(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 cS(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=pa(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 ST=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function PT(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 FV(e){let t=e.flatMap(s=>{let o=PT(s);return o?[o]:[]}).join(" ").trim();return t?ST.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function xT(e){return e?.info?.time??{}}function BV(e){let t=xT(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Ks=6e4,wT=10080*Ks,uS=1440;function pS(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 kT(e,t){let n=t.getTime()-e.getTime(),r=n/Ks,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<uS)return s(Math.round(r/60),"hour");let o=(n-(pS(t)-pS(e)))/Ks;return s(Math.round(o/uS),"day")}function mS(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 dS=new Map;function vT(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=dS.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),dS.set(r,s)),s}function qs(e,t,n){return vT(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?AT(r.value,n):r.value).join("")}function AT(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function gS(e,t){return qs(e,{year:"numeric"},t)}function KV(e,t,n={}){let r=mS(e);if(!r)return"";let s=i=>qs(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<Ks?"just now":o<wT?kT(r,new Date(t)):s(gS(r,n)!==gS(new Date(t),n))}function qV(e,t={}){let n=mS(e);if(!n)return"";let r=qs(n,{month:"long",day:"numeric",year:"numeric"},t),s=qs(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function fS(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!Hy(o)){if(Je(o)){s(),n.push({kind:"text",part:o});continue}if(te(o)&&(Vy(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function RT(e){let t=he(e);return t==="show"||t==="show_user"}function hS(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"&&RT(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var CT=["title","description","path","url","content","language","aspect_ratio","attachment"];function yS(e,t){if(!t||typeof t!="object")return null;let n=t;if(rs(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of CT){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function TT(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 _S(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=TT(s.items),i=o?o.map(a=>yS(n.callID,a)).filter(a=>!!a):[yS(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 bS(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Yn=e=>"id"in e?e.id:e.userMessage.info.id,SS=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,IT=e=>e.time?.completed;function ZV(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function ET(e,t){let n=Yn(e);return t.pendingTurnIds.has(n)||SS(e)===0&&t.pendingPromptIds.has(n)}function ez(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Yn(r)));if(t)return Yn(t);let n=e.turns.findIndex(r=>ET(r,e));return n<=0?null:Yn(e.turns[n-1])}function tz(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function nz(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 rz(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:bS({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function sz(e,t){for(let n=e.length-1;n>=0;n--){let r=Yn(e[n]);if(t(r))return SS(e[n])===0?r:null}return null}function PS(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(!IT(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 cz(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 lz(e,t){return!t||!e?!1:e.type!=="idle"}function uz(e,t){return!e&&!!t}function pz(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)?.message||_e(n.error)}}function dz(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Is(n.error)}}function gz(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)}}function xS(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(Je(e))return"Gathering thoughts..."}}var MT=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function OT(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=xS(n.parts[r]);if(s)return s}}}function jT(e,t){let n=te(e)?e:void 0;if(n&&MT.has(n.tool)&&n.state.status==="running"){let r=OT(t);return r||(t?.length?"Handing off to an agent...":void 0)}return xS(e)}function wS(e,t){for(let n=e.length-1;n>=0;n--){let r=jT(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function kS(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 vS=1.055;function AS(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 da(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function RS(e,t,n,r){if(da(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?AS(e.tokens,o):0}function CS(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function ga(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}=CS(d.info);n+=RS(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=TS(g,t),f=g.tokens&&da(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*vS,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function TS(e,t){if(da(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?AS({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function mz(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=CS(s),a=0,l=!1;for(let p of r.parts)p.type==="step-finish"&&(l=!0,a+=RS(p,o,i,t));l||(a+=TS(s,t)),n+=a}return n*vS}function fz(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function yz(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function hz(e){if(!e||e.type!=="retry")return;let t=e,n=_e(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:xe(t.message)}}function _z(e){if(!(!e||e.type!=="retry"))return _e(e.message)}function bz(e){return(e.info.summary?.diffs?.length??0)>0}function IS(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=he(e.part.tool);return t==="show"||t==="show_user"}function DT(e){return e.kind==="text"&&!e.part.text?.trim()}function ES(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(IS(o)||DT(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):IS(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function wz(e){let t=e==null?"":kS(e);return t?`Worked for ${t}`:"Worked"}function LT(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>Je(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 Az(e){if(LT(e))return e.assistantMessages[0].parts[0]}function Tz(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=Rb(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 Iz(e){return e?e.split(`
|
|
84
|
+
`).filter(n=>n.trim()).length<=3:!1}function Ez(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 Mz(e){if(!e)return[];let t=[],n=e.split(`
|
|
86
|
+
`).filter(r=>r.trim());for(let r of n){let s=Eb(r);if(s){let o=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...s,sessionId:o?.[0]})}}return t}var xt={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 jz(e,t){let n=xt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function Dz(e,t){return t?"failed":e?"running":"done"}var Uz={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function Fz(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function Nz(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(Tb(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
|
|
88
88
|
`).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
|
|
89
89
|
`)};if(/files and directories/i.test(r)){let o=t.replace(/\/$/,""),i=[];for(let a of s.split(`
|
|
90
|
-
`)){if(!a.trim())continue;let l=a.indexOf(" ");if(l===-1)continue;let p=a.slice(0,l).trim(),d=a.slice(l+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var
|
|
90
|
+
`)){if(!a.trim())continue;let l=a.indexOf(" ");if(l===-1)continue;let p=a.slice(0,l).trim(),d=a.slice(l+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var $T={add:{...xt.write,icon:"create"},delete:{...xt.delete,icon:"delete"},move:{...xt.rename,icon:"edit"},update:{...xt.edit,icon:"edit"}},MS={...xt.change,icon:"edit"};function qz(e){if(e.length===0)return MS;let t=OS(e[0]);for(let n=1;n<e.length;n++)if(OS(e[n])!==t)return MS;return $T[t]}function OS(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function Wz(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 jS(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 Yz(e){if(!e)return null;let t=Nn(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=zi(e,"content");if(r!==null){let o=r.split(`
|
|
91
91
|
`).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
|
|
92
|
-
`);return{path:n,type:"file",content:o}}let s=
|
|
93
|
-
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function
|
|
94
|
-
\u2026`:e}function
|
|
92
|
+
`);return{path:n,type:"file",content:o}}let s=zi(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 Xz(e){let t=Ab(e,"skill_content");return t!==null?t.trim():e}function UT(e){let t=Nn(e,"<skill_files>","</skill_files>");return t===null?[]:Cb(t,"<file>","</file>").map(n=>n.trim())}function FT(e){let t=vb(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 NT(e){return Ib(e,["Base directory","Directory","Skill directory"])?.trim()??""}function BT(e){return Ye(FT(e)||NT(e))}function Zz(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Ye(n.trim())}return""}var KT="skills";function qT(e){let t=kb(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?`${KT}/${r}`:""}function eY(e,t,n){let s=Ye(t?.trim()??"")||BT(e)||qT(n),o=UT(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 GT=4e3;function Jn(e,t=GT){return e.length>t?`${e.slice(0,t)}
|
|
94
|
+
\u2026`:e}function DS(e){if(e!==void 0)try{return Jn(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 Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function WT(e){let t=ne(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=Jt(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=Jt(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 HT=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function $S(e){let t=e.match(HT);return t?Number(t[1]):void 0}function VT(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 zT=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function YT(e){let t=-1;for(let n of zT){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}function JT(e){let t=ne(e.input?.command)??"",n=e.output??"",r=$S(n),o=Ub(YT(VT(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 fa(e){return ne(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function QT(e){let t=e.status==="error"?e.error:e.output&&Jn(e.output)||void 0;return{kind:"file-read",path:fa(e),preview:t}}function XT(e){let t=ne(e.input?.content),n=e.status==="error"?e.error:Jn(t??e.output??"")||void 0;return{kind:"file-write",path:fa(e),preview:n}}var ZT=256*1024;function eI(e,t){if(e.length+t.length>ZT)return;let n=e.split(`
|
|
95
95
|
`),r=t.split(`
|
|
96
|
-
`),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let l=0;l<s;l++)a.push({type:"unchanged",text:n[l]});for(let l=s;l<o;l++)a.push({type:"removed",text:n[l]});for(let l=s;l<i;l++)a.push({type:"added",text:r[l]});for(let l=o;l<n.length;l++)a.push({type:"unchanged",text:n[l]});return a}function
|
|
97
|
-
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function rI(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=LS.test(e.output.trim())?tI(e.output):nI(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function sI(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 da(e){let t=Yt(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function oI(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(da)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(da)};let n=Yt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(da)}:{kind:"todo",items:[]}}function iI(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=Yt(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let l=Yt(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 aI(e){let n=e.input&&Object.keys(e.input).length>0?OS(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Jn(e.outputParsed):OS(e.outputParsed):e.outputText!==void 0?r=Jn(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function cI(e){switch(ce(e.name)){case"web_search":return qT(e);case"bash":return zT(e);case"read":return YT(e);case"write":return JT(e);case"edit":return ZT(e);case"grep":case"glob":return rI(e);case"task":return sI(e);case"todowrite":return oI(e);case"question":return iI(e);default:return aI(e)}}var lI=new Set(["AbortError","MessageAbortedError"]),uI=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],pI=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function $S(e){let t=e.toLowerCase();return pI.some(n=>t.includes(n))?!1:uI.some(n=>t.includes(n))}function dI(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 qs(e){if(typeof e=="string")return $S(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&lI.has(n))return!0;let r=dI(t);return typeof r=="string"?$S(r):!1}var gI=["user","runtime-disposed","orphan-finalized","wake"],eY=["orphan-finalized","wake"];function tY(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 gI.includes(n)?n:void 0}var Gs="kortix-active-instance",mI=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function fI(e){return mI.some(t=>e===t||e.startsWith(`${t}/`))}function Qn(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 rY(e){let t=Qn(e);return!!t&&t.innerPath===""}function sY(e){let t=Qn(e);return!t||!t.innerPath?e:t.innerPath}function yI(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=Qn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return fI(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function hI(e){return e?Qn(e)?.instanceId??null:null}function oY(){return typeof window>"u"?null:hI(window.location.pathname)||_I()}function _I(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Gs}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function iY(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Gs}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Gs}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Gs}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function aY(e,t){return t?yI(t,e):e}function cY(e){let t=Qn(e);return t?t.innerPath||"/dashboard":e}function Xn(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 US(e){let t=Xn(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 uY=US;function ma(e){let t=US(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var pY=ma;function bI(e){return ma(e)!==null}var dY=bI,SI=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],gY=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],PI=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function xI(e){return PI.test(Xn(e))}function Zn(e){let t=Xn(e);return t?xI(t)||SI.some(n=>n.test(t)):!1}var wI=/server url not ready|sandbox is still loading/i;function mY(e){return wI.test(Xn(e))||Zn(e)}var Ws=class extends Error{constructor(t){let n=t?.trim();super(n&&Zn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function vI(e){let t=ma(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=Xn(e);return Zn(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 fY=vI;function FS(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`${nt()}/p/${e.external_id}/${tt.KORTIX_MASTER}`}function bY(e,t){return e.external_id?`${nt()}/p/${e.external_id}/${t}`:null}async function vY(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function kI(e){let t=await mn();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Rt())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await Dt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await mt(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Yr(r,s,o),created:!0}}async function kY(){return(await mn().catch(()=>null))?.sandbox??null}async function AY(e){return{sandbox:(await kI(e)).sandbox}}async function RY(e){let t=gn(e);if(!t)return null;try{let n=await Yo(t);return n?Yr(await Ct(n.project_id),n,null):(await mn(t))?.sandbox??null}catch{return null}}async function CY(e,t){throw await Jr(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function TY(e){let t=gn(e);return(await zo().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function IY(){return null}async function EY(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Jr(e);if(!t)throw new Error("Project session sandbox not found");await Ur(t.projectId,t.sessionId)}async function MY(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Jr(e);if(!t)throw new Error("Project session sandbox not found");await Fr(t.projectId,t.sessionId)}async function OY(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function jY(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function fa(e,t,n){let r=FS(e),s=await U(`${pe(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 FY(e,t){return fa(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function NY(e,t,n,r="member"){await fa(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function BY(e,t,n){await fa(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var ya="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function GY(e){throw N("getInvite",ya)}async function WY(e){throw N("acceptInvite",ya)}async function HY(e){throw N("declineInvite",ya)}async function zY(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function YY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function JY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function QY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function ZY(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function e2(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var AI=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function s2(e){return AI.includes(e)}async function o2(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 i2(e){let t=e?`?channel=${e}`:"",r=await(await Oe(`${nt()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await RI(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function RI(e){let t=e?`?channel=${e}`:"";return(await(await Oe(`${nt()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function a2(){return(await Oe(`${nt()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function c2(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function l2(e){}async function u2(e){}async function g2(e){return{serverTypes:[],location:e||"hel1"}}async function m2(e){throw new Error("Retired instance provisioning is unavailable. Create a project session on platinum (or the legacy daytona fallback).")}async function f2(e){throw N("deleteInstance")}async function y2(e,t){}async function h2(){throw N("claimComputer")}async function _2(e){return null}function b2(e,t){throw N("getSandboxProvisionStreamUrl")}var Hs=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function NS(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 BS(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function KS(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 X(e,t,n){let r=n?.body!==void 0,s=await fetch(`${Ne(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:NS(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 BS(s);if(!s.ok)throw new Hs(KS(s,o),s.status,o);return o}function CI(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 v2(e,t){return X(`/marketplace/items${CI(t)}`,e)}function k2(e){return X("/marketplace/marketplaces",e)}function A2(e,t){return X(`/marketplace/items/${encodeURIComponent(e)}`,t)}function R2(e,t,n){return X(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function C2(e,t){return X("/access/check-email",t,{method:"POST",body:{email:e}})}function T2(e,t){return X("/access/request-access",t,{method:"POST",body:e})}function I2(e){return X("/auth/logout",e,{method:"POST",body:{}})}function E2(e,t){return X(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function M2(e,t){return X("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function O2(e,t){return X(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function j2(e,t){return X(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function D2(e,t,n={}){return X(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function L2(e,t){return X(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function $2(e,t,n,r){return X(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function U2(e,t){return X(`/p/public-share/${encodeURIComponent(e)}`,t)}function F2(e,t,n){return X(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function N2(e){return X("/system/maintenance",e)}function B2(e,t){return X("/system/maintenance",t,{method:"PUT",body:e})}function K2(e){return X("/user-roles",e)}function q2(e,t){return X("/system/demo-request",t,{method:"POST",body:e})}async function G2(e,t,n){let r=await fetch(`${Ne(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${$t(t)}`,{headers:NS(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await BS(r);throw new Hs(KS(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 W2(e,t){throw N("openStressTestStream")}function H2(e,t){throw N("buildPublicTemplateUrl")}async function V2(e,t,n){throw N("getPublicTemplate")}var TI="kortix:connect-link:";function ha(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`${TI}${t.toString(36)}${n.toString(36)}`}function Y2(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(ha(i));if(!a)return;let l=JSON.parse(a);if(Date.parse(l.expires_at)<=Date.now()){t.removeItem(ha(i));return}return l}catch{return}},o=(i,a)=>{if(t)try{t.setItem(ha(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 qS="Could not start the connect flow.";async function J2(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:qS}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:qS};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var II=3e3,EI=5e3,MI=5*6e4;function Q2(e,t){let n=e===0?II:EI;return t+n>MI?null:n}function X2(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 tJ(){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 nJ(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 rJ(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 sJ(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 oJ(){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 aJ="1";var OI="kortix.query-cache";function WS(e){return!!e&&typeof e.then=="function"}function GS(e){return WS(e)?e:Promise.resolve()}function cJ(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 lJ(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:l=OI,now:p=()=>Date.now()}=e,d=`${l}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),P=()=>{try{return GS(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),_=(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},b=async x=>{let v=_(T(x),i);for(;;){let C={v:s,user:n,at:p(),queries:v};try{await GS(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(()=>b(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 WS(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 uJ(){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 jI="/kortix/part/";function DI(e){return typeof e=="string"&&e.startsWith(jI)}async function mJ(e){if(!DI(e))throw new Error(`not an attachment part reference: ${e}`);let t=Ge();if(!t)throw new Error("runtime url not bound");let n=await U(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function HS(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 LI(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 VS(e,t){return LI(e,t)?(t?HS(t):null)??HS(e):null}function Vs(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 yJ(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var $I=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function UI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function FI(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(UI).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function NI(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function zS(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function BI(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:$I.test(n.hostname)?t.backendUrls.some(r=>{let s=NI(r);return s!==null&&zS(s)===zS(n)}):t.templates.some(r=>FI(n.origin,r))}async function YS(e,t={}){if(!Vs(e))return!1;let n=I().backendUrl;n&&await ft(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return BI(e,{templates:nh(),backendUrls:r})}async function KI(e,t={}){let n=VS(e,t.serverUrl||I().backendUrl||void 0);if(!n)return!1;let r=await sn();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 RJ(e,t={}){if(Vs(e)){if(!await YS(e,t)||!await sn())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 KI(e,t),e}var TJ=3e3;function qI(e){return!Number.isFinite(e)||e<100||e>599?"unknown":e===502||e===503||e===504?"unreachable":e===401||e===403?"unknown":"reachable"}async function IJ(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return qI(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function GI(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function OJ(e,t){throw N("buildPresentationTemplatePdfUrl")}function jJ(e,t){throw N("buildPresentationTemplateImageUrl")}function WI(e,t){return`${GI(e)}/presentation/convert-to-${t}`}async function DJ(e,t,n,r){let s=WI(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 UJ(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 FJ(e){return e==="unreachable"}function NJ(e){return!e||e.status===0?"unknown":e.ok&&c_(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var HI=1e4,BJ={connection:"unknown",faultSinceMs:null};function KJ(e,t,n,r=HI){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 JS({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<_a,l=!!t&&i-t.atMs<Pa;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<=ba,streamFresh:!!s&&i-s.atMs<=er,inboxFresh:!!n&&i-n.atMs<=Sa,activityFresh:!!o&&i-o.atMs<=er}}function Jt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function xa(e,t,n){if(!t)return!1;let r=Jt(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=Jt(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function VI(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"&&!xa(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function zI(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,l=i?s.turns.filter(g=>!xa(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:Jt(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function YI(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 JI(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:Jt(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 QS(e){let t=JS(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=VI(e,t,s,o);if(i)return i;let{result:a,openTurn:l}=zI(e,t,s,o);return a??YI(e,t,o)??JI(e,t,l,o)}var _a=6e4,ba=45e3,er=45e3,Sa=1e4,ZJ=3e3,Pa=15e3;function eQ(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function tQ(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 rQ(e){return QS(e)}function sQ(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,l=[null,t?t.atMs+_a:null,n?n.atMs+Pa:null,r?r.atMs+Sa:null,s?s.atMs+ba:null,o?o.atMs+er:null,i?i.atMs+er:null],p=null;for(let d of l)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function QI(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||qs({name:s.name??void 0,message:s.message})?null:s}var XI="SandboxMemoryGuard";function cQ(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=QI(e,t);if(r?.message){if(r.name!==XI)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 uQ=6e4;function pQ(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function dQ(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var ZI=9e4;function gQ(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+ZI}var fQ=75e3,yQ=2,hQ=2e4;function XS(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function _Q(e){return e.filter(t=>t!=null).join("|")}function eE(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function bQ(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...XS(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...XS(),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=eE(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 tE={"retry-start":"retrying",restart:"restarting"};function SQ(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${tE[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function nE(e){return e===1?"once":e===2?"twice":`${e} times`}function PQ(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 ${nE(t)}`),`Tried: ${r.join(", then ")}.`}var wQ={"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 rE(e){return!!(e.metadata??{}).legacy_migration}function vQ(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 rE(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function kQ(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 AQ={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 RQ(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function wa(e){return e.runtime_sessions??e.opencode_sessions??[]}function sE(e){let t=wa(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 TQ(e){let t=sE(e);return t?wa(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 IQ(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=>wa(r).some(s=>s.id===t))??null)}var oE=new Set;function iE(e){for(let t of[...oE])try{t(e)}catch{}}var rP={schema:ue,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var sP=e=>Object.values(e.ext??{}).find(t=>t.version===Te),oP=e=>!!e&&sP(e)!==void 0,iP=e=>{let t=sP(e);return t?t.native_id??null:e.thread_id};function aP(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:iP(t),hasMessages:n,empty:!n&&e.older[t.thread_id]===!1}}var ZS=new WeakMap;function cP(e,t){let n=iP(e),r=ZS.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=cs({...rP,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return ZS.set(t,{native:n,rows:o}),o}var va=e=>e.info.time?.created;var aE=(e,t)=>(va(e)??-1/0)-(va(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var eP=new WeakMap,tP=new WeakMap,lP=e=>typeof e=="object"&&e!==null,cE=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,lE=e=>e.info.role==="user"&&e.parts.some(t=>lP(t)&&t.type==="compaction"),uE=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},nP=new WeakMap;function pE(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(!lP(p)||a.type==="compaction")return a;let d=`${s}|${l}|${a.id}`,g=nP.get(p);return g&&g.key===d?(o=!0,g.block):(nP.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function dE(e){let t=new Map,n=new Set;for(let r of e){if(!lE(r))continue;let s=e.find(o=>!n.has(o)&&uE(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function gE(e,t,n,r,s){let o=eP.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=ls({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=pE(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 eP.set(n,p),p}function mE(e,t,n){let r=tP.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(aE),{paired:o,used:i}=dE(s),a={tool_input:0,cut_point:0,attachment:0},l=[];for(let m of s){if(i.has(m))continue;let f=gE(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=cE(s.map(va).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=l.filter(m=>m.role==="user"&&m.kind==="turn"),g={...rP,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:ue,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:Te,native_id:t}}}]};return tP.set(n,{sessionId:e,native:t,log:g}),g}var ka=new WeakMap,Qt=new WeakMap,uP=new WeakMap;function zs(e){let t,n=Qt.get(e);return n&&(t=fE(n).get(e.id)),t?(ka.set(t,e),t):(e.type!=="harness"?t=ni(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=uP.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},uP.set(e,t)),t&&ka.set(t,e),t)}var tr=e=>ka.get(e),xt=e=>e.flatMap(t=>zs(t)??[]),pP=new WeakMap;function fE(e){let t=pP.get(e);return t||pP.set(e,t=new Map(at(e)[0]?.parts.map(n=>[n.id,n]))),t}var dP=new Map;function at(e){let t=dP.get(e.thread_id);return t||(t={schema:ue,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},dP.set(e.thread_id,t)),cP(t,e)}var yE="kortix-v1-import",Aa={schema:ue,v:1};function Ys(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var Ra=e=>e.type==="tool_call",hE=e=>e.status==="pending"||e.status==="running",Ca=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function _E(e,t){let n=Ca(e);return!hE(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var gP=new WeakMap;function bE(e,t){let n=gP.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={...Aa,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 gP.set(e,s),s}var mP=new WeakMap;function SE(e){let t=mP.get(e);return t||(t={...Aa,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:[]},mP.set(e,t)),t}var fP=new WeakMap;function PE(e){let t=fP.get(e);return t||(t={...Aa,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:[]},fP.set(e,t)),t}var xE=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function wE(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"||xE(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:PE(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:SE(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 vE(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 kE(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 _P(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=at(n)[0]?.info?.error??n.error.message,s=xe(r),o=Ts(r);return{code:n.error.code,message:s?.message||_e(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function AE(e,t,n){return e.length&&e.every(t)?pa(e.flatMap(r=>at(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:Ta(e,n)}function Ta(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 pa(n,t)??null}function RE(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 CE(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&&Ra(n)&&n.name==="bash"?n:null}function TE(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:Ra(i)?Os(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var IE=e=>e.assistant.some(t=>t.blocks.some(n=>Ra(n)&&ce(n.name)==="todowrite"&&Kn(n))),EE=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function ME(e,t){let n=e.map(s=>_P(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 yP=new WeakMap,OE=[];function bP(e){let t=Ys(e.messages,n=>n.role==="assistant");return!!t&&zb(at(t))}var hP=new WeakMap;function jE(e){let t=hP.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},hP.set(e,t)}return t}function Ia(e,t={}){let n=t.hideOutOfContext?jE(e):e,r=new Set(t.held??OE),s=wE(n.messages,r),o=kE(s,t.liveMessageId),{list:i,hint:a}=t.foldCompactions?vE(s,o):{list:s,hint:o},l=Ys(n.messages,_=>_.role==="assistant"),p=bP(n),d=bS({turns:i.map(_=>({userMessage:{info:{id:_.user.message_id}},assistantMessages:_.assistant.map(b=>({info:{time:b.status==="streaming"?{}:{completed:1},error:b.error??void 0}}))})),hintMessageId:a,unrunTurnIds:r}),g=Ys(i,IE)??i[i.length-1],m=i.map(_=>!_.partial&&EE(_.user)),f=ME(i,m),h=oP(n),P=_=>h||_.producer.harness===yE,k=t.threads??[],T=new Set(k.map(_=>_.thread_id));return i.map((_,b)=>{let O=t.busy===!0&&d.workingTurnId===_.user.message_id,y=d.pendingTurnIds.includes(_.user.message_id),w=p&&_.assistant.includes(l),x=f[b],v=`${_.partial}|${O}|${y}|${_===g}|${w}|${x?(x.continued?"c":"")+x.retries:"-"}`,C=yP.get(_.user);if(C&&C.key===v&&C.pricing===t.pricing&&C.heads===t.threads&&C.assistant.length===_.assistant.length&&C.assistant.every((j,q)=>j===_.assistant[q]))return C.turn;let D=_.assistant.flatMap(j=>j.blocks);for(let j of _.assistant)for(let q of j.blocks)Qt.set(q,j);let R=TE(_,D,k,T),L=_.assistant[_.assistant.length-1],le={internal:m[b],autoRetry:x,id:_.user.message_id,user:_.user,assistant:_.assistant,partial:_.partial,continues:_.continues??null,blocks:D,status:w?"streaming":L?L.status:_.user.kind==="compaction"?_.user.status:"pending",error:_P(_),cost:AE([_.user,..._.assistant],P,t.pricing),compaction:RE(_.user),threads:R,plan:_===g,shell:CE(_),response:Ys(D,j=>j.type==="text"&&!!j.text.trim())??null,attachments:_.user.blocks.filter(j=>j.type==="attachment"&&(j.mime.startsWith("image/")||j.mime==="application/pdf")),live:O,queued:y,retrying:w};return yP.set(_.user,{assistant:_.assistant,key:v,pricing:t.pricing,heads:t.threads,turn:le}),le})}var Ea=e=>tr(e);function DE(e,t={}){return fS(gS(xt(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(tr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Ea)}:n.kind==="text"?{kind:n.kind,block:tr(n.part)}:{kind:n.kind,block:Ea(n.part)})}var LE=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:xt(e.blocks)}:{kind:e.kind,part:zs(e.block)};function $E(e,t){let n=new Map(e.map(o=>[LE(o),o])),r=TS([...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 UE(e){if(!te(e)||!Ky(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=Bb(e);return(n.answers??MS(n.outputText??"",t.length)??[]).length>0}function FE(e){return aS(xt(e),n=>zn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(UE)?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:tr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Ea),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&&Qt.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function NE(e,t){return PS(xt(e.blocks).map(n=>({part:n})),t?.flatMap(at))}function BE(e){return ca(xt(e))}function KE(e){return sS(xt(e))}function qE(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=zs(n),s=Qt.get(n);return!!r&&we(r)&&la(r)&&(!s||s.status==="streaming")}):!1}var SP=new WeakMap;function GE(e){if(!Ca(e))return e;let t=SP.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},SP.set(e,t)}return t}function WE(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function HE(e){let t=e.map(se),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=yS(t).map(WE);return us({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function VE(e,t,n){let r=se(e),s=r.state;return us({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function zE(e){let t=at(e).map(r=>Zi(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 PP=Object.freeze([]),xP=new WeakMap;function YE(e){if(!e)return PP;let t=xP.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&Kn(s)):[]);t=n.length?n:PP,xP.set(e,t)}return t}function JE(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 Ia(e)){let s=Ta([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 QE="prt_kortix_restore_g";function XE(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(QE))}function ZE(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 Ma=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qe=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,eM=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function tM(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=Ma(t)?t.restore:void 0;if(!Ma(n))return null;let r=Ma(n.dropped)?n.dropped:{},s=e.grade_counts,o=[{kind:"message",count:Qe(r.message)},{kind:"attachment",count:Qe(s?.attachment)},{kind:"text",count:Qe(r.text)+Qe(n.truncated)},{kind:"tool_input",count:Qe(s?.tool_input)},{kind:"tool_result",count:Qe(r.tool_result)},{kind:"cut_point",count:Qe(s?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,l])=>eM.has(a)?i:i+Qe(l),0)}];return{generation:Qe(n.generation),missing:o.filter(i=>i.count>0)}}var vP=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function nM(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of vP(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 kP=(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}},rM=(e,t)=>e.map(n=>n.type==="text"?kP(n,t):n),wP=new WeakMap;function sM(e,t){let n=wP.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>vP(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?kP(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:rM(s.result.content,t)}}:s)}:e;return wP.set(e,{texts:t,out:r}),r}var Oa=1024*1024;function oM(e){return e.reduce((t,n)=>t+n.bytes,0)>Oa?"download":"inline"}function iM(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>Oa)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function aM(e,t){if(t.size===0)return e;let n=e.messages.map(r=>sM(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function cM(e){return e==="TIMEOUT"||e==="request_deadline"}function lM(e){let t=RP(e)?e.code:void 0;return typeof t=="string"?t:void 0}var RP=e=>typeof e=="object"&&e!==null;function AP(e){let t=e?.metadata;return!!RP(t)&&t.warm===!0}var uM=5,pM=2e3,dM=e=>new Promise(t=>setTimeout(t,e));async function gM(e,{attempts:t=uM,delayMs:n=pM,sleep:r=dM}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function BX(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 cM(lM(g))?gM(async()=>!AP(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(AP(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 mM=12e4,Js=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},fM=1e3,yM=15e3,CP=100,hM=50,_M=10;function TP(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 Ws(`session ${l.status}`):new S(`Session synchronization failed: ${l.status}`,{status:l.status});return{messages:await l.json(),nextCursor:l.headers.get("x-next-cursor")||void 0}}}function bM(e){return PM(TP(e))}function SM(e){return new ja({...e,loadPage:TP(e)})}async function PM(e){let t=[],n=new Set,r;do{let i=await e({limit:CP,...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 xM={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},ja=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??xM,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??mM,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 Js;if(!r&&qs(n))return;if(r||this.update({freshness:Zn(n)?"loading":"error"}),n instanceof S&&(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(fM*2**this.retryAttempt,yM);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"?hM:CP,...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 Js(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<_M&&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 wM=5e3,EP=40,VX=5*6e4,vM=16,nr=new Map;function MP(e,t,n,r=Date.now()){let s=OP(e,t);for(nr.delete(s),nr.set(s,{envelope:n,atMs:r});nr.size>vM;){let o=nr.keys().next().value;if(o===void 0)break;nr.delete(o)}}var IP=new Map;function OP(e,t){return`${e}/${t}`}function kM(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=wM}function jP(e,t,n=Date.now()){if(!e||!t)return null;let r=OP(e,t),s=IP.get(r);return s?kM(s,n)?s.promise:(IP.delete(r),null):null}function DP(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 AM=/(?:\n\n)?Command exited with code (-?\d+)\s*$/;function RM(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=AM.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 LP(e){let t=!1,n=e.blocks.map(r=>{if(r.type!=="tool_call")return r;let s=RM(r);return s!==r&&(t=!0),s});return t?{...e,blocks:n}:e}var $P=Object.freeze({generation:0,session:{},threads:{},messages:{},revs:{},older:{}});function CM(e,t){let n=LP(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 UP(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)!To(p)||e.revs[p.message_id]!==void 0||(r=CM(r,p));let a={...e.threads};for(let p of t.threads)Io(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 TM=2e3;async function IM(e,t,n){let r=jP(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??TM,null)})]).finally(()=>clearTimeout(s)):null;return(o&&DP(o))??Dr(e,t,{limit:EP,history:!0,signal:n.signal})}async function EM(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s=pn?await Op(pn,t,n):null;if(s==="missing")return{envelope:null,empty:!1,log:null};if(s){let i=aP(UP($P,s));return{envelope:null,empty:!!i?.empty&&i.runtimeSessionId===r&&await FP(t,n,r),log:s}}let o;try{o=await IM(t,n,{})}catch{return{envelope:null,empty:!1}}return MP(t,n,o),NP(o)!==r?{envelope:o,empty:!1}:{envelope:o,empty:await FP(t,n,r)}}async function FP(e,t,n){try{let r=await Lr(e,t);return BP({savedEmptyRoot:n,rootSessionId:n,turnRead:!0,hasEndedTurn:r.last_ended!=null,hasOpenOrQueuedTurn:r.turns.length>0})}catch{return!1}}function NP(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 BP(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function a4(e){throw N("buildTunnelEventStreamUrl")}function c4(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:l,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(b,O){o?.(b,O);let y=d.get(b);if(y)for(let w of y)try{w(O)}catch{}}async function P(){if(m)return;let b=new AbortController;g=b,p&&(p.aborted?b.abort():p.addEventListener("abort",()=>b.abort(),{once:!0}));let O=b.signal;try{let y={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(y["Content-Type"]="application/json"),f&&(y["Last-Event-ID"]=f);let w=await fetch(t,{method:r,headers:y,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:O,credentials:"include"});if(!w.ok)throw new Error(`SSE connection failed: ${w.status} ${w.statusText}`);if(!w.body)throw new Error("SSE response has no body");i?.();let x=w.body.getReader(),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)},le=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}),le(!1)}m||(C+=v.decode(),le(!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(b,O){let y=d.get(b)??new Set;y.add(O),d.set(b,y)}function _(b,O){d.get(b)?.delete(O)}return{connect:P,close:k,addEventListener:T,removeEventListener:_}}function l4(e,t){throw N("createTunnelEventStream")}var KP="/_kortix/viewer",Qs=6e4,Xt=new Map;function MM(){Xt.clear(),rr.clear()}async function OM(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 qP(e={}){let t=e.path??KP,n=e.fetch??((o,i)=>fetch(o,i)),r=Xt.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=OM(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-Qs:Date.now()+Qs;return Xt.set(t,{session:o,expiresAt:a}),o});return Xt.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function jM(e={}){let t=e.path??KP;return Object.assign(async()=>(await qP(e))?.access_token??null,{invalidate:n=>{let r=Xt.get(t);r&&!r.inflight&&r.session?.access_token===n&&Xt.delete(t)}})}var rr=new Map;async function DM(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 rr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-Qs:Date.now()+Qs}),r.token}catch{return null}}function GP(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=rr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=DM(n,r).then(a=>(a===null&&rr.delete(n),a));return rr.set(n,i),i}}function LM(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:`${pe(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:GP({audience:e,fetch:t.fetch})}}var wt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},be=e=>typeof e=="string"&&e.length>0?e:null;function WP(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 La(e){if(!e||typeof e!="object")return null;let t=e,n=be(t.sub)??be(t.subject)??be(t.user_id)??be(t.userId);return n?{userId:n,email:be(t.email),name:be(t.name),picture:be(t.picture)??be(t.pictureUrl),groups:WP(t.groups),groupIds:WP(t.group_ids??t.groupIds),role:be(t.role),accountId:be(t.account_id)??be(t.accountId),projectId:be(t.project_id)??be(t.projectId)}:null}function $M(e,t={}){let n=La(e);if(!n)throw new wt("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 wt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new wt("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var UM=60,Da=new Map;function VP(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 HP(e){return JSON.parse(new TextDecoder().decode(VP(e)))}async function FM(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=Da.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(()=>Da.delete(e)),Da.set(e,n)),n}return JSON.parse(e)}async function NM(e,t={}){let n=b=>{throw new wt("unauthenticated",`Kortix sign-in token refused: ${b}.`)},r=t.jwks??et("KORTIX_AUTH_JWKS"),s=t.issuer??et("KORTIX_AUTH_ISSUER"),o=t.audience??et("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=HP(a),g=HP(l)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await FM(r,t.fetch??((b,O)=>fetch(b,O)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(b=>b.kty==="EC"&&(d.kid===void 0||b.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${l}`),P;try{P=VP(p)}catch{return n("malformed")}let k=!1;for(let b of f)try{let{kid:O,alg:y,use:w,key_ops:x,...v}=b,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+UM<T)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let b=g.aud;if(!(b===o||Array.isArray(b)&&b.includes(o)))return n("wrong audience")}let _=La(g);return _||n("no subject")}function zP(e){let t=e.agents.map(BM),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 BM(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 YP(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>ci(n?{...r,mode:null}:r))}function KM(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=YP(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 qM=zP;function JP(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function $a(e){return{providerID:"kortix",modelID:e}}function sr(e,t){return $a(e.startsWith("kortix/")?e.slice(7):e)}var QP=[{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 Ua(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function WM(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function XP(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 or(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 ZP(e){return e.reduce((t,n)=>{let r=Ua(n)??0,s=Ua(t)??0;return r!==s?r>s?n:t:or(n.id)>or(t.id)?n:t})}function Fa(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of XP(e,WM)){let a=[...XP(o,p=>p.family||p.id).values()].map(ZP),l=a.filter(p=>{let d=Ua(p);return d!==null&&Math.abs(n-d)<r});for(let p of l.length>0?l:[ZP(a)])s.add(p.id)}return s}function Na(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=>or(r.id)>0)?n.filter(r=>or(r.id)>0):n}var ex={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:[]},tx=[...QP,{id:ex.id,env:ex.env}],HM={"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 nx(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var VM=(()=>{let e=new Map;for(let{id:n,env:r}of tx)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=>nx(o)===n)??s[0])}return t})();function rx(e){let t=HM[e.id];if(t)return t;let n=e.env??[],r=n.length===1?VM.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[nx(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}var zM=["low","medium","high"];function sx(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:[...zM]}: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 ox=tx;var R4=ox.map(e=>({id:e.id,authRequirement:rx(e)})),ix=new Set(["kortix"]);function YM(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=sx({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 JM(e){return e.modelPicker?YM(e.modelPicker):void 0}function QM(e){return"capabilities"in e&&e.capabilities!=null}function Ba(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1&&n.available!==!1}function XM(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)&&ix.has(o.id))for(let[i,a]of Object.entries(o.models)){if(i==="auto"||i==="kortix/auto")continue;let l;if(QM(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:JP({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 ax(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var lx="kortix",cx="codex";function ux(e){return e.providerID===lx&&!e.modelID.includes("/")}function ZM(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Zt(e){return ux(e)}function eO(e){return Fa(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function tO(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=eO(e.catalogModels),s=ax(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===lx){let d=ZM(i.modelID,i.provider),g=d===cx?t?.has(cx)??!1:t?.has(d)??!1;if(ux(i))return!n;if(!g)return!1;if(l==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return Zt(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Zt(i)}catch{return Zt(i)}return!1}if(l==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return Zt(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Zt(i)}catch{return Zt(i)}return!1}}function nO(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 rO(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?$a(r):void 0}function sO(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 oO=new Set(["explicit","repointed","fallback"]);function iO(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:sr(n),from:sr(r),reason:typeof o=="string"?o:"other",atMs:s}}function aO(e,t){return!t||(e??-1)>=t.atMs}function cO(e){let t=e.session?Nr(e.session):null,n=t?sr(t):void 0,r=e.session?.metadata;return(oO.has(String(r?.opencode_model_source))||r?.opencode_model_restored===!0?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(i=>!!i)}function lO(e){let{models:t,providers:n}=e,r=l=>Ba(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 Na(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}}export{gI as ABORT_REASONS,eY as ABORT_REASONS_NOT_YET_EMITTED,nc as ACCOUNTS_LIST_UNAVAILABLE_CODE,Gs as ACTIVE_INSTANCE_COOKIE,tc as ANALYTICS_UNAVAILABLE_CODE,jI as ATTACHMENT_PART_REF_PREFIX,S as ApiError,ie as AuthError,ut as BillingError,Z1 as CAPTURE_DEVICE_DEFAULTS,Y1 as CAPTURE_EXCLUSION_GROUPS,Q1 as CAPTURE_FRAME_INTERVALS_MS,z1 as CAPTURE_LAYERS,X1 as CAPTURE_MAX_HEIGHTS,J1 as CAPTURE_RETENTION_LIMITS,HI as CONNECTION_FAULT_GRACE_MS,II as CONNECTOR_POLL_FIRST_DELAY_MS,EI as CONNECTOR_POLL_INTERVAL_MS,MI as CONNECTOR_POLL_WINDOW_MS,GR as CONTEXT_TOOLS,wS as COST_MARKUP,wo as ConnectorApprovalPendingError,kr as ConnectorCallError,vo as ConnectorPageLimitError,WR as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,JN as DEFAULT_NOTIFICATION_PREFERENCES,mb as DEFAULT_TRANSCRIPT_OPTIONS,AI as DESTRUCTIVE_PHASES,en as FEATURE_DISABLED_CODE,ZO as FEATURE_FLAG_KEYS,Qa as FEATURE_NOT_SUPPORTED_CODE,Pt as FILE_VERBS,In as FileExistsError,hn as HeadlessAuthError,Hs as HostBoundaryError,Rx as IMPERSONATION_HEADER,YN as INBOX_NOTIFICATION_KINDS,Sa as INBOX_OBSERVATION_MAX_MS,BJ as INITIAL_SETTLED_CONNECTION,mI as INSTANCE_SCOPED_ROUTES,vw as KNOWN_TOOL_KINDS,Te as KORTIX_TRANSCRIPT_SCHEMA,wt as KortixMemberError,uw as MAX_PROMPT_ATTACHMENTS_BYTES,Ao as MAX_PROMPT_ATTACHMENT_BYTES,zu as MAX_PROMPT_ATTACHMENT_FILES,Mz as MEMORY_VERBS,Xa as MODEL_NOT_SERVABLE_CODE,rk as NO_GROUP_ACTIVITY_TOOLS,Pa as OPTIMISTIC_ABORT_MAX_MS,uQ as OPTIMISTIC_COMPACTION_MAX_MS,_a as OPTIMISTIC_RECEIPT_MAX_MS,aJ as PERSISTED_QUERY_CACHE_VERSION,pT as PLUMBING_TOOLS,TJ as PREVIEW_PROBE_TIMEOUT_MS,Z as PROJECT_ACTIONS,_L as PROJECT_SESSION_NAME_LOOKUP_LIMIT,hL as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,Ww as PROJECT_SESSION_PAGE_MAX_LIMIT,Za as PROVISION_IN_FLIGHT_CODE,zx as PROVISION_STREAM_UNTERMINATED_CODE,Uo as PublicSessionShareError,lr as REPOSITORY_DISCONNECTED_CODE,r0 as REVIEW_CONTROL_ACTIONS,gY as RUNTIME_NOT_READY_MARKERS,cB as RUNTIME_PERMISSION_CAPABILITIES,aB as RUNTIME_PERMISSION_REPLIES,vt as RequestTooLargeError,kn as RuntimeNotReadyError,$i as SANDBOX_FS_ROOTS,tt as SANDBOX_PORTS,ec as SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE,ZI as SERVER_COMPACTION_REVALIDATE_MS,ba as SERVER_OBSERVATION_MAX_MS,wQ as SESSION_LIST_STATUS,Oa as SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES,Se as SESSION_LOG_MINOR,ue as SESSION_LOG_SCHEMA,AQ as SESSION_NOTICE,sk as STANDALONE_TOOLS,er as STREAM_OBSERVATION_MAX_MS,Ws as SandboxNotReadyError,Bt as SessionNotReadyError,Mo as SessionStartError,t0 as TRIGGER_CONTROL_ACTIONS,ZJ as TURN_END_LEDGER_LAG_MS,Tv as TURN_ERROR_CODES,hQ as WAKE_ESCALATION_COOLDOWN_MS,yQ as WAKE_MAX_RESTARTS,fQ as WAKE_NO_PROGRESS_MS,Ai as WIRE_ID_BACKDATE_MS,yt as WIRE_ID_CLOCK_TOLERANCE,st as WIRE_ID_TIME_MASK,xn as WIRE_ID_TIME_SCALE,kk as WIRE_MESSAGE_ID,pO as __getConfigResolver,uO as __setConfigResolver,tY as abortErrorReason,uo as acceptAccountInvite,Ac as acceptAccountInviteAndLand,pg as acceptEnterpriseOffer,WY as acceptInvite,Vx as accountInviteLanding,jm as actReviewItem,Zl as activateConnection,nu as addComputerToProject,im as addGroupMembers,If as addMarketplaceSource,nf as addRoomPerson,ef as addRoomSession,bQ as advanceWakeEscalation,AC as allDescendantIds,yJ as appendPreviewToken,rb as approveCaptureDeviceGrant,q_ as approveCaptureEnrollment,OF as approveCliDevice,il as approveProjectAccessRequest,iq as approveTask,xr as archiveProject,mq as assignTicket,yl as attachGroupToProject,Si as authMfa,hi as authUser,U as authenticatedFetch,Rr as authenticatedRequest,RJ as authorizePreviewUrl,c as backendApi,R$ as bindSlackIdentity,C$ as bindTeamsIdentity,Cl as brokerProjectSecretRequest,uJ as browserKeyValueStorage,yI as buildInstancePath,jJ as buildPresentationTemplateImageUrl,OJ as buildPresentationTemplatePdfUrl,VS as buildPreviewAuthEndpoint,H2 as buildPublicTemplateUrl,WI as buildRuntimePresentationConversionUrl,Fu as buildSandboxTemplate,$C as buildScrapeFailureResults,QG as buildStaticFileHealthPreviewUrl,JG as buildStaticFileLocalUrl,YG as buildStaticFilePreviewUrl,WA as buildStaticFileServicePath,a4 as buildTunnelEventStreamUrl,n1 as buildWebProxyUrl,Dm as bulkActReviewItems,R0 as bulkDeletePolicies,C0 as bulkImportPolicies,ca as burstSummary,fT as burstSummaryLabel,sS as burstWorkLabel,It as callConnector,Zw as canManageBilling,l$ as canOfferTopup,QU as cancelAccountDeletion,xc as cancelAccountInvite,OY as cancelSandbox,u2 as cancelSandboxUpdate,sg as cancelScheduledChange,tg as cancelSubscription,oW as captureHealthBucket,dv as changeRequestControlsFrom,C2 as checkAccessEmail,cD as checkMcpServerSignIn,IH as childMapByParent,h2 as claimComputer,cR as claimNext,m$ as claimPerSeatBilling,Vp as claimWarmProjectSession,Kb as classifyPart,qI as classifyPreviewProbeStatus,Mk as classifyPtyClose,zE as classifySessionLogMessage,Zi as classifyTurn,WH as cleanErrorMessage,QH as cleanResultSnippet,wz as cleanWorkerOutput,sc as clearImpersonationSession,MM as clearKortixAppViewerCache,$d as clearModelDefault,HD as clearSessionFresh,dp as closeChangeRequest,Kq as closeMilestone,LH as collectTurnParts,yq as commentTicket,fp as commitSessionChanges,dQ as compactionExpiryAtMs,kV as compactionTurnInfo,na as compareForDisplayAt,TH as compareMessagesForDisplay,pW as compareSemver,lR as completeInFlight,xg as completeSlackInstall,wg as completeTeamsInstall,YP as composerSelectableAgents,SS as computeStatusFromPart,cg as configureAutoTopup,eo as configureKortix,Zd as confirmCheckoutSession,Ig as connectEmail,bg as connectSlack,M$ as connectTelegram,NJ as connectionFromHealth,FJ as connectionIsFaulted,zj as connectionSharedWithEveryone,sw as connectorConnect,ow as connectorFinalize,X2 as connectorHeadline,dg as contactEnterpriseSales,dV as contextLabelForTool,GW as contextToolSummary,WW as contextToolTrigger,gF as convertPresentationToGoogleSlides,DJ as convertRuntimePresentation,Ps as copyFile,mg as costExportUrl,tQ as countLiveInboxPrompts,J$ as countReviewItemsBySegment,pc as createAccount,bf as createAccountAuditWebhook,Ll as createAccountSecretResource,af as createAccountToken,Of as createApp,Bf as createAppAccessSession,qf as createAppDeployment,Lf as createAppToken,oy as createAppVolume,ly as createAppVolumeSnapshot,gV as createArtifactKind,Am as createAssignment,AU as createAuditWebhook,YY as createBackup,N_ as createCaptureEnrollmentToken,Xd as createCheckoutSession,yu as createConnector,Y2 as createConnectorLinkInfoCache,Ss as createFile,zg as createGatewayKey,nm as createGroup,SM as createHttpSessionSyncController,m2 as createInstance,sR as createKortix,Rh as createKortixPty,xi as createKortixSession,zF as createMarketplaceInstallSession,Nq as createMilestone,tO as createModelVisibility,Pm as createOAuthClient,g$ as createPerSeatCheckout,lJ as createPersistedQueryCache,v0 as createPolicy,eg as createPortalSession,$c as createProject,Aq as createProjectAgent,df as createProjectCliToken,Uc as createProjectRepo,Sl as createProjectResourceGrant,Dt as createProjectSession,Gc as createProjectSkill,yd as createProjectTrigger,A_ as createPromptAttachmentController,gm as createRole,zm as createRoom,c4 as createSSEStream,AY as createSandbox,$m as createSandboxShare,Lu as createSandboxTemplate,nL as createSavedCopyStore,U0 as createScimToken,_U as createServiceAccountApi,$r as createSessionPrompt,Gp as createSessionPublicShare,iR as createSessionQueue,Km as createSessionReminder,rU as createSsoGroupMapping,rq as createTask,pq as createTicket,l4 as createTunnelEventStream,BX as createWarmSessionPool,Ip as currentSavedCopyStore,Rc as declineAccountInvite,HY as declineInvite,XU as deleteAccountImmediately,Fl as deleteAccountSecretResource,Df as deleteApp,Yf as deleteAppDeployment,CU as deleteAuditWebhook,QY as deleteBackup,Su as deleteConnector,Au as deleteConnectorCredential,Yq as deleteCredential,ts as deleteCustomLlmProvider,vN as deleteDriveFile,kh as deleteEnv,Wt as deleteFile,Hg as deleteGatewayBudget,nl as deleteGitHubInstallation,sm as deleteGroup,f2 as deleteInstance,Dq as deleteKortixProject,Gq as deleteMilestone,vm as deleteOAuthClient,Ol as deletePersonalProjectSecret,A0 as deletePolicy,Cq as deleteProjectAgent,Il as deleteProjectProviderOAuth,Pl as deleteProjectResourceGrant,wr as deleteProjectSecret,sd as deleteProjectSession,_d as deleteProjectTrigger,ln as deletePromptAttachment,ym as deleteRole,Uu as deleteSandboxTemplate,SU as deleteServiceAccountApi,Xp as deleteSessionPrompt,No as deleteSessionReminder,Hm as deleteSessionReminders,sU as deleteSsoGroupMapping,tU as deleteSsoProvider,aq as deleteTask,hq as deleteTicket,sb as denyCaptureDeviceGrant,G_ as denyCaptureEnrollment,kc as describeAccountInvite,_o as describeConnectorTool,ty as destroyAppMachine,ay as destroyAppVolume,_l as detachGroupFromProject,BA as detectLocalhostUrls,TQ as directSubsessions,bU as disableServiceAccountApi,Eg as disconnectEmail,oJ as disconnectGitHubApp,kg as disconnectSlack,j$ as disconnectTelegram,Xj as discoverConnectionOAuth2,Zj as discoverConnectionOAuth2Resource,hu as discoverConnectorAuth,IY as discoverLocalSandbox,_N as dismissDriveConflict,G2 as downloadAccountAudit,SN as downloadDriveFile,lG as dropClientForUrl,dG as dropPublicClientForUrl,gR as editQueued,Zp as editSessionPrompt,aR as enqueue,vq as ensurePmSession,KI as ensurePreviewSessionCookie,Yj as ensureProjectConnectorConnection,kI as ensureSandbox,Hp as ensureWarmProjectSession,Ik as env,mi as exchangeCode,ry as execInApp,hf as exportAccountAudit,xe as extractGatewayErrorDetails,Qn as extractInstanceRoute,FT as extractSkillBaseDir,Hz as extractSkillContent,LT as extractSkillFiles,kz as extractWorkerPreview,uR as failInFlight,zV as fallbackBusyRowAfterTurnId,Vn as familyForTool,Wa as featureDisabledKey,Yy as featureFlags,u$ as fetchAccountStateWithToken,zO as fetchAccountsWithToken,mJ as fetchAttachmentPart,w$ as fetchCostExportCsv,qP as fetchKortixAppViewer,Wu as fetchProjectArchive,MD as fetchProjectFileRaw,uj as fetchProjectsForAccountWithToken,Vy as fetchSessionAttachment,gA as fileDownloadRequest,Tz as filePhase,Cz as fileVerb,AA as files,Wo as finalizeAppArtifact,D2 as finalizeConnectorSetupLink,SL as findActiveTranscriptShare,_s as findFiles,$H as findLastTextPart,TB as findSessionAttachments,bs as findText,Pd as fireProjectTrigger,Du as fixSandboxWithAgent,XM as flattenModels,OV as flattenThought,py as forkAppVolume,Va as formatBillingErrorForUI,lz as formatCost,xS as formatDuration,HH as formatJsonFailureOutput,LV as formatMessageDay,$V as formatMessageExact,fY as formatOpenCodeRuntimeError,JH as formatRawOutput,vI as formatRuntimeError,uz as formatTokens,SR as formatTranscript,XV as freshSendHint,oR as generateSessionId,dc as getAccount,ff as getAccountAuditActivity,RL as getAccountAutomations,mc as getAccountBranding,YU as getAccountDeletionStatus,Wd as getAccountState,Hd as getAccountStateMinimal,_I as getActiveInstanceIdFromCookie,iF as getAdminProviderAnalytics,rF as getAdminProviderDistribution,cF as getAdminProviderFallback,ZU as getAdminRole,ZR as getAgentCardLabel,t$ as getAgentConfig,Tq as getAgentPersona,a2 as getAllVersions,FH as getAnsweredQuestionParts,qo as getApp,Uf as getAppAccess,$f as getAppAuthEnv,Wf as getAppDeployment,Hf as getAppDeploymentLogs,GF as getApprovalLink,sn as getAuthToken,Bj as getAuthTokenWithRetry,ag as getAutoTopupSettings,d$ as getAutoTopupSetupStatus,Yd as getBillingCreditBreakdown,Qd as getBillingTierConfigurations,zd as getBillingTransactionsSummary,Jd as getBillingUsageHistory,tb as getCaptureAssetUrl,eb as getCaptureChunkMedia,Q_ as getCaptureDays,nb as getCaptureDeviceGrant,Z_ as getCaptureFrame,W_ as getCapturePolicy,V_ as getCaptureStorage,Y_ as getCaptureTimeline,J_ as getCaptureTimelineItems,ob as getCaptureWorkspace,ap as getChangeRequest,cp as getChangeRequestDiff,lp as getChangeRequestMergePreview,aH as getChildSessionError,Os as getChildSessionId,cH as getChildSessionToolParts,ht as getClient,He as getClientForUrl,vu as getConnectStatus,Qj as getConnectionOAuth2Application,sD as getConnectionOAuth2Status,oD as getConnectionPolicies,on as getConnectorCatalog,gu as getConnectorConfig,pu as getConnectorPolicies,O2 as getConnectorSetupLink,x$ as getCostSummary,hI as getCurrentInstanceIdFromPathname,oY as getCurrentInstanceIdFromWindow,n_ as getCurrentProject,Kd as getDefaultAccountState,pH as getDiagnostics,XR as getDirectory,xo as getDiscoverConnector,dD as getDiscoverIntegration,gy as getDriveFileUrl,Cg as getEmailInstallation,Tg as getEmailMode,LU as getEnterpriseDemo,hs as getFileStatus,jb as getFileWithDir,QR as getFilename,gN as getFolderAccess,RI as getFullChangelog,Bg as getGatewayBreakdown,Gg as getGatewayBudgets,qg as getGatewayErrors,Vg as getGatewayKeys,Ug as getGatewayLog,Fg as getGatewayOverview,Og as getGatewayRoutingPolicy,Ng as getGatewaySeries,Kg as getGatewaySessions,tJ as getGitHubAppStatus,zc as getGitHubInstallation,dF as getGoogleAuthUrl,tm as getGroup,oH as getHiddenToolParts,Ix as getImpersonationSession,GY as getInvite,g2 as getJustavpsServerTypes,Mq as getKortixProject,Oq as getKortixProjectBySession,Ih as getKortixPtyWebSocketUrl,i2 as getLatestSandboxVersion,N2 as getMaintenanceConfig,rl as getManagedGitBackend,sj as getManagedGitStatus,Rf as getMarketplaceCatalogItem,Cf as getMarketplaceCatalogItemFile,q0 as getMfaRequired,Uq as getMilestone,pb as getMobileClientPolicy,Dd as getModelDefaults,lb as getMyCaptureFrame,cb as getMyCaptureTimeline,Sy as getNotificationPreferences,Sm as getOAuthClient,E2 as getOAuthConsentRequest,pY as getOpenCodeConfigInvalidError,nH as getPartText,dU as getPatPolicy,dH as getPermissionForTool,Ct as getProject,Iq as getProjectActivity,np as getProjectCommit,rp as getProjectCommitDiff,_r as getProjectDetail,dy as getProjectDrive,sp as getProjectFileHistory,_j as getProjectGitConnectionState,Lc as getProjectGitToken,ON as getProjectGoalFiles,br as getProjectLlmCatalog,tj as getProjectLlmCatalogProviders,Qr as getProjectModelAccess,Sr as getProjectModelPicker,rj as getProjectQuota,Ar as getProjectSandboxHealth,ij as getProjectSandboxProviderTransition,jr as getProjectSession,ad as getProjectSessionConfigState,ud as getProjectSessionScope,og as getProrationPreview,vY as getProviders,XG as getProxyBaseUrl,pG as getPublicClientForUrl,A2 as getPublicMarketplaceItem,R2 as getPublicMarketplaceItemFile,xF as getPublicSessionShare,wF as getPublicSessionShareMessages,U2 as getPublicShareByToken,V2 as getPublicTemplate,gH as getQuestionForTool,q$ as getReferralCode,H$ as getReferralStats,pz as getRetryInfo,dz as getRetryMessage,Mm as getReviewItem,Em as getReviewSummary,pm as getRolePermissions,dm as getRoleUsage,Ym as getRoom,ma as getRuntimeConfigInvalidError,e2 as getSSHConnection,kY as getSandbox,RY as getSandboxById,bY as getSandboxPortUrl,_2 as getSandboxProvisionStatus,b2 as getSandboxProvisionStreamUrl,o2 as getSandboxUpdateStatus,FS as getSandboxUrl,Fe as getSandboxUrlForExternalId,L2 as getSecretSetupLink,Ui as getServerHealth,Xq as getServiceLogs,zp as getSessionAudit,cz as getSessionCost,Hr as getSessionCostRecord,bv as getSessionDrives,l_ as getSessionHealth,Jp as getSessionLogPage,gd as getSessionMessageAuthors,md as getSessionModelUsage,PL as getSessionOpenBundle,H0 as getSessionOversight,$p as getSessionParticipants,cU as getSessionPolicy,Kp as getSessionPreviewCandidates,ql as getSessionProviderSecretPool,Yp as getSessionTranscript,Dr as getSessionTranscriptSync,Lr as getSessionTurn,Up as getSessionWatch,Sz as getShellModePart,Ag as getSlackChannelFile,_g as getSlackInstallation,vg as getSlackManifest,Sg as getSlackMode,Q0 as getSsoProvider,HA as getStaticFileHealthPath,fo as getSupabaseAccessToken,Zx as getSupabaseAccessTokenWithRetry,eq as getTask,nq as getTaskStatus,E$ as getTelegramInstallation,QF as getTemplate,lq as getTicket,lH as getToolInfo,Ji as getToolPrimaryArg,PR as getTranscriptFilename,pa as getTurnCost,oz as getTurnError,az as getTurnErrorDetails,iz as getTurnErrorRawText,PS as getTurnStatus,gg as getUsageRollup,K2 as getUserRolesWithToken,op as getVersionDiff,xy as getWebPushPublicKey,rz as getWorkingState,wv as goalHealth,Nl as grantAccountSecretResource,NY as grantSandboxProjectAccess,r$ as grantSecretToAgent,DH as groupMessagesIntoTurns,fS as groupShowSegments,iS as groupSteps,gz as hasDiffs,zG as hasLocalhostUrls,GA as hasPreviewTarget,zb as hasRetryingAssistantTurn,tA as heartbeatGapEvent,nd as holdSessionPrompts,Zg as humanizeReviewActionPath,Is as humanizeSearchQuery,Fb as humanizeToolName,oc as impersonationHeaders,Z0 as importSsoProviderFromMetadata,eQ as inboxObservationSupersedes,XS as initialWakeEscalationState,Ie as inputPath,XF as installTemplate,ed as interruptSessionPrompt,yo as invalidateTokenCache,Sc as inviteAccountMember,pl as inviteProjectMember,jc as inviteRepoCollaborator,qs as isAbortError,jx as isAdminBypassEnabled,QW as isAgentPart,UA as isAppRouteUrl,rH as isAttachment,DI as isAttachmentPartRef,tn as isAuthFailure,Ha as isBillingError,XW as isCompactionPart,to as isConfigured,qW as isContextTool,s2 as isDestructivePhase,BP as isEmptyConversation,ri as isEmptyShowPart,GH as isErrorOutput,o1 as isExternalUrl,Ga as isFeatureDisabledError,Db as isFilePart,Cx as isImpersonationSessionLive,rY as isInstanceDetailPath,fI as isInstanceScopedAppPath,t1 as isInternalLocalhostUrl,Gy as isInvisibleActivityPart,Aj as isInviteSent,nz as isLastUserMessage,rE as isLegacyMigratedSession,ej as isManagedGithubProject,qy as isNoGroupActivityTool,Ba as isOfferedModel,dY as isOpenCodeConfigInvalidError,Mw as isPaintableSavedCopy,eH as isPatchPart,cJ as isPersistableQueryKey,e1 as isPreviewUrl,VA as isProxiableLocalhostUrl,Ky as isQuestionTool,we as isReasoningPart,hx as isRepositoryDisconnectedError,TC as isRetryableTurnError,bI as isRuntimeConfigInvalidError,xI as isRuntimeNotReadyResponse,c_ as isRuntimeReady,mY as isRuntimeStartingError,Zn as isSandboxNotReadyError,ci as isSelectableAgent,r_ as isServerReachable,CB as isSessionAttachmentRef,hp as isSessionFresh,XE as isSessionLogRestoreNote,$L as isSessionStartError,bB as isShellActivityTool,jT as isShellMode,vz as isShortOutput,oB as isShowContentUnavailable,ns as isShowPayloadEmpty,ZW as isSnapshotPart,Wy as isStandaloneActivityTool,tH as isStepPart,Vs as isSubdomainPreviewUrl,Je as isTextPart,te as isToolPart,iH as isToolPartHidden,Ry as isTurnErrorCode,Hh as isUnderSandboxRoot,s1 as isWebProxyUrl,Rk as isWireIdAheadOf,jM as kortixAppViewerToken,LM as kortixBinding,Lk as kortixPty,GP as kortixToken,sO as latestPromptModel,Ic as leaveAccount,U_ as linkCaptureDevice,el as linkGitHubInstallation,Hc as linkRepository,mf as listAccountAudit,_f as listAccountAuditWebhooks,Pc as listAccountInvites,bc as listAccountMembers,_0 as listAccountResourceGrants,Dl as listAccountSecretResources,uU as listAccountSessions,of as listAccountTokens,uc as listAccounts,M0 as listActions,sF as listAdminSandboxes,lm as listAgentIdentities,zl as listAllConnections,Ff as listAppAgents,Gf as listAppDeployments,Qf as listAppMachines,cy as listAppVolumeSnapshots,sy as listAppVolumes,Mf as listApps,km as listAssignments,TU as listAuditEvents,kU as listAuditWebhooks,zY as listBackups,Vd as listBillingTransactions,L_ as listCaptureDevices,F_ as listCaptureEnrollmentTokens,K_ as listCaptureEnrollments,ip as listChangeRequests,D$ as listChannelBindings,_q as listColumns,uD as listConnectSections,lD as listConnectToolkits,Vl as listConnections,bo as listConnectorAccounts,_u as listConnectorMoves,ho as listConnectorTools,iu as listConnectors,P$ as listCostByProject,Hq as listCredentialEvents,Wq as listCredentials,Zr as listCustomLlmProviders,Po as listDiscoverConnectors,pD as listDiscoverIntegrations,wu as listDiscoverSections,hN as listDriveConflicts,bN as listDriveFiles,Vo as listDriveFolder,kN as listDriveVersions,wh as listEnv,Af as listFeaturedMarketplaces,Sq as listFields,On as listFiles,yN as listFolderPrincipals,$g as listGatewayLogs,Yc as listGitHubInstallations,Qc as listGitHubRepositories,Xc as listGitHubRepositoryBranches,om as listGroupMembers,p0 as listGroupProjectGrants,em as listGroups,jq as listKortixProjectSessions,Eq as listKortixProjects,Ah as listKortixPty,Jc as listLinkableGitHubInstallations,sl as listManagedGitRepositories,vf as listMarketplaceCatalogItems,Tf as listMarketplaceSources,kf as listMarketplaces,d0 as listMemberGroups,g0 as listMemberProjectAccess,Fq as listMilestoneEvents,$q as listMilestones,vc as listMyAccountInvites,_y as listNotifications,bm as listOAuthClients,lf as listOAuthGrants,xl as listPendingApprovals,dl as listPendingProjectInvites,Cm as listPermissions,Pu as listPipedreamApps,xu as listPipedreamSections,w0 as listPolicies,cl as listProjectAccess,ol as listProjectAccessRequests,um as listProjectAgentIdentities,kq as listProjectAgents,yf as listProjectAudit,ep as listProjectBranches,pf as listProjectCliTokens,tp as listProjectCommits,Ku as listProjectDirectory,Bu as listProjectFiles,MN as listProjectGoals,fl as listProjectGroupGrants,Iu as listProjectPolicies,Tl as listProjectProviderOAuth,Vr as listProjectReminders,bl as listProjectResourceGrants,Mu as listProjectSandboxTemplates,Nu as listProjectSandboxes,kl as listProjectSecrets,jt as listProjectSessions,Dp as listProjectSessionsPage,Ou as listProjectSnapshots,Ad as listProjectTriggerEventApps,kd as listProjectTriggerEventTypes,wd as listProjectTriggerRuns,fd as listProjectTriggers,Rt as listProjects,Oc as listProjectsForAccount,v2 as listPublicMarketplaceItems,k2 as listPublicMarketplaces,V$ as listReferrals,Im as listReviewItems,cm as listRoles,Qm as listRoomMessages,sf as listRoomPeople,Vm as listRooms,FY as listSandboxProjectMembers,Lm as listSandboxShares,TY as listSandboxes,$0 as listScimTokens,hU as listServiceAccountsApi,Qq as listServiceTemplates,Jq as listServices,aD as listSessionConnectRequests,fg as listSessionCosts,RN as listSessionDrives,Qp as listSessionPrompts,Gl as listSessionProviderSecretPools,qp as listSessionPublicShares,Bm as listSessionReminders,wl as listSessionsNeedingInput,jF as listSignedInDevices,nU as listSsoGroupMappings,tq as listTaskEvents,ZK as listTasks,xq as listTemplates,uq as listTicketEvents,cq as listTickets,xd as listTriggerRuns,bM as loadHttpSessionHistory,ft as loadPreviewUrlTemplate,Jb as looksLikeError,sV as looksLikeHtml,YH as looksLikeJsonPayload,xN as makeDriveFolder,X$ as mapApiReviewItem,y2 as markInstanceError,by as markNotificationsRead,Zm as markRoomRead,Mr as markSessionFresh,_h as maxWireIdClock,Oz as memoryRelPath,aS as mergeBurstSteps,pp as mergeChangeRequest,DV as messageCreatedAt,ST as messageTime,aF as migrateAdminSandboxProvider,Ri as mintWireMessageId,Sh as mintWireMessageIdAbove,$n as mkdir,nO as modelInDefaultView,sr as modelRefToKey,bu as moveConnector,wN as moveDriveFile,rS as narrateFailedStep,Ns as narrateStep,Fs as narrationToolName,nA as narrowChatEvent,Ck as newestWireIdClock,Q2 as nextConnectorPollDelay,he as normalizeActivityToolName,cY as normalizeAppPathname,tW as normalizeCaptureAppId,eW as normalizeCaptureDomain,i1 as normalizeExternalInput,ee as normalizeName,Ub as normalizeToolName,iE as notifyHostSignal,up as openChangeRequest,Mi as openEventStream,W2 as openStressTestStream,Tu as paginateConnector,ur as parseBillingError,XH as parseEmbeddedFailure,OB as parseFlagOverride,Qb as parseJsonFailure,ks as parseLocalhostUrl,jz as parseMemoryView,uY as parseOpenCodeErrorPayload,Fz as parsePresentationOutput,a_ as parseProxyHop,MS as parseQuestionAnswersFromOutput,qz as parseReadOutput,US as parseRuntimeErrorPayload,LC as parseScrapeInputUrls,UC as parseScrapeOutput,__ as parseSubdomainUrl,Az as parseTaskRows,r1 as parseWebProxyUrl,Zb as parseWebSearchOutput,ra as partOutcome,Lq as patchKortixProject,$z as patchVerb,JM as pickerProviderList,fu as pipedreamConnect,su as pipedreamConnectConnection,Ru as pipedreamFinalize,ou as pipedreamFinalizeConnection,I as platformConfig,rD as pollConnectionOAuth2DeviceAuthorization,go as pollProjectProviderOAuth,Xm as postRoomMessage,lg as previewBillingPlan,Lg as previewGatewayRoute,G0 as previewMfaRequired,T$ as previewSlackIdentity,I$ as previewTeamsIdentity,hm as probeEffectivePermission,_m as probeEffectivePermissions,IJ as probePreviewPort,Hu as projectArchiveRequest,pQ as projectCompacting,qM as projectConfigAgentsToOpenCodeAgents,zP as projectConfigAgentsToRuntimeAgents,UJ as projectSessionConnection,IQ as projectSessionForRuntimeId,Ed as projectSessionStartSeed,rQ as projectWorking,Fc as provisionProject,nj as provisionProjectStream,pj as provisionProjectWithToken,y_ as proxyLocalhostUrl,ZG as proxyUrlToInternal,ig as purchaseCredits,Jj as putConnectionOAuth2Application,es as putCustomLlmProvider,Ts as rawErrorText,jY as reactivateSandbox,ng as reactivateSubscription,Dn as readBlob,my as readDriveFile,jn as readFile,La as readKortixMember,Gu as readProjectFile,EM as readSavedSessionCopy,la as reasoningIsRunning,ju as rebuildProjectSnapshot,Yl as reconcileConnection,Jl as reconcileMemberConnection,eG as reconcileServices,I2 as recordPlatformLogout,sa as recoverLinkResults,od as recoverProjectSession,G$ as refreshReferralCode,_n as refreshSession,Go as registerAppArtifact,eD as registerConnectionOAuth2Client,fy as registerDeviceToken,tG as registerService,wy as registerWebPushSubscription,al as rejectProjectAccessRequest,uH as relativizePath,hy as releaseDeviceToken,cd as reloadProjectSessionConfig,ld as reloadProjectSessionConfigStream,Pf as removeAccountAuditWebhook,hc as removeAccountBrandingAsset,Cc as removeAccountMember,am as removeGroupMember,Th as removeKortixPty,Ef as removeMarketplaceSource,Wc as removeProjectSkill,dR as removeQueued,rf as removeRoomPerson,tf as removeRoomSession,tu as renameConnection,ws as renameFile,CY as renameSandbox,gp as reopenChangeRequest,qq as reopenMilestone,mR as reorderQueued,bq as replaceColumns,Pq as replaceFields,Vc as replaceProjectRepository,wq as replaceTemplates,vd as replayTriggerRun,_x as repositoryDisconnectedReason,JU as requestAccountDeletion,mp as requestChangesOnChangeRequest,kj as requestProjectAccess,wf as requestProjectConnector,xf as requestProjectSecret,p$ as requestTopUp,$M as requireKortixMember,wc as resendAccountInvite,ml as resendPendingProjectInvite,_c as resetAccountBranding,uG as resetClient,Dg as resetGatewayRoutingPolicy,fi as resetPassword,gG as resetPublicClient,l2 as resetSandboxUpdateStatus,vl as resolveApproval,KM as resolveComposerAgent,lO as resolveComposerModel,J2 as resolveConnectorStart,rO as resolveModelDefault,bL as resolvePublicShareUrl,oV as resolveScrapeResults,bS as resolveWorkingTurn,c$ as resolvedPlan,ey as restartAppMachine,Ur as restartProjectSession,EY as restartSandbox,uy as restoreAppVolume,JY as restoreBackup,AN as restoreDriveVersion,id as restoreProjectSession,Ul as retryAccountSecretResource,pR as retryFailed,td as retrySessionPrompt,zq as revealCredential,Xg as reviewItemTarget,nv as reviewSegmentForStatus,s0 as reviewVerdictAllowed,Q$ as reviewVerdictForStatus,Bl as revokeAccountSecretResourceGrant,pU as revokeAccountSession,cf as revokeAccountToken,Rm as revokeAssignment,$_ as revokeCaptureDevice,B_ as revokeCaptureEnrollmentToken,Xl as revokeConnection,Yg as revokeGatewayKey,uf as revokeOAuthGrant,gl as revokePendingProjectInvite,ul as revokeProjectAccess,gf as revokeProjectCliToken,BY as revokeSandboxProjectAccess,Um as revokeSandboxShare,F0 as revokeScimToken,Wp as revokeSessionPublicShare,bt as rewriteLocalhostUrl,Jf as rollbackApp,sE as rootRuntimeSession,$l as rotateAccountSecretResource,wm as rotateOAuthClientSecret,ko as runConnector,Jg as runGatewayPlayground,Ij as runProjectProviderOAuthFlow,qm as runSessionReminder,wa as runtimeSessionsOf,CA as runtimeSupports,Dk as sanitizePtyChunk,Zc as saveGitHubInstallation,NP as savedCopyEmptyRoot,ny as scaleApp,rg as scheduleDowngrade,X_ as searchCapture,Hl as searchConnectorTools,ab as searchMyCapture,qu as searchProjectFiles,gS as segmentTurn,LB as selectableProjectAgents,pi as sendMagicLink,z$ as sendReferralEmails,gQ as serverCompactionRevalidateAtMs,Zq as serviceAction,kQ as sessionConnectionLabel,vQ as sessionListStatus,NE as sessionLogActivityText,VE as sessionLogAnsweredQuestionCall,qE as sessionLogBurstRunning,FE as sessionLogBurstSteps,BE as sessionLogBurstSummary,KE as sessionLogBurstWorkLabel,_E as sessionLogCallStatus,oM as sessionLogFullTextAction,iM as sessionLogFullTextPlan,ZE as sessionLogHarnessSwitches,mE as sessionLogOfV1Rows,GE as sessionLogOpenCall,bE as sessionLogPromptMessage,nM as sessionLogReferencedTexts,tM as sessionLogRestoreNotice,bP as sessionLogRetrying,HE as sessionLogShowGroupCall,JE as sessionLogThreadMetrics,DE as sessionLogTurnSegments,Ia as sessionLogTurns,aM as sessionLogWithFullTexts,cO as sessionModelCandidates,iO as sessionModelFallback,Nr as sessionModelPin,yL as sessionParentId,aO as sessionPickStands,wL as sessionPromptActions,UL as sessionStartKey,CL as setAccountAutomationsPaused,Kl as setAccountSecretResourceAccess,iY as setActiveInstanceCookie,Ox as setAdminBypass,oF as setAdminProviderDistribution,lF as setAdminProviderFallback,Fd as setAgentScope,ug as setBillingPlan,Nj as setBootstrapAuthToken,Fj as setCachedAuthToken,ib as setCaptureEnabled,H_ as setCapturePolicy,z_ as setCaptureStorage,iD as setConnectionPolicies,lu as setConnectorAuthorizationStrategy,ku as setConnectorCredential,cu as setConnectorCredentialMode,mu as setConnectorName,du as setConnectorPolicies,gD as setConnectorSecretBinding,uu as setConnectorSensitive,eu as setDefaultConnection,oj as setDefaultReasoningEffort,$U as setEnterpriseDemo,vh as setEnv,Wg as setGatewayBudget,jg as setGatewayRoutingPolicy,rJ as setGitHubAppFromExisting,sJ as setGitHubAppPat,PO as setImpersonationSession,B2 as setMaintenanceConfig,O0 as setMemberSuperAdmin,W0 as setMfaRequired,Ld as setModelDefault,Ml as setPersonalProjectSecret,Xr as setProjectModelAccess,WL as setProjectModelEnablement,qc as setProjectOnboardingComplete,cj as setProjectOnboardingProfile,Eu as setProjectPolicies,Rl as setProjectSecretStrategy,dd as setProjectSessionModel,pd as setProjectSessionScope,Lp as setProjectSessionSharing,bd as setProjectTriggersActivation,rL as setSavedCopyStore,Bp as setSessionArchived,V0 as setSessionOversight,Np as setSessionPinned,Wl as setSessionProviderSecretPool,Fp as setSessionWatch,O$ as setTelegramAllowedUsers,KJ as settleSessionConnection,ZY as setupSSH,ru as shareConnection,mN as shareFolder,SB as shellActivityGroupLabel,DS as shellExitCode,Mx as shouldAttachImpersonation,sz as shouldHideResponsePart,Kn as shouldShowToolPart,VV as shouldSuppressWorkingTurnBusy,yS as showGroupItems,hS as showTurnBusyIndicator,ui as signInWithPassword,gi as signInWithProvider,bi as signInWithSso,Pi as signOut,DF as signOutDevice,li as signUp,zz as skillDocumentPath,Vz as skillInputDir,EH as sortSessions,$E as splitSessionLogTurnWork,TS as splitTurnWork,sH as splitUserParts,Vf as startApp,Xf as startAppMachine,tD as startConnectionOAuth2Authorization,nD as startConnectionOAuth2DeviceAuthorization,j2 as startConnectorSetupLink,nJ as startGitHubAppManifest,po as startProjectProviderOAuth,mt as startProjectSession,Od as startProjectSessionOrThrow,F2 as startSessionWithToken,oq as startTask,zn as stepLabel,zf as stopApp,Zf as stopAppMachine,Fr as stopProjectSession,MY as stopSandbox,tl as storeGitHubUserToken,Lb as stripAnsi,sY as stripInstancePrefix,pe as stripTrailingSlashes,YE as subAgentCalls,T2 as submitAccessRequest,q2 as submitDemoRequest,M2 as submitOAuthConsent,Om as submitReviewItem,$2 as submitSecretSetupLink,xO as subscribeToImpersonation,BO as supabaseClient,au as syncConnectors,f$ as syncSubscription,mG as systemReload,_t as toDaemonPath,aY as toInstanceAwarePath,zA as toInternalUrl,Mn as toSandboxAbsolutePath,Bb as toToolView,Vh as toWorkspaceRelative,us as toolCallBlock,nk as toolCallError,Zv as toolCallMetadata,tk as toolCallRawOutput,ek as toolCallStatus,Qi as toolInfo,ce as toolKind,cI as toolViewModel,lj as transferProject,n0 as triggerControlsFrom,c2 as triggerSandboxUpdate,Ek as triggersRequest,QI as turnEndCause,cQ as turnEndNotice,UH as turnHasSteps,YV as turnIsConfirmedActive,JV as turnRendersQueued,RQ as turnRetryLabel,fq as unassignTicket,yy as unregisterDeviceToken,vy as unregisterWebPushSubscription,fN as unshareFolder,Vb as untimedAnchorOf,_e as unwrapError,Sf as updateAccountAuditWebhook,fc as updateAccountBranding,Tc as updateAccountMemberRole,gc as updateAccountName,n$ as updateAgentConfig,jf as updateApp,Nf as updateAppAccess,iy as updateAppVolume,RU as updateAuditWebhook,yp as updateChangeRequest,L$ as updateChannelBinding,Ql as updateConnectionCredential,Mg as updateEmailPolicy,Bc as updateExperimentalFeature,Nc as updateFeatureFlag,rm as updateGroup,Ch as updateKortixPty,Bq as updateMilestone,Py as updateNotificationPreferences,xm as updateOAuthClient,yi as updatePassword,gU as updatePatPolicy,k0 as updatePolicy,Pr as updateProject,ll as updateProjectAccess,Rq as updateProjectAgent,Nd as updateProjectDefaultAgent,hl as updateProjectGroupGrant,Kc as updateProjectSandboxProvider,rd as updateProjectSession,hd as updateProjectTrigger,mm as updateRole,fm as updateRolePermissions,Jm as updateRoom,$u as updateSandboxTemplate,lU as updateSessionPolicy,Fo as updateSessionReminder,Wm as updateSessionReminders,sq as updateTask,aj as updateTemplateWarmPool,dq as updateTicket,gq as updateTicketStatus,_i as updateUserMetadata,yc as uploadAccountBrandingAsset,Kf as uploadAppArtifactArchive,So as uploadConnectorAttachment,PN as uploadDriveFile,Ln as uploadFile,PA as uploadNativeFile,Er as uploadPromptAttachment,Hy as uploadSessionAttachment,Rg as uploadSlackChannelFile,Cn as uploadTimeoutMsForBytes,Vq as upsertCredential,El as upsertProjectGitCredential,Al as upsertProjectSecret,X0 as upsertSsoProvider,Dc as validateProjectManifest,W$ as validateReferralCode,Ec as validateToken,N$ as verifyGatewayProvider,NM as verifyKortixToken,di as verifyOtp,eU as verifySsoDomain,PQ as wakeEscalationAttemptSummary,SQ as wakeEscalationNote,_Q as wakeProgressFingerprint,Kt as wireIdClock,wn as wireIdClockAt,qt as wireIdClockDelta,hz as workedForLabel,sQ as workingExpiryAtMs,QV as workingTurnDrawsBusyRow,PB as writeActivityGroupLabel,xs as writeFile,Vu as writeProjectFile,oa as wsDomain,rV as wsFavicon,nV as wsRootDomain};
|
|
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 tI(e){let t=Ds(e.input),n=t.map(([s,o])=>eI(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:fa(e),diff:r}}var US=/^Found\s+(\d+)\s+match/i,nI=/^(\/[^:]+?):\s*/,LS=/Line\s+(\d+):/g;function rI(e){let t=e.trim(),n=t.match(US),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(nI);if(!a)continue;let l=a[1],p=i.slice(a[0].length),d=[],g;for(LS.lastIndex=0;(g=LS.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 sI(e){return e.trim().split(`
|
|
97
|
+
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function oI(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=US.test(e.output.trim())?rI(e.output):sI(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function iI(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 ma(e){let t=Jt(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function aI(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(ma)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(ma)};let n=Jt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(ma)}:{kind:"todo",items:[]}}function cI(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=Jt(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let l=Jt(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 lI(e){let n=e.input&&Object.keys(e.input).length>0?DS(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Jn(e.outputParsed):DS(e.outputParsed):e.outputText!==void 0?r=Jn(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function uI(e){switch(ce(e.name)){case"web_search":return WT(e);case"bash":return JT(e);case"read":return QT(e);case"write":return XT(e);case"edit":return tI(e);case"grep":case"glob":return oI(e);case"task":return iI(e);case"todowrite":return aI(e);case"question":return cI(e);default:return lI(e)}}var pI=new Set(["AbortError","MessageAbortedError"]),dI=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],gI=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function FS(e){let t=e.toLowerCase();return gI.some(n=>t.includes(n))?!1:dI.some(n=>t.includes(n))}function mI(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 Gs(e){if(typeof e=="string")return FS(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&pI.has(n))return!0;let r=mI(t);return typeof r=="string"?FS(r):!1}var fI=["user","runtime-disposed","orphan-finalized","wake"],iY=["orphan-finalized","wake"];function aY(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 fI.includes(n)?n:void 0}var Ws="kortix-active-instance",yI=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function hI(e){return yI.some(t=>e===t||e.startsWith(`${t}/`))}function Qn(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 lY(e){let t=Qn(e);return!!t&&t.innerPath===""}function uY(e){let t=Qn(e);return!t||!t.innerPath?e:t.innerPath}function _I(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=Qn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return hI(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function bI(e){return e?Qn(e)?.instanceId??null:null}function pY(){return typeof window>"u"?null:bI(window.location.pathname)||SI()}function SI(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Ws}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function dY(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Ws}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Ws}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Ws}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function gY(e,t){return t?_I(t,e):e}function mY(e){let t=Qn(e);return t?t.innerPath||"/dashboard":e}function Zn(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 NS(e){let t=Zn(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 yY=NS;function ya(e){let t=NS(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var hY=ya;function PI(e){return ya(e)!==null}var _Y=PI,xI=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],bY=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],wI=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function kI(e){return wI.test(Zn(e))}function er(e){let t=Zn(e);return t?kI(t)||xI.some(n=>n.test(t)):!1}var vI=/server url not ready|sandbox is still loading/i;function SY(e){return vI.test(Zn(e))||er(e)}var Xn=class extends Error{constructor(t){let n=t?.trim();super(n&&er(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function AI(e){let t=ya(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=Zn(e);return er(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 PY=AI;function BS(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`${nt()}/p/${e.external_id}/${tt.KORTIX_MASTER}`}function vY(e,t){return e.external_id?`${nt()}/p/${e.external_id}/${t}`:null}async function IY(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function RI(e){let t=await mn();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Ct())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await Lt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await ft(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Jr(r,s,o),created:!0}}async function EY(){return(await mn().catch(()=>null))?.sandbox??null}async function MY(e){return{sandbox:(await RI(e)).sandbox}}async function OY(e){let t=gn(e);if(!t)return null;try{let n=await Qo(t);return n?Jr(await Tt(n.project_id),n,null):(await mn(t))?.sandbox??null}catch{return null}}async function jY(e,t){throw await Qr(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function DY(e){let t=gn(e);return(await Jo().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function LY(){return null}async function $Y(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Qr(e);if(!t)throw new Error("Project session sandbox not found");await Fr(t.projectId,t.sessionId)}async function UY(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Qr(e);if(!t)throw new Error("Project session sandbox not found");await Nr(t.projectId,t.sessionId)}async function FY(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function NY(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function ha(e,t,n){let r=BS(e),s=await U(`${pe(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 WY(e,t){return ha(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function HY(e,t,n,r="member"){await ha(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function VY(e,t,n){await ha(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var _a="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function JY(e){throw N("getInvite",_a)}async function QY(e){throw N("acceptInvite",_a)}async function XY(e){throw N("declineInvite",_a)}async function e2(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function t2(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function n2(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function r2(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function o2(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function i2(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var CI=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function u2(e){return CI.includes(e)}async function p2(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 d2(e){let t=e?`?channel=${e}`:"",r=await(await Oe(`${nt()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await TI(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function TI(e){let t=e?`?channel=${e}`:"";return(await(await Oe(`${nt()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function g2(){return(await Oe(`${nt()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function m2(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function f2(e){}async function y2(e){}async function b2(e){return{serverTypes:[],location:e||"hel1"}}async function S2(e){throw new Error("Retired instance provisioning is unavailable. Create a project session on platinum (or the legacy daytona fallback).")}async function P2(e){throw N("deleteInstance")}async function x2(e,t){}async function w2(){throw N("claimComputer")}async function k2(e){return null}function v2(e,t){throw N("getSandboxProvisionStreamUrl")}var Hs=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function KS(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 qS(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function GS(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(`${Ne(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:KS(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 qS(s);if(!s.ok)throw new Hs(GS(s,o),s.status,o);return o}function II(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 E2(e,t){return z(`/marketplace/items${II(t)}`,e)}function M2(e){return z("/marketplace/marketplaces",e)}function O2(e,t){return z(`/marketplace/items/${encodeURIComponent(e)}`,t)}function j2(e,t,n){return z(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function D2(e,t){return z("/access/check-email",t,{method:"POST",body:{email:e}})}function L2(e,t){return z("/access/request-access",t,{method:"POST",body:e})}function $2(e){return z("/auth/logout",e,{method:"POST",body:{}})}function U2(e,t){return z(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function F2(e,t){return z("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function N2(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function B2(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function K2(e,t,n={}){return z(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function q2(e,t){return z(`/connectors/app-form/${encodeURIComponent(e)}`,t)}function G2(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 W2(e,t){return z(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function H2(e,t,n,r){return z(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function V2(e,t){return z(`/p/public-share/${encodeURIComponent(e)}`,t)}async function z2(e,t={backendUrl:mt()}){return(await z(`/public/responses/${encodeURIComponent(e)}`,{...t,accessToken:null})).response}function Y2(e,t,n){return z(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function J2(e){return z("/system/maintenance",e)}function Q2(e,t){return z("/system/maintenance",t,{method:"PUT",body:e})}function X2(e){return z("/user-roles",e)}function Z2(e,t){return z("/system/demo-request",t,{method:"POST",body:e})}async function eJ(e,t,n){let r=await fetch(`${Ne(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${Ut(t)}`,{headers:KS(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await qS(r);throw new Hs(GS(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 tJ(e,t){throw N("openStressTestStream")}function nJ(e,t){throw N("buildPublicTemplateUrl")}async function rJ(e,t,n){throw N("getPublicTemplate")}var EI="kortix:connect-link:";function ba(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`${EI}${t.toString(36)}${n.toString(36)}`}function oJ(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(ba(i));if(!a)return;let l=JSON.parse(a);if(Date.parse(l.expires_at)<=Date.now()){t.removeItem(ba(i));return}return l}catch{return}},o=(i,a)=>{if(t)try{t.setItem(ba(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 WS="Could not start the connect flow.";async function iJ(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:WS}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:WS};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var MI=3e3,OI=5e3,jI=5*6e4;function aJ(e,t){let n=e===0?MI:OI;return t+n>jI?null:n}function cJ(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 pJ(){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 dJ(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 gJ(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 mJ(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 fJ(){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 hJ="1";var DI="kortix.query-cache";function VS(e){return!!e&&typeof e.then=="function"}function HS(e){return VS(e)?e:Promise.resolve()}function _J(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 bJ(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:l=DI,now:p=()=>Date.now()}=e,d=`${l}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),P=()=>{try{return HS(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),_=(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},b=async x=>{let k=_(T(x),i);for(;;){let C={v:s,user:n,at:p(),queries:k};try{await HS(t.setItem(d,JSON.stringify(C)));return}catch{if(k.length===0)return;k=k.slice(0,Math.floor(k.length/2))}}},O=()=>{f!==null&&(clearTimeout(f),f=null)},y=()=>{O();let x=g;return!x||!m||(m=!1,h=h.then(()=>b(x)).catch(()=>{})),h},w=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,y()},a))};return{storageKey:d,restore(x){let k;try{k=t.getItem(d)}catch{return 0}return VS(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 SJ(){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 LI="/kortix/part/";function $I(e){return typeof e=="string"&&e.startsWith(LI)}async function kJ(e){if(!$I(e))throw new Error(`not an attachment part reference: ${e}`);let t=Ge();if(!t)throw new Error("runtime url not bound");let n=await U(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function zS(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 UI(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 YS(e,t){return UI(e,t)?(t?zS(t):null)??zS(e):null}function Vs(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 AJ(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var FI=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function NI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function BI(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(NI).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function KI(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function JS(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function qI(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:FI.test(n.hostname)?t.backendUrls.some(r=>{let s=KI(r);return s!==null&&JS(s)===JS(n)}):t.templates.some(r=>BI(n.origin,r))}async function QS(e,t={}){if(!Vs(e))return!1;let n=I().backendUrl;n&&await yt(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return qI(e,{templates:sh(),backendUrls:r})}async function GI(e,t={}){let n=YS(e,t.serverUrl||I().backendUrl||void 0);if(!n)return!1;let r=await on();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 $J(e,t={}){if(Vs(e)){if(!await QS(e,t)||!await on())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 GI(e,t),e}var FJ=3e3;function WI(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 NJ(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 WI(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function HI(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function qJ(e,t){throw N("buildPresentationTemplatePdfUrl")}function GJ(e,t){throw N("buildPresentationTemplateImageUrl")}function VI(e,t){return`${HI(e)}/presentation/convert-to-${t}`}async function WJ(e,t,n,r){let s=VI(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 zJ(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 YJ(e){return e==="unreachable"}function JJ(e){return!e||e.status===0?"unknown":e.ok&&u_(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var zI=1e4,QJ={connection:"unknown",faultSinceMs:null};function XJ(e,t,n,r=zI){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 XS({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<Sa,l=!!t&&i-t.atMs<wa;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<=Pa,streamFresh:!!s&&i-s.atMs<=tr,inboxFresh:!!n&&i-n.atMs<=xa,activityFresh:!!o&&i-o.atMs<=tr}}function Qt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function ka(e,t,n){if(!t)return!1;let r=Qt(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=Qt(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function YI(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"&&!ka(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function JI(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,l=i?s.turns.filter(g=>!ka(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:Qt(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function QI(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 XI(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:Qt(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 ZS(e){let t=XS(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=YI(e,t,s,o);if(i)return i;let{result:a,openTurn:l}=JI(e,t,s,o);return a??QI(e,t,o)??XI(e,t,l,o)}var Sa=6e4,Pa=45e3,tr=45e3,xa=1e4,lQ=3e3,wa=15e3;function uQ(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function pQ(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 gQ(e){return ZS(e)}function mQ(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,l=[null,t?t.atMs+Sa:null,n?n.atMs+wa:null,r?r.atMs+xa:null,s?s.atMs+Pa:null,o?o.atMs+tr:null,i?i.atMs+tr:null],p=null;for(let d of l)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function ZI(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||Gs({name:s.name??void 0,message:s.message})?null:s}var eE="SandboxMemoryGuard";function _Q(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=ZI(e,t);if(r?.message){if(r.name!==eE)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 SQ=6e4;function PQ(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function xQ(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var tE=9e4;function wQ(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+tE}var vQ=75e3,AQ=2,RQ=2e4;function eP(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function CQ(e){return e.filter(t=>t!=null).join("|")}function nE(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function TQ(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...eP(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...eP(),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=nE(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 rE={"retry-start":"retrying",restart:"restarting"};function IQ(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${rE[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function sE(e){return e===1?"once":e===2?"twice":`${e} times`}function EQ(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 ${sE(t)}`),`Tried: ${r.join(", then ")}.`}var OQ={"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 oE(e){return!!(e.metadata??{}).legacy_migration}function jQ(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 oE(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function DQ(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 LQ={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 $Q(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function va(e){return e.runtime_sessions??e.opencode_sessions??[]}function iE(e){let t=va(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 FQ(e){let t=iE(e);return t?va(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 NQ(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=>va(r).some(s=>s.id===t))??null)}var aE=new Set;function cE(e){for(let t of[...aE])try{t(e)}catch{}}var oP={schema:ue,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var iP=e=>Object.values(e.ext??{}).find(t=>t.version===Te),aP=e=>!!e&&iP(e)!==void 0,cP=e=>{let t=iP(e);return t?t.native_id??null:e.thread_id};function lP(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:cP(t),hasMessages:n,empty:!n&&e.older[t.thread_id]===!1}}var tP=new WeakMap;function uP(e,t){let n=cP(e),r=tP.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=ls({...oP,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return tP.set(t,{native:n,rows:o}),o}var Aa=e=>e.info.time?.created;var lE=(e,t)=>(Aa(e)??-1/0)-(Aa(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var nP=new WeakMap,rP=new WeakMap,pP=e=>typeof e=="object"&&e!==null,uE=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,pE=e=>e.info.role==="user"&&e.parts.some(t=>pP(t)&&t.type==="compaction"),dE=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},sP=new WeakMap;function gE(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(!pP(p)||a.type==="compaction")return a;let d=`${s}|${l}|${a.id}`,g=sP.get(p);return g&&g.key===d?(o=!0,g.block):(sP.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function mE(e){let t=new Map,n=new Set;for(let r of e){if(!pE(r))continue;let s=e.find(o=>!n.has(o)&&dE(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function fE(e,t,n,r,s){let o=nP.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=us({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=gE(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 nP.set(n,p),p}function yE(e,t,n){let r=rP.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(lE),{paired:o,used:i}=mE(s),a={tool_input:0,cut_point:0,attachment:0},l=[];for(let m of s){if(i.has(m))continue;let f=fE(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=uE(s.map(Aa).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=l.filter(m=>m.role==="user"&&m.kind==="turn"),g={...oP,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:ue,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:Te,native_id:t}}}]};return rP.set(n,{sessionId:e,native:t,log:g}),g}var Ra=new WeakMap,Xt=new WeakMap,dP=new WeakMap;function zs(e){let t,n=Xt.get(e);return n&&(t=hE(n).get(e.id)),t?(Ra.set(t,e),t):(e.type!=="harness"?t=si(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=dP.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},dP.set(e,t)),t&&Ra.set(t,e),t)}var nr=e=>Ra.get(e),wt=e=>e.flatMap(t=>zs(t)??[]),gP=new WeakMap;function hE(e){let t=gP.get(e);return t||gP.set(e,t=new Map(at(e)[0]?.parts.map(n=>[n.id,n]))),t}var mP=new Map;function at(e){let t=mP.get(e.thread_id);return t||(t={schema:ue,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},mP.set(e.thread_id,t)),uP(t,e)}var _E="kortix-v1-import",Ca={schema:ue,v:1};function Ys(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var Ta=e=>e.type==="tool_call",bE=e=>e.status==="pending"||e.status==="running",Ia=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function SE(e,t){let n=Ia(e);return!bE(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var fP=new WeakMap;function PE(e,t){let n=fP.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={...Ca,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 fP.set(e,s),s}var yP=new WeakMap;function xE(e){let t=yP.get(e);return t||(t={...Ca,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:[]},yP.set(e,t)),t}var hP=new WeakMap;function wE(e){let t=hP.get(e);return t||(t={...Ca,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:[]},hP.set(e,t)),t}var kE=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function vE(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"||kE(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:wE(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:xE(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 AE(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 RE(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 SP(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=at(n)[0]?.info?.error??n.error.message,s=xe(r),o=Is(r);return{code:n.error.code,message:s?.message||_e(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function CE(e,t,n){return e.length&&e.every(t)?ga(e.flatMap(r=>at(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:Ea(e,n)}function Ea(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 ga(n,t)??null}function TE(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 IE(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&&Ta(n)&&n.name==="bash"?n:null}function EE(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:Ta(i)?js(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var ME=e=>e.assistant.some(t=>t.blocks.some(n=>Ta(n)&&ce(n.name)==="todowrite"&&Kn(n))),OE=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function jE(e,t){let n=e.map(s=>SP(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 _P=new WeakMap,DE=[];function PP(e){let t=Ys(e.messages,n=>n.role==="assistant");return!!t&&Jb(at(t))}var bP=new WeakMap;function LE(e){let t=bP.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},bP.set(e,t)}return t}function Ma(e,t={}){let n=t.hideOutOfContext?LE(e):e,r=new Set(t.held??DE),s=vE(n.messages,r),o=RE(s,t.liveMessageId),{list:i,hint:a}=t.foldCompactions?AE(s,o):{list:s,hint:o},l=Ys(n.messages,_=>_.role==="assistant"),p=PP(n),d=PS({turns:i.map(_=>({userMessage:{info:{id:_.user.message_id}},assistantMessages:_.assistant.map(b=>({info:{time:b.status==="streaming"?{}:{completed:1},error:b.error??void 0}}))})),hintMessageId:a,unrunTurnIds:r}),g=Ys(i,ME)??i[i.length-1],m=i.map(_=>!_.partial&&OE(_.user)),f=jE(i,m),h=aP(n),P=_=>h||_.producer.harness===_E,v=t.threads??[],T=new Set(v.map(_=>_.thread_id));return i.map((_,b)=>{let O=t.busy===!0&&d.workingTurnId===_.user.message_id,y=d.pendingTurnIds.includes(_.user.message_id),w=p&&_.assistant.includes(l),x=f[b],k=`${_.partial}|${O}|${y}|${_===g}|${w}|${x?(x.continued?"c":"")+x.retries:"-"}`,C=_P.get(_.user);if(C&&C.key===k&&C.pricing===t.pricing&&C.heads===t.threads&&C.assistant.length===_.assistant.length&&C.assistant.every((j,q)=>j===_.assistant[q]))return C.turn;let D=_.assistant.flatMap(j=>j.blocks);for(let j of _.assistant)for(let q of j.blocks)Xt.set(q,j);let R=EE(_,D,v,T),L=_.assistant[_.assistant.length-1],le={internal:m[b],autoRetry:x,id:_.user.message_id,user:_.user,assistant:_.assistant,partial:_.partial,continues:_.continues??null,blocks:D,status:w?"streaming":L?L.status:_.user.kind==="compaction"?_.user.status:"pending",error:SP(_),cost:CE([_.user,..._.assistant],P,t.pricing),compaction:TE(_.user),threads:R,plan:_===g,shell:IE(_),response:Ys(D,j=>j.type==="text"&&!!j.text.trim())??null,attachments:_.user.blocks.filter(j=>j.type==="attachment"&&(j.mime.startsWith("image/")||j.mime==="application/pdf")),live:O,queued:y,retrying:w};return _P.set(_.user,{assistant:_.assistant,key:k,pricing:t.pricing,heads:t.threads,turn:le}),le})}var Oa=e=>nr(e);function $E(e,t={}){return hS(fS(wt(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(nr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Oa)}:n.kind==="text"?{kind:n.kind,block:nr(n.part)}:{kind:n.kind,block:Oa(n.part)})}var UE=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:wt(e.blocks)}:{kind:e.kind,part:zs(e.block)};function FE(e,t){let n=new Map(e.map(o=>[UE(o),o])),r=ES([...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 NE(e){if(!te(e)||!Gy(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=qb(e);return(n.answers??jS(n.outputText??"",t.length)??[]).length>0}function BE(e){return lS(wt(e),n=>zn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(NE)?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:nr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Oa),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&&Xt.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function KE(e,t){return wS(wt(e.blocks).map(n=>({part:n})),t?.flatMap(at))}function qE(e){return ua(wt(e))}function GE(e){return iS(wt(e))}function WE(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=zs(n),s=Xt.get(n);return!!r&&we(r)&&pa(r)&&(!s||s.status==="streaming")}):!1}var xP=new WeakMap;function HE(e){if(!Ia(e))return e;let t=xP.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},xP.set(e,t)}return t}function VE(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function zE(e){let t=e.map(se),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=_S(t).map(VE);return ps({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function YE(e,t,n){let r=se(e),s=r.state;return ps({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function JE(e){let t=at(e).map(r=>ta(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 wP=Object.freeze([]),kP=new WeakMap;function QE(e){if(!e)return wP;let t=kP.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&Kn(s)):[]);t=n.length?n:wP,kP.set(e,t)}return t}function XE(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 Ma(e)){let s=Ea([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 ZE="prt_kortix_restore_g";function eM(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(ZE))}function tM(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 ja=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qe=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,nM=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function rM(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=ja(t)?t.restore:void 0;if(!ja(n))return null;let r=ja(n.dropped)?n.dropped:{},s=e.grade_counts,o=[{kind:"message",count:Qe(r.message)},{kind:"attachment",count:Qe(s?.attachment)},{kind:"text",count:Qe(r.text)+Qe(n.truncated)},{kind:"tool_input",count:Qe(s?.tool_input)},{kind:"tool_result",count:Qe(r.tool_result)},{kind:"cut_point",count:Qe(s?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,l])=>nM.has(a)?i:i+Qe(l),0)}];return{generation:Qe(n.generation),missing:o.filter(i=>i.count>0)}}var AP=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function sM(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of AP(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 RP=(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}},oM=(e,t)=>e.map(n=>n.type==="text"?RP(n,t):n),vP=new WeakMap;function iM(e,t){let n=vP.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>AP(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?RP(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:oM(s.result.content,t)}}:s)}:e;return vP.set(e,{texts:t,out:r}),r}var Da=1024*1024;function aM(e){return e.reduce((t,n)=>t+n.bytes,0)>Da?"download":"inline"}function cM(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>Da)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function lM(e,t){if(t.size===0)return e;let n=e.messages.map(r=>iM(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function uM(e){return e==="TIMEOUT"||e==="request_deadline"}function pM(e){let t=TP(e)?e.code:void 0;return typeof t=="string"?t:void 0}var TP=e=>typeof e=="object"&&e!==null;function CP(e){let t=e?.metadata;return!!TP(t)&&t.warm===!0}var dM=5,gM=2e3,mM=e=>new Promise(t=>setTimeout(t,e));async function fM(e,{attempts:t=dM,delayMs:n=gM,sleep:r=mM}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function QX(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 uM(pM(g))?fM(async()=>!CP(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(CP(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 yM=12e4,Js=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},hM=1e3,_M=15e3,IP=100,bM=50,SM=10,Qs=class extends Xn{};async function PM(e){let t=await e.json().catch(()=>null);return t!==null&&typeof t=="object"&&t.retry===!1}function EP(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 PM(l)?new Qs(`session ${l.status}`):new Xn(`session ${l.status}`):new S(`Session synchronization failed: ${l.status}`,{status:l.status});return{messages:await l.json(),nextCursor:l.headers.get("x-next-cursor")||void 0}}}function xM(e){return kM(EP(e))}function wM(e){return new La({...e,loadPage:EP(e)})}async function kM(e){let t=[],n=new Set,r;do{let i=await e({limit:IP,...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 vM={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},La=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??vM,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??yM,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 Js;if(!r&&Gs(n))return;if(r||this.update({freshness:er(n)?"loading":"error"}),n instanceof S&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}if(n instanceof Qs){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(hM*2**this.retryAttempt,_M);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?bM:IP,...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 Js(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<SM&&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 AM=5e3,OP=40,r4=5*6e4,RM=16,rr=new Map;function jP(e,t,n,r=Date.now()){let s=DP(e,t);for(rr.delete(s),rr.set(s,{envelope:n,atMs:r});rr.size>RM;){let o=rr.keys().next().value;if(o===void 0)break;rr.delete(o)}}var MP=new Map;function DP(e,t){return`${e}/${t}`}function CM(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=AM}function LP(e,t,n=Date.now()){if(!e||!t)return null;let r=DP(e,t),s=MP.get(r);return s?CM(s,n)?s.promise:(MP.delete(r),null):null}function $P(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 TM=/(?:\n\n)?Command exited with code (-?\d+)\s*$/;function IM(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=TM.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 UP(e){let t=!1,n=e.blocks.map(r=>{if(r.type!=="tool_call")return r;let s=IM(r);return s!==r&&(t=!0),s});return t?{...e,blocks:n}:e}var FP=Object.freeze({generation:0,session:{},threads:{},messages:{},revs:{},older:{}});function EM(e,t){let n=UP(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 NP(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)!Io(p)||e.revs[p.message_id]!==void 0||(r=EM(r,p));let a={...e.threads};for(let p of t.threads)Eo(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 MM=2e3;async function OM(e,t,n){let r=LP(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??MM,null)})]).finally(()=>clearTimeout(s)):null;return(o&&$P(o))??Lr(e,t,{limit:OP,history:!0,signal:n.signal})}async function jM(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s=dn?await Dp(dn,t,n):null;if(s==="missing")return{envelope:null,empty:!1,log:null};if(s){let i=lP(NP(FP,s));return{envelope:null,empty:!!i?.empty&&i.runtimeSessionId===r&&await BP(t,n,r),log:s}}let o;try{o=await OM(t,n,{})}catch{return{envelope:null,empty:!1}}return jP(t,n,o),KP(o)!==r?{envelope:o,empty:!1}:{envelope:o,empty:await BP(t,n,r)}}async function BP(e,t,n){try{let r=await $r(e,t);return qP({savedEmptyRoot:n,rootSessionId:n,turnRead:!0,hasEndedTurn:r.last_ended!=null,hasOpenOrQueuedTurn:r.turns.length>0})}catch{return!1}}function KP(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function qP(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function h4(e){throw N("buildTunnelEventStreamUrl")}function _4(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:l,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(b,O){o?.(b,O);let y=d.get(b);if(y)for(let w of y)try{w(O)}catch{}}async function P(){if(m)return;let b=new AbortController;g=b,p&&(p.aborted?b.abort():p.addEventListener("abort",()=>b.abort(),{once:!0}));let O=b.signal;try{let y={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(y["Content-Type"]="application/json"),f&&(y["Last-Event-ID"]=f);let w=await fetch(t,{method:r,headers:y,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:O,credentials:"include"});if(!w.ok)throw new Error(`SSE connection failed: ${w.status} ${w.statusText}`);if(!w.body)throw new Error("SSE response has no body");i?.();let x=w.body.getReader(),k=new TextDecoder,C="",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)},le=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}),le(!1)}m||(C+=k.decode(),le(!0),l?.())}catch(y){if(m||y instanceof DOMException&&y.name==="AbortError")return;a?.(y instanceof Error?y:new Error(String(y)))}}function v(){m=!0,g?.abort(),g=null,d.clear()}function T(b,O){let y=d.get(b)??new Set;y.add(O),d.set(b,y)}function _(b,O){d.get(b)?.delete(O)}return{connect:P,close:v,addEventListener:T,removeEventListener:_}}function b4(e,t){throw N("createTunnelEventStream")}var GP="/_kortix/viewer",Xs=6e4,Zt=new Map;function DM(){Zt.clear(),sr.clear()}async function LM(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 WP(e={}){let t=e.path??GP,n=e.fetch??((o,i)=>fetch(o,i)),r=Zt.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=LM(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-Xs:Date.now()+Xs;return Zt.set(t,{session:o,expiresAt:a}),o});return Zt.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function $M(e={}){let t=e.path??GP;return Object.assign(async()=>(await WP(e))?.access_token??null,{invalidate:n=>{let r=Zt.get(t);r&&!r.inflight&&r.session?.access_token===n&&Zt.delete(t)}})}var sr=new Map;async function UM(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 sr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-Xs:Date.now()+Xs}),r.token}catch{return null}}function HP(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=sr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=UM(n,r).then(a=>(a===null&&sr.delete(n),a));return sr.set(n,i),i}}function FM(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:`${pe(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:HP({audience:e,fetch:t.fetch})}}var kt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},be=e=>typeof e=="string"&&e.length>0?e:null;function VP(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 Ua(e){if(!e||typeof e!="object")return null;let t=e,n=be(t.sub)??be(t.subject)??be(t.user_id)??be(t.userId);return n?{userId:n,email:be(t.email),name:be(t.name),picture:be(t.picture)??be(t.pictureUrl),groups:VP(t.groups),groupIds:VP(t.group_ids??t.groupIds),role:be(t.role),accountId:be(t.account_id)??be(t.accountId),projectId:be(t.project_id)??be(t.projectId)}:null}function NM(e,t={}){let n=Ua(e);if(!n)throw new kt("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 kt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new kt("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var BM=60,$a=new Map;function YP(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 zP(e){return JSON.parse(new TextDecoder().decode(YP(e)))}async function KM(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=$a.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(()=>$a.delete(e)),$a.set(e,n)),n}return JSON.parse(e)}async function qM(e,t={}){let n=b=>{throw new kt("unauthenticated",`Kortix sign-in token refused: ${b}.`)},r=t.jwks??et("KORTIX_AUTH_JWKS"),s=t.issuer??et("KORTIX_AUTH_ISSUER"),o=t.audience??et("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=zP(a),g=zP(l)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await KM(r,t.fetch??((b,O)=>fetch(b,O)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(b=>b.kty==="EC"&&(d.kid===void 0||b.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${l}`),P;try{P=YP(p)}catch{return n("malformed")}let v=!1;for(let b of f)try{let{kid:O,alg:y,use:w,key_ops:x,...k}=b,C=await crypto.subtle.importKey("jwk",k,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},C,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+BM<T)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let b=g.aud;if(!(b===o||Array.isArray(b)&&b.includes(o)))return n("wrong audience")}let _=Ua(g);return _||n("no subject")}function JP(e){let t=e.agents.map(GM),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 GM(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 QP(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>ui(n?{...r,mode:null}:r))}function WM(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=QP(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 HM=JP;function XP(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Fa(e){return{providerID:"kortix",modelID:e}}function or(e,t){return Fa(e.startsWith("kortix/")?e.slice(7):e)}var ZP=[{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 Na(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function zM(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function ex(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 ir(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 tx(e){return e.reduce((t,n)=>{let r=Na(n)??0,s=Na(t)??0;return r!==s?r>s?n:t:ir(n.id)>ir(t.id)?n:t})}function Ba(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of ex(e,zM)){let a=[...ex(o,p=>p.family||p.id).values()].map(tx),l=a.filter(p=>{let d=Na(p);return d!==null&&Math.abs(n-d)<r});for(let p of l.length>0?l:[tx(a)])s.add(p.id)}return s}function Ka(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=>ir(r.id)>0)?n.filter(r=>ir(r.id)>0):n}var nx={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:[]},rx=[...ZP,{id:nx.id,env:nx.env}],YM={"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 sx(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var JM=(()=>{let e=new Map;for(let{id:n,env:r}of rx)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=>sx(o)===n)??s[0])}return t})();function ox(e){let t=YM[e.id];if(t)return t;let n=e.env??[],r=n.length===1?JM.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[sx(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}var QM=["low","medium","high"];function ix(e){if(!e)return{temperature:!1,topP:!1};let t=e.reasoning_options?.find(a=>a.type==="effort"),n=e.reasoning_options?.find(a=>a.type==="budget_tokens"),r=t?.values?.length?{values:t.values}:n?{values:[...QM]}:void 0,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 ax=rx;var $4=ax.map(e=>({id:e.id,authRequirement:ox(e)})),cx=new Set(["kortix"]);function XM(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=ix({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 ZM(e){return e.modelPicker?XM(e.modelPicker):void 0}function eO(e){return"capabilities"in e&&e.capabilities!=null}function qa(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1&&n.available!==!1}function tO(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)&&cx.has(o.id))for(let[i,a]of Object.entries(o.models)){if(i==="auto"||i==="kortix/auto")continue;let l;if(eO(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:XP({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 lx(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var px="kortix",ux="codex";function dx(e){return e.providerID===px&&!e.modelID.includes("/")}function nO(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function en(e){return dx(e)}function rO(e){return Ba(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function sO(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=rO(e.catalogModels),s=lx(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===px){let d=nO(i.modelID,i.provider),g=d===ux?t?.has(ux)??!1:t?.has(d)??!1;if(dx(i))return!n;if(!g)return!1;if(l==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return en(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return en(i)}catch{return en(i)}return!1}if(l==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return en(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return en(i)}catch{return en(i)}return!1}}function oO(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 iO(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?Fa(r):void 0}function aO(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 cO=new Set(["explicit","repointed","fallback"]);function lO(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:or(n),from:or(r),reason:typeof o=="string"?o:"other",atMs:s}}function uO(e,t){return!t||(e??-1)>=t.atMs}function pO(e){let t=e.session?Br(e.session):null,n=t?or(t):void 0,r=e.session?.metadata;return(cO.has(String(r?.opencode_model_source))||r?.opencode_model_restored===!0?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(i=>!!i)}function dO(e){let{models:t,providers:n}=e,r=l=>qa(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 Ka(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}}export{fI as ABORT_REASONS,iY as ABORT_REASONS_NOT_YET_EMITTED,sc as ACCOUNTS_LIST_UNAVAILABLE_CODE,Ws as ACTIVE_INSTANCE_COOKIE,rc as ANALYTICS_UNAVAILABLE_CODE,LI as ATTACHMENT_PART_REF_PREFIX,S as ApiError,ie as AuthError,ut as BillingError,oW as CAPTURE_DEVICE_DEFAULTS,tW as CAPTURE_EXCLUSION_GROUPS,rW as CAPTURE_FRAME_INTERVALS_MS,eW as CAPTURE_LAYERS,sW as CAPTURE_MAX_HEIGHTS,nW as CAPTURE_RETENTION_LIMITS,zI as CONNECTION_FAULT_GRACE_MS,MI as CONNECTOR_POLL_FIRST_DELAY_MS,OI as CONNECTOR_POLL_INTERVAL_MS,jI as CONNECTOR_POLL_WINDOW_MS,HR as CONTEXT_TOOLS,vS as COST_MARKUP,ko as ConnectorApprovalPendingError,Ar as ConnectorCallError,vo as ConnectorPageLimitError,VR as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,nB as DEFAULT_NOTIFICATION_PREFERENCES,yb as DEFAULT_TRANSCRIPT_OPTIONS,CI as DESTRUCTIVE_PHASES,tn as FEATURE_DISABLED_CODE,nj as FEATURE_FLAG_KEYS,Za as FEATURE_NOT_SUPPORTED_CODE,xt as FILE_VERBS,In as FileExistsError,hn as HeadlessAuthError,Hs as HostBoundaryError,Tx as IMPERSONATION_HEADER,tB as INBOX_NOTIFICATION_KINDS,xa as INBOX_OBSERVATION_MAX_MS,QJ as INITIAL_SETTLED_CONNECTION,yI as INSTANCE_SCOPED_ROUTES,Aw as KNOWN_TOOL_KINDS,Te as KORTIX_TRANSCRIPT_SCHEMA,kt as KortixMemberError,dw as MAX_PROMPT_ATTACHMENTS_BYTES,Ro as MAX_PROMPT_ATTACHMENT_BYTES,Ju as MAX_PROMPT_ATTACHMENT_FILES,Uz as MEMORY_VERBS,ec as MODEL_NOT_SERVABLE_CODE,ov as NO_GROUP_ACTIVITY_TOOLS,wa as OPTIMISTIC_ABORT_MAX_MS,SQ as OPTIMISTIC_COMPACTION_MAX_MS,Sa as OPTIMISTIC_RECEIPT_MAX_MS,hJ as PERSISTED_QUERY_CACHE_VERSION,gT as PLUMBING_TOOLS,FJ as PREVIEW_PROBE_TIMEOUT_MS,Z as PROJECT_ACTIONS,PL as PROJECT_SESSION_NAME_LOOKUP_LIMIT,SL as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,Vw as PROJECT_SESSION_PAGE_MAX_LIMIT,tc as PROVISION_IN_FLIGHT_CODE,Jx as PROVISION_STREAM_UNTERMINATED_CODE,No as PublicSessionShareError,ur as REPOSITORY_DISCONNECTED_CODE,l0 as REVIEW_CONTROL_ACTIONS,bY as RUNTIME_NOT_READY_MARKERS,mB as RUNTIME_PERMISSION_CAPABILITIES,gB as RUNTIME_PERMISSION_REPLIES,vt as RequestTooLargeError,vn as RuntimeNotReadyError,Fi as SANDBOX_FS_ROOTS,tt as SANDBOX_PORTS,nc as SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE,tE as SERVER_COMPACTION_REVALIDATE_MS,Pa as SERVER_OBSERVATION_MAX_MS,OQ as SESSION_LIST_STATUS,Da as SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES,Se as SESSION_LOG_MINOR,ue as SESSION_LOG_SCHEMA,LQ as SESSION_NOTICE,iv as STANDALONE_TOOLS,tr as STREAM_OBSERVATION_MAX_MS,Xn as SandboxNotReadyError,Kt as SessionNotReadyError,jo as SessionStartError,a0 as TRIGGER_CONTROL_ACTIONS,lQ as TURN_END_LEDGER_LAG_MS,Ek as TURN_ERROR_CODES,RQ as WAKE_ESCALATION_COOLDOWN_MS,AQ as WAKE_MAX_RESTARTS,vQ as WAKE_NO_PROGRESS_MS,Ci as WIRE_ID_BACKDATE_MS,ht as WIRE_ID_CLOCK_TOLERANCE,st as WIRE_ID_TIME_MASK,xn as WIRE_ID_TIME_SCALE,Rv as WIRE_MESSAGE_ID,mO as __getConfigResolver,gO as __setConfigResolver,aY as abortErrorReason,po as acceptAccountInvite,Cc as acceptAccountInviteAndLand,gg as acceptEnterpriseOffer,QY as acceptInvite,Yx as accountInviteLanding,Lm as actReviewItem,tu as activateConnection,su as addComputerToProject,cm as addGroupMembers,Mf as addMarketplaceSource,sf as addRoomPerson,nf as addRoomSession,TQ as advanceWakeEscalation,CC as allDescendantIds,AJ as appendPreviewToken,ob as approveCaptureDeviceGrant,W_ as approveCaptureEnrollment,FF as approveCliDevice,cl as approveProjectAccessRequest,dq as approveTask,wr as archiveProject,Sq as assignTicket,_l as attachGroupToProject,xi as authMfa,bi as authUser,U as authenticatedFetch,Cr as authenticatedRequest,$J as authorizePreviewUrl,c as backendApi,O$ as bindSlackIdentity,j$ as bindTeamsIdentity,Il as brokerProjectSecretRequest,SJ as browserKeyValueStorage,_I as buildInstancePath,GJ as buildPresentationTemplateImageUrl,qJ as buildPresentationTemplatePdfUrl,YS as buildPreviewAuthEndpoint,nJ as buildPublicTemplateUrl,VI as buildRuntimePresentationConversionUrl,Bu as buildSandboxTemplate,FC as buildScrapeFailureResults,r1 as buildStaticFileHealthPreviewUrl,n1 as buildStaticFileLocalUrl,t1 as buildStaticFilePreviewUrl,VA as buildStaticFileServicePath,h4 as buildTunnelEventStreamUrl,c1 as buildWebProxyUrl,$m as bulkActReviewItems,O0 as bulkDeletePolicies,j0 as bulkImportPolicies,ua as burstSummary,hT as burstSummaryLabel,iS as burstWorkLabel,Et as callConnector,tk as canManageBilling,f$ as canOfferTopup,rF as cancelAccountDeletion,kc as cancelAccountInvite,FY as cancelSandbox,y2 as cancelSandboxUpdate,ig as cancelScheduledChange,rg as cancelSubscription,pW as captureHealthBucket,mk as changeRequestControlsFrom,D2 as checkAccessEmail,pD as checkMcpServerSignIn,LH as childMapByParent,w2 as claimComputer,uR as claimNext,S$ as claimPerSeatBilling,Yp as claimWarmProjectSession,Gb as classifyPart,WI as classifyPreviewProbeStatus,jv as classifyPtyClose,JE as classifySessionLogMessage,ta as classifyTurn,QH as cleanErrorMessage,rV as cleanResultSnippet,Tz as cleanWorkerOutput,ic as clearImpersonationSession,DM as clearKortixAppViewerCache,Fd as clearModelDefault,YD as clearSessionFresh,mp as closeChangeRequest,zq as closeMilestone,KH as collectTurnParts,xq as commentTicket,hp as commitSessionChanges,xQ as compactionExpiryAtMs,EV as compactionTurnInfo,sa as compareForDisplayAt,DH as compareMessagesForDisplay,hW as compareSemver,pR as completeInFlight,kg as completeSlackInstall,vg as completeTeamsInstall,QP as composerSelectableAgents,xS as computeStatusFromPart,ug as configureAutoTopup,to as configureKortix,tg as confirmCheckoutSession,Mg as connectEmail,Pg as connectSlack,U$ as connectTelegram,JJ as connectionFromHealth,YJ as connectionIsFaulted,Qj as connectionSharedWithEveryone,iw as connectorConnect,aw as connectorFinalize,cJ as connectorHeadline,mg as contactEnterpriseSales,_V as contextLabelForTool,JW as contextToolSummary,QW as contextToolTrigger,bF as convertPresentationToGoogleSlides,WJ as convertRuntimePresentation,xs as copyFile,yg as costExportUrl,pQ as countLiveInboxPrompts,n0 as countReviewItemsBySegment,gc as createAccount,Pf as createAccountAuditWebhook,Ul as createAccountSecretResource,lf as createAccountToken,Df as createApp,qf as createAppAccessSession,Wf as createAppDeployment,Uf as createAppToken,ay as createAppVolume,py as createAppVolumeSnapshot,bV as createArtifactKind,Cm as createAssignment,MU as createAuditWebhook,t2 as createBackup,K_ as createCaptureEnrollmentToken,eg as createCheckoutSession,_u as createConnector,oJ as createConnectorLinkInfoCache,Ps as createFile,Jg as createGatewayKey,sm as createGroup,wM as createHttpSessionSyncController,S2 as createInstance,iR as createKortix,Th as createKortixPty,ki as createKortixSession,eN as createMarketplaceInstallSession,Hq as createMilestone,sO as createModelVisibility,wm as createOAuthClient,b$ as createPerSeatCheckout,bJ as createPersistedQueryCache,I0 as createPolicy,ng as createPortalSession,Fc as createProject,Mq as createProjectAgent,mf as createProjectCliToken,Nc as createProjectRepo,xl as createProjectResourceGrant,Lt as createProjectSession,Hc as createProjectSkill,_d as createProjectTrigger,C_ as createPromptAttachmentController,fm as createRole,Jm as createRoom,_4 as createSSEStream,MY as createSandbox,Fm as createSandboxShare,Uu as createSandboxTemplate,oL as createSavedCopyStore,G0 as createScimToken,kU as createServiceAccountApi,Ur as createSessionPrompt,Hp as createSessionPublicShare,cR as createSessionQueue,Gm as createSessionReminder,lU as createSsoGroupMapping,lq as createTask,hq as createTicket,b4 as createTunnelEventStream,QX as createWarmSessionPool,Mp as currentSavedCopyStore,Tc as declineAccountInvite,XY as declineInvite,sF as deleteAccountImmediately,Bl as deleteAccountSecretResource,$f as deleteApp,Qf as deleteAppDeployment,jU as deleteAuditWebhook,r2 as deleteBackup,xu as deleteConnector,Cu as deleteConnectorCredential,tG as deleteCredential,ns as deleteCustomLlmProvider,IN as deleteDriveFile,Rh as deleteEnv,Ht as deleteFile,zg as deleteGatewayBudget,sl as deleteGitHubInstallation,im as deleteGroup,P2 as deleteInstance,Bq as deleteKortixProject,Jq as deleteMilestone,Am as deleteOAuthClient,Dl as deletePersonalProjectSecret,M0 as deletePolicy,jq as deleteProjectAgent,Ml as deleteProjectProviderOAuth,wl as deleteProjectResourceGrant,kr as deleteProjectSecret,id as deleteProjectSession,Sd as deleteProjectTrigger,un as deletePromptAttachment,_m as deleteRole,Nu as deleteSandboxTemplate,AU as deleteServiceAccountApi,ed as deleteSessionPrompt,Ko as deleteSessionReminder,zm as deleteSessionReminders,uU as deleteSsoGroupMapping,aU as deleteSsoProvider,gq as deleteTask,wq as deleteTicket,ib as denyCaptureDeviceGrant,H_ as denyCaptureEnrollment,Rc as describeAccountInvite,bo as describeConnectorTool,ry as destroyAppMachine,ly as destroyAppVolume,Sl as detachGroupFromProject,qA as detectLocalhostUrls,FQ as directSubsessions,vU as disableServiceAccountApi,Og as disconnectEmail,fJ as disconnectGitHubApp,Rg as disconnectSlack,N$ as disconnectTelegram,tD as discoverConnectionOAuth2,nD as discoverConnectionOAuth2Resource,bu as discoverConnectorAuth,LY as discoverLocalSandbox,kN as dismissDriveConflict,eJ as downloadAccountAudit,AN as downloadDriveFile,fG as dropClientForUrl,_G as dropPublicClientForUrl,fR as editQueued,td as editSessionPrompt,lR as enqueue,Iq as ensurePmSession,GI as ensurePreviewSessionCookie,Xj as ensureProjectConnectorConnection,RI as ensureSandbox,zp as ensureWarmProjectSession,Mv as env,yi as exchangeCode,oy as execInApp,bf as exportAccountAudit,xe as extractGatewayErrorDetails,Qn as extractInstanceRoute,BT as extractSkillBaseDir,Xz as extractSkillContent,UT as extractSkillFiles,Ez as extractWorkerPreview,dR as failInFlight,ez as fallbackBusyRowAfterTurnId,Vn as familyForTool,Va as featureDisabledKey,Qy as featureFlags,y$ as fetchAccountStateWithToken,QO as fetchAccountsWithToken,kJ as fetchAttachmentPart,T$ as fetchCostExportCsv,WP as fetchKortixAppViewer,Vu as fetchProjectArchive,DD as fetchProjectFileRaw,gj as fetchProjectsForAccountWithToken,Yy as fetchSessionAttachment,fA as fileDownloadRequest,Dz as filePhase,jz as fileVerb,CA as files,Vo as finalizeAppArtifact,K2 as finalizeConnectorSetupLink,wL as findActiveTranscriptShare,bs as findFiles,qH as findLastTextPart,DB as findSessionAttachments,Ss as findText,wd as fireProjectTrigger,$u as fixSandboxWithAgent,tO as flattenModels,FV as flattenThought,gy as forkAppVolume,Ya as formatBillingErrorForUI,fz as formatCost,kS as formatDuration,XH as formatJsonFailureOutput,KV as formatMessageDay,qV as formatMessageExact,PY as formatOpenCodeRuntimeError,nV as formatRawOutput,AI as formatRuntimeError,yz as formatTokens,xR as formatTranscript,sz as freshSendHint,aR as generateSessionId,mc as getAccount,hf as getAccountAuditActivity,OL as getAccountAutomations,yc as getAccountBranding,tF as getAccountDeletionStatus,Vd as getAccountState,zd as getAccountStateMinimal,SI as getActiveInstanceIdFromCookie,dF as getAdminProviderAnalytics,lF as getAdminProviderDistribution,mF as getAdminProviderFallback,oF as getAdminRole,tC as getAgentCardLabel,a$ as getAgentConfig,Dq as getAgentPersona,g2 as getAllVersions,WH as getAnsweredQuestionParts,Wo as getApp,Nf as getAppAccess,Ff as getAppAuthEnv,Vf as getAppDeployment,zf as getAppDeploymentLogs,JF as getApprovalLink,on as getAuthToken,Gj as getAuthTokenWithRetry,lg as getAutoTopupSettings,_$ as getAutoTopupSetupStatus,Qd as getBillingCreditBreakdown,Zd as getBillingTierConfigurations,Jd as getBillingTransactionsSummary,Xd as getBillingUsageHistory,rb as getCaptureAssetUrl,nb as getCaptureChunkMedia,Z_ as getCaptureDays,sb as getCaptureDeviceGrant,tb as getCaptureFrame,V_ as getCapturePolicy,Y_ as getCaptureStorage,Q_ as getCaptureTimeline,X_ as getCaptureTimelineItems,ab as getCaptureWorkspace,lp as getChangeRequest,up as getChangeRequestDiff,pp as getChangeRequestMergePreview,gH as getChildSessionError,js as getChildSessionId,mH as getChildSessionToolParts,_t as getClient,He as getClientForUrl,Au as getConnectStatus,eD as getConnectionOAuth2Application,aD as getConnectionOAuth2Status,cD as getConnectionPolicies,q2 as getConnectorAppForm,an as getConnectorCatalog,fu as getConnectorConfig,gu as getConnectorPolicies,N2 as getConnectorSetupLink,C$ as getCostSummary,bI as getCurrentInstanceIdFromPathname,pY as getCurrentInstanceIdFromWindow,s_ as getCurrentProject,Gd as getDefaultAccountState,hH as getDiagnostics,eC as getDirectory,wo as getDiscoverConnector,fD as getDiscoverIntegration,fy as getDriveFileUrl,Ig as getEmailInstallation,Eg as getEmailMode,KU as getEnterpriseDemo,_s as getFileStatus,Lb as getFileWithDir,ZR as getFilename,bN as getFolderAccess,TI as getFullChangelog,qg as getGatewayBreakdown,Hg as getGatewayBudgets,Wg as getGatewayErrors,Yg as getGatewayKeys,Ng as getGatewayLog,Bg as getGatewayOverview,Dg as getGatewayRoutingPolicy,Kg as getGatewaySeries,Gg as getGatewaySessions,pJ as getGitHubAppStatus,Jc as getGitHubInstallation,_F as getGoogleAuthUrl,rm as getGroup,pH as getHiddenToolParts,Mx as getImpersonationSession,JY as getInvite,b2 as getJustavpsServerTypes,Uq as getKortixProject,Fq as getKortixProjectBySession,Mh as getKortixPtyWebSocketUrl,d2 as getLatestSandboxVersion,J2 as getMaintenanceConfig,ol as getManagedGitBackend,aj as getManagedGitStatus,Tf as getMarketplaceCatalogItem,If as getMarketplaceCatalogItemFile,Y0 as getMfaRequired,Gq as getMilestone,gb as getMobileClientPolicy,$d as getModelDefaults,pb as getMyCaptureFrame,ub as getMyCaptureTimeline,xy as getNotificationPreferences,xm as getOAuthClient,U2 as getOAuthConsentRequest,hY as getOpenCodeConfigInvalidError,cH as getPartText,_U as getPatPolicy,_H as getPermissionForTool,Tt as getProject,Lq as getProjectActivity,sp as getProjectCommit,op as getProjectCommitDiff,br as getProjectDetail,my as getProjectDrive,ip as getProjectFileHistory,Pj as getProjectGitConnectionState,Uc as getProjectGitToken,FN as getProjectGoalFiles,Sr as getProjectLlmCatalog,sj as getProjectLlmCatalogProviders,Xr as getProjectModelAccess,Pr as getProjectModelPicker,ij as getProjectQuota,Rr as getProjectSandboxHealth,lj as getProjectSandboxProviderTransition,Dr as getProjectSession,ld as getProjectSessionConfigState,dd as getProjectSessionScope,ag as getProrationPreview,IY as getProviders,s1 as getProxyBaseUrl,hG as getPublicClientForUrl,O2 as getPublicMarketplaceItem,j2 as getPublicMarketplaceItemFile,z2 as getPublicResponse,CF as getPublicSessionShare,TF as getPublicSessionShareMessages,V2 as getPublicShareByToken,rJ as getPublicTemplate,bH as getQuestionForTool,Y$ as getReferralCode,X$ as getReferralStats,hz as getRetryInfo,_z as getRetryMessage,jm as getReviewItem,Om as getReviewSummary,gm as getRolePermissions,mm as getRoleUsage,Qm as getRoom,ya as getRuntimeConfigInvalidError,i2 as getSSHConnection,EY as getSandbox,OY as getSandboxById,vY as getSandboxPortUrl,k2 as getSandboxProvisionStatus,v2 as getSandboxProvisionStreamUrl,p2 as getSandboxUpdateStatus,BS as getSandboxUrl,Fe as getSandboxUrlForExternalId,W2 as getSecretSetupLink,Ni as getServerHealth,sG as getServiceLogs,Jp as getSessionAudit,mz as getSessionCost,Vr as getSessionCostRecord,Pk as getSessionDrives,p_ as getSessionHealth,Xp as getSessionLogPage,fd as getSessionMessageAuthors,yd as getSessionModelUsage,RL as getSessionOpenBundle,X0 as getSessionOversight,Fp as getSessionParticipants,mU as getSessionPolicy,Gp as getSessionPreviewCandidates,Wl as getSessionProviderSecretPool,Qp as getSessionTranscript,Lr as getSessionTranscriptSync,$r as getSessionTurn,Np as getSessionWatch,Az as getShellModePart,Cg as getSlackChannelFile,Sg as getSlackInstallation,Ag as getSlackManifest,xg as getSlackMode,rU as getSsoProvider,zA as getStaticFileHealthPath,yo as getSupabaseAccessToken,tw as getSupabaseAccessTokenWithRetry,iq as getTask,cq as getTaskStatus,$$ as getTelegramInstallation,rN as getTemplate,fq as getTicket,fH as getToolInfo,Xi as getToolPrimaryArg,wR as getTranscriptFilename,ga as getTurnCost,pz as getTurnError,gz as getTurnErrorDetails,dz as getTurnErrorRawText,kL as getTurnShare,wS as getTurnStatus,fg as getUsageRollup,X2 as getUserRolesWithToken,ap as getVersionDiff,ky as getWebPushPublicKey,lz as getWorkingState,vk as goalHealth,Kl as grantAccountSecretResource,HY as grantSandboxProjectAccess,l$ as grantSecretToAgent,BH as groupMessagesIntoTurns,hS as groupShowSegments,cS as groupSteps,bz as hasDiffs,e1 as hasLocalhostUrls,HA as hasPreviewTarget,Jb as hasRetryingAssistantTurn,rA as heartbeatGapEvent,sd as holdSessionPrompts,tm as humanizeReviewActionPath,Es as humanizeSearchQuery,Bb as humanizeToolName,ac as impersonationHeaders,oU as importSsoProviderFromMetadata,uQ as inboxObservationSupersedes,eP as initialWakeEscalationState,Ie as inputPath,sN as installTemplate,nd as interruptSessionPrompt,ho as invalidateTokenCache,xc as inviteAccountMember,gl as inviteProjectMember,Lc as inviteRepoCollaborator,Gs as isAbortError,Lx as isAdminBypassEnabled,rH as isAgentPart,NA as isAppRouteUrl,lH as isAttachment,$I as isAttachmentPartRef,nn as isAuthFailure,za as isBillingError,sH as isCompactionPart,no as isConfigured,YW as isContextTool,u2 as isDestructivePhase,qP as isEmptyConversation,oi as isEmptyShowPart,JH as isErrorOutput,p1 as isExternalUrl,Ha as isFeatureDisabledError,$b as isFilePart,Ix as isImpersonationSessionLive,lY as isInstanceDetailPath,hI as isInstanceScopedAppPath,a1 as isInternalLocalhostUrl,Hy as isInvisibleActivityPart,Tj as isInviteSent,cz as isLastUserMessage,oE as isLegacyMigratedSession,rj as isManagedGithubProject,Wy as isNoGroupActivityTool,qa as isOfferedModel,_Y as isOpenCodeConfigInvalidError,jw as isPaintableSavedCopy,iH as isPatchPart,_J as isPersistableQueryKey,i1 as isPreviewUrl,YA as isProxiableLocalhostUrl,Gy as isQuestionTool,we as isReasoningPart,bx as isRepositoryDisconnectedError,EC as isRetryableTurnError,PI as isRuntimeConfigInvalidError,kI as isRuntimeNotReadyResponse,u_ as isRuntimeReady,SY as isRuntimeStartingError,er as isSandboxNotReadyError,ui as isSelectableAgent,o_ as isServerReachable,jB as isSessionAttachmentRef,bp as isSessionFresh,eM as isSessionLogRestoreNote,qL as isSessionStartError,vB as isShellActivityTool,LT as isShellMode,Iz as isShortOutput,pB as isShowContentUnavailable,rs as isShowPayloadEmpty,oH as isSnapshotPart,Vy as isStandaloneActivityTool,aH as isStepPart,Vs as isSubdomainPreviewUrl,Je as isTextPart,te as isToolPart,dH as isToolPartHidden,Ty as isTurnErrorCode,zh as isUnderSandboxRoot,u1 as isWebProxyUrl,Tv as isWireIdAheadOf,$M as kortixAppViewerToken,FM as kortixBinding,Uv as kortixPty,HP as kortixToken,aO as latestPromptModel,Mc as leaveAccount,N_ as linkCaptureDevice,nl as linkGitHubInstallation,zc as linkRepository,yf as listAccountAudit,Sf as listAccountAuditWebhooks,wc as listAccountInvites,Pc as listAccountMembers,k0 as listAccountResourceGrants,$l as listAccountSecretResources,yU as listAccountSessions,cf as listAccountTokens,dc as listAccounts,U0 as listActions,uF as listAdminSandboxes,pm as listAgentIdentities,Jl as listAllConnections,Bf as listAppAgents,Hf as listAppDeployments,Zf as listAppMachines,uy as listAppVolumeSnapshots,iy as listAppVolumes,jf as listApps,Rm as listAssignments,DU as listAuditEvents,EU as listAuditWebhooks,e2 as listBackups,Yd as listBillingTransactions,U_ as listCaptureDevices,B_ as listCaptureEnrollmentTokens,G_ as listCaptureEnrollments,cp as listChangeRequests,B$ as listChannelBindings,kq as listColumns,gD as listConnectSections,dD as listConnectToolkits,Yl as listConnections,So as listConnectorAccounts,Su as listConnectorMoves,_o as listConnectorTools,cu as listConnectors,R$ as listCostByProject,Xq as listCredentialEvents,Qq as listCredentials,es as listCustomLlmProviders,xo as listDiscoverConnectors,mD as listDiscoverIntegrations,vu as listDiscoverSections,wN as listDriveConflicts,vN as listDriveFiles,Yo as listDriveFolder,EN as listDriveVersions,vh as listEnv,Cf as listFeaturedMarketplaces,Aq as listFields,On as listFiles,xN as listFolderPrincipals,Fg as listGatewayLogs,Qc as listGitHubInstallations,Zc as listGitHubRepositories,el as listGitHubRepositoryBranches,am as listGroupMembers,h0 as listGroupProjectGrants,nm as listGroups,Nq as listKortixProjectSessions,$q as listKortixProjects,Ch as listKortixPty,Xc as listLinkableGitHubInstallations,il as listManagedGitRepositories,Af as listMarketplaceCatalogItems,Ef as listMarketplaceSources,Rf as listMarketplaces,_0 as listMemberGroups,b0 as listMemberProjectAccess,Wq as listMilestoneEvents,qq as listMilestones,Ac as listMyAccountInvites,Sy as listNotifications,Pm as listOAuthClients,pf as listOAuthGrants,kl as listPendingApprovals,ml as listPendingProjectInvites,Im as listPermissions,wu as listPipedreamApps,ku as listPipedreamSections,T0 as listPolicies,ul as listProjectAccess,al as listProjectAccessRequests,dm as listProjectAgentIdentities,Eq as listProjectAgents,_f as listProjectAudit,np as listProjectBranches,gf as listProjectCliTokens,rp as listProjectCommits,Gu as listProjectDirectory,qu as listProjectFiles,UN as listProjectGoals,hl as listProjectGroupGrants,Mu as listProjectPolicies,El as listProjectProviderOAuth,zr as listProjectReminders,Pl as listProjectResourceGrants,ju as listProjectSandboxTemplates,Ku as listProjectSandboxes,Rl as listProjectSecrets,Dt as listProjectSessions,$p as listProjectSessionsPage,Du as listProjectSnapshots,Cd as listProjectTriggerEventApps,Rd as listProjectTriggerEventTypes,vd as listProjectTriggerRuns,hd as listProjectTriggers,Ct as listProjects,Dc as listProjectsForAccount,E2 as listPublicMarketplaceItems,M2 as listPublicMarketplaces,Z$ as listReferrals,Mm as listReviewItems,um as listRoles,Zm as listRoomMessages,af as listRoomPeople,Ym as listRooms,WY as listSandboxProjectMembers,Um as listSandboxShares,DY as listSandboxes,q0 as listScimTokens,wU as listServiceAccountsApi,rG as listServiceTemplates,nG as listServices,uD as listSessionConnectRequests,hg as listSessionCosts,ON as listSessionDrives,Zp as listSessionPrompts,Hl as listSessionProviderSecretPools,Wp as listSessionPublicShares,qm as listSessionReminders,vl as listSessionsNeedingInput,NF as listSignedInDevices,cU as listSsoGroupMappings,aq as listTaskEvents,oq as listTasks,Cq as listTemplates,yq as listTicketEvents,mq as listTickets,kd as listTriggerRuns,xM as loadHttpSessionHistory,yt as loadPreviewUrlTemplate,Xb as looksLikeError,uV as looksLikeHtml,tV as looksLikeJsonPayload,CN as makeDriveFolder,s0 as mapApiReviewItem,x2 as markInstanceError,Py as markNotificationsRead,tf as markRoomRead,Or as markSessionFresh,Sh as maxWireIdClock,Fz as memoryRelPath,lS as mergeBurstSteps,gp as mergeChangeRequest,BV as messageCreatedAt,xT as messageTime,gF as migrateAdminSandboxProvider,Ti as mintWireMessageId,xh as mintWireMessageIdAbove,$n as mkdir,oO as modelInDefaultView,or as modelRefToKey,Pu as moveConnector,TN as moveDriveFile,oS as narrateFailedStep,Bs as narrateStep,Ns as narrationToolName,sA as narrowChatEvent,Iv as newestWireIdClock,aJ as nextConnectorPollDelay,he as normalizeActivityToolName,mY as normalizeAppPathname,aW as normalizeCaptureAppId,iW as normalizeCaptureDomain,d1 as normalizeExternalInput,ee as normalizeName,Nb as normalizeToolName,cE as notifyHostSignal,dp as openChangeRequest,ji as openEventStream,tJ as openStressTestStream,Eu as paginateConnector,pr as parseBillingError,sV as parseEmbeddedFailure,FB as parseFlagOverride,Zb as parseJsonFailure,As as parseLocalhostUrl,Nz as parseMemoryView,yY as parseOpenCodeErrorPayload,Wz as parsePresentationOutput,l_ as parseProxyHop,jS as parseQuestionAnswersFromOutput,Yz as parseReadOutput,NS as parseRuntimeErrorPayload,UC as parseScrapeInputUrls,NC as parseScrapeOutput,S_ as parseSubdomainUrl,Mz as parseTaskRows,l1 as parseWebProxyUrl,tS as parseWebSearchOutput,oa as partOutcome,Kq as patchKortixProject,qz as patchVerb,ZM as pickerProviderList,hu as pipedreamConnect,iu as pipedreamConnectConnection,Tu as pipedreamFinalize,au as pipedreamFinalizeConnection,I as platformConfig,iD as pollConnectionOAuth2DeviceAuthorization,mo as pollProjectProviderOAuth,ef as postRoomMessage,pg as previewBillingPlan,Ug as previewGatewayRoute,J0 as previewMfaRequired,D$ as previewSlackIdentity,L$ as previewTeamsIdentity,bm as probeEffectivePermission,Sm as probeEffectivePermissions,NJ as probePreviewPort,zu as projectArchiveRequest,PQ as projectCompacting,HM as projectConfigAgentsToOpenCodeAgents,JP as projectConfigAgentsToRuntimeAgents,zJ as projectSessionConnection,NQ as projectSessionForRuntimeId,Od as projectSessionStartSeed,gQ as projectWorking,Bc as provisionProject,oj as provisionProjectStream,mj as provisionProjectWithToken,__ as proxyLocalhostUrl,o1 as proxyUrlToInternal,cg as purchaseCredits,Zj as putConnectionOAuth2Application,ts as putCustomLlmProvider,Is as rawErrorText,NY as reactivateSandbox,sg as reactivateSubscription,Dn as readBlob,yy as readDriveFile,jn as readFile,Ua as readKortixMember,Hu as readProjectFile,jM as readSavedSessionCopy,pa as reasoningIsRunning,Lu as rebuildProjectSnapshot,Ql as reconcileConnection,Xl as reconcileMemberConnection,iG as reconcileServices,$2 as recordPlatformLogout,ia as recoverLinkResults,ad as recoverProjectSession,J$ as refreshReferralCode,_n as refreshSession,Ho as registerAppArtifact,rD as registerConnectionOAuth2Client,hy as registerDeviceToken,aG as registerService,vy as registerWebPushSubscription,ll as rejectProjectAccessRequest,yH as relativizePath,by as releaseDeviceToken,ud as reloadProjectSessionConfig,pd as reloadProjectSessionConfigStream,wf as removeAccountAuditWebhook,bc as removeAccountBrandingAsset,Ic as removeAccountMember,lm as removeGroupMember,Eh as removeKortixPty,Of as removeMarketplaceSource,Vc as removeProjectSkill,mR as removeQueued,of as removeRoomPerson,rf as removeRoomSession,ru as renameConnection,ks as renameFile,jY as renameSandbox,fp as reopenChangeRequest,Yq as reopenMilestone,yR as reorderQueued,vq as replaceColumns,Rq as replaceFields,Yc as replaceProjectRepository,Tq as replaceTemplates,Ad as replayTriggerRun,Sx as repositoryDisconnectedReason,nF as requestAccountDeletion,yp as requestChangesOnChangeRequest,Cj as requestProjectAccess,vf as requestProjectConnector,kf as requestProjectSecret,h$ as requestTopUp,NM as requireKortixMember,vc as resendAccountInvite,yl as resendPendingProjectInvite,Sc as resetAccountBranding,yG as resetClient,$g as resetGatewayRoutingPolicy,hi as resetPassword,bG as resetPublicClient,f2 as resetSandboxUpdateStatus,Al as resolveApproval,WM as resolveComposerAgent,dO as resolveComposerModel,iJ as resolveConnectorStart,iO as resolveModelDefault,xL as resolvePublicShareUrl,pV as resolveScrapeResults,PS as resolveWorkingTurn,m$ as resolvedPlan,ny as restartAppMachine,Fr as restartProjectSession,$Y as restartSandbox,dy as restoreAppVolume,n2 as restoreBackup,MN as restoreDriveVersion,cd as restoreProjectSession,Nl as retryAccountSecretResource,gR as retryFailed,rd as retrySessionPrompt,eG as revealCredential,em as reviewItemTarget,sk as reviewSegmentForStatus,u0 as reviewVerdictAllowed,r0 as reviewVerdictForStatus,ql as revokeAccountSecretResourceGrant,hU as revokeAccountSession,uf as revokeAccountToken,Tm as revokeAssignment,F_ as revokeCaptureDevice,q_ as revokeCaptureEnrollmentToken,eu as revokeConnection,Qg as revokeGatewayKey,df as revokeOAuthGrant,fl as revokePendingProjectInvite,dl as revokeProjectAccess,ff as revokeProjectCliToken,VY as revokeSandboxProjectAccess,Nm as revokeSandboxShare,W0 as revokeScimToken,Vp as revokeSessionPublicShare,St as rewriteLocalhostUrl,Xf as rollbackApp,iE as rootRuntimeSession,Fl as rotateAccountSecretResource,vm as rotateOAuthClientSecret,Ao as runConnector,Xg as runGatewayPlayground,Oj as runProjectProviderOAuthFlow,Wm as runSessionReminder,va as runtimeSessionsOf,IA as runtimeSupports,$v as sanitizePtyChunk,tl as saveGitHubInstallation,KP as savedCopyEmptyRoot,sy as scaleApp,og as scheduleDowngrade,eb as searchCapture,zl as searchConnectorTools,lb as searchMyCapture,Wu as searchProjectFiles,fS as segmentTurn,KB as selectableProjectAgents,gi as sendMagicLink,e0 as sendReferralEmails,wQ as serverCompactionRevalidateAtMs,oG as serviceAction,DQ as sessionConnectionLabel,jQ as sessionListStatus,KE as sessionLogActivityText,YE as sessionLogAnsweredQuestionCall,WE as sessionLogBurstRunning,BE as sessionLogBurstSteps,qE as sessionLogBurstSummary,GE as sessionLogBurstWorkLabel,SE as sessionLogCallStatus,aM as sessionLogFullTextAction,cM as sessionLogFullTextPlan,tM as sessionLogHarnessSwitches,yE as sessionLogOfV1Rows,HE as sessionLogOpenCall,PE as sessionLogPromptMessage,sM as sessionLogReferencedTexts,rM as sessionLogRestoreNotice,PP as sessionLogRetrying,zE as sessionLogShowGroupCall,XE as sessionLogThreadMetrics,$E as sessionLogTurnSegments,Ma as sessionLogTurns,lM as sessionLogWithFullTexts,pO as sessionModelCandidates,lO as sessionModelFallback,Br as sessionModelPin,bL as sessionParentId,uO as sessionPickStands,TL as sessionPromptActions,GL as sessionStartKey,jL as setAccountAutomationsPaused,Gl as setAccountSecretResourceAccess,dY as setActiveInstanceCookie,Dx as setAdminBypass,pF as setAdminProviderDistribution,fF as setAdminProviderFallback,Bd as setAgentScope,dg as setBillingPlan,qj as setBootstrapAuthToken,Kj as setCachedAuthToken,cb as setCaptureEnabled,z_ as setCapturePolicy,J_ as setCaptureStorage,lD as setConnectionPolicies,pu as setConnectorAuthorizationStrategy,Ru as setConnectorCredential,uu as setConnectorCredentialMode,yu as setConnectorName,mu as setConnectorPolicies,yD as setConnectorSecretBinding,du as setConnectorSensitive,nu as setDefaultConnection,cj as setDefaultReasoningEffort,qU as setEnterpriseDemo,Ah as setEnv,Vg as setGatewayBudget,Lg as setGatewayRoutingPolicy,gJ as setGitHubAppFromExisting,mJ as setGitHubAppPat,kO as setImpersonationSession,Q2 as setMaintenanceConfig,F0 as setMemberSuperAdmin,Q0 as setMfaRequired,Ud as setModelDefault,jl as setPersonalProjectSecret,Zr as setProjectModelAccess,QL as setProjectModelEnablement,Wc as setProjectOnboardingComplete,pj as setProjectOnboardingProfile,Ou as setProjectPolicies,Tl as setProjectSecretStrategy,md as setProjectSessionModel,gd as setProjectSessionScope,Up as setProjectSessionSharing,Pd as setProjectTriggersActivation,iL as setSavedCopyStore,qp as setSessionArchived,Z0 as setSessionOversight,Kp as setSessionPinned,Vl as setSessionProviderSecretPool,Bp as setSessionWatch,F$ as setTelegramAllowedUsers,XJ as settleSessionConnection,o2 as setupSSH,ou as shareConnection,SN as shareFolder,vL as shareTurn,AB as shellActivityGroupLabel,$S as shellExitCode,jx as shouldAttachImpersonation,uz as shouldHideResponsePart,Kn as shouldShowToolPart,ZV as shouldSuppressWorkingTurnBusy,_S as showGroupItems,bS as showTurnBusyIndicator,di as signInWithPassword,fi as signInWithProvider,Pi as signInWithSso,wi as signOut,BF as signOutDevice,pi as signUp,eY as skillDocumentPath,Zz as skillInputDir,$H as sortSessions,FE as splitSessionLogTurnWork,ES as splitTurnWork,uH as splitUserParts,Yf as startApp,ey as startAppMachine,sD as startConnectionOAuth2Authorization,oD as startConnectionOAuth2DeviceAuthorization,B2 as startConnectorSetupLink,dJ as startGitHubAppManifest,go as startProjectProviderOAuth,ft as startProjectSession,Dd as startProjectSessionOrThrow,Y2 as startSessionWithToken,pq as startTask,zn as stepLabel,Jf as stopApp,ty as stopAppMachine,Nr as stopProjectSession,UY as stopSandbox,rl as storeGitHubUserToken,Ub as stripAnsi,uY as stripInstancePrefix,pe as stripTrailingSlashes,QE as subAgentCalls,L2 as submitAccessRequest,G2 as submitConnectorAppForm,Z2 as submitDemoRequest,F2 as submitOAuthConsent,Dm as submitReviewItem,H2 as submitSecretSetupLink,vO as subscribeToImpersonation,GO as supabaseClient,lu as syncConnectors,P$ as syncSubscription,SG as systemReload,bt as toDaemonPath,gY as toInstanceAwarePath,JA as toInternalUrl,Mn as toSandboxAbsolutePath,qb as toToolView,Yh as toWorkspaceRelative,ps as toolCallBlock,sv as toolCallError,tv as toolCallMetadata,rv as toolCallRawOutput,nv as toolCallStatus,Zi as toolInfo,ce as toolKind,uI as toolViewModel,dj as transferProject,c0 as triggerControlsFrom,m2 as triggerSandboxUpdate,Ov as triggersRequest,ZI as turnEndCause,_Q as turnEndNotice,GH as turnHasSteps,tz as turnIsConfirmedActive,nz as turnRendersQueued,$Q as turnRetryLabel,Pq as unassignTicket,_y as unregisterDeviceToken,Ay as unregisterWebPushSubscription,PN as unshareFolder,AL as unshareTurn,Yb as untimedAnchorOf,_e as unwrapError,xf as updateAccountAuditWebhook,hc as updateAccountBranding,Ec as updateAccountMemberRole,fc as updateAccountName,c$ as updateAgentConfig,Lf as updateApp,Kf as updateAppAccess,cy as updateAppVolume,OU as updateAuditWebhook,_p as updateChangeRequest,K$ as updateChannelBinding,Zl as updateConnectionCredential,jg as updateEmailPolicy,qc as updateExperimentalFeature,Kc as updateFeatureFlag,om as updateGroup,Ih as updateKortixPty,Vq as updateMilestone,wy as updateNotificationPreferences,km as updateOAuthClient,_i as updatePassword,bU as updatePatPolicy,E0 as updatePolicy,xr as updateProject,pl as updateProjectAccess,Oq as updateProjectAgent,Kd as updateProjectDefaultAgent,bl as updateProjectGroupGrant,Gc as updateProjectSandboxProvider,od as updateProjectSession,bd as updateProjectTrigger,ym as updateRole,hm as updateRolePermissions,Xm as updateRoom,Fu as updateSandboxTemplate,fU as updateSessionPolicy,Bo as updateSessionReminder,Vm as updateSessionReminders,uq as updateTask,uj as updateTemplateWarmPool,_q as updateTicket,bq as updateTicketStatus,Si as updateUserMetadata,_c as uploadAccountBrandingAsset,Gf as uploadAppArtifactArchive,Po as uploadConnectorAttachment,RN as uploadDriveFile,Ln as uploadFile,wA as uploadNativeFile,Mr as uploadPromptAttachment,zy as uploadSessionAttachment,Tg as uploadSlackChannelFile,Cn as uploadTimeoutMsForBytes,Zq as upsertCredential,Ol as upsertProjectGitCredential,Cl as upsertProjectSecret,sU as upsertSsoProvider,$c as validateProjectManifest,Q$ as validateReferralCode,Oc as validateToken,H$ as verifyGatewayProvider,qM as verifyKortixToken,mi as verifyOtp,iU as verifySsoDomain,EQ as wakeEscalationAttemptSummary,IQ as wakeEscalationNote,CQ as wakeProgressFingerprint,qt as wireIdClock,wn as wireIdClockAt,Gt as wireIdClockDelta,wz as workedForLabel,mQ as workingExpiryAtMs,rz as workingTurnDrawsBusyRow,RB as writeActivityGroupLabel,ws as writeFile,Yu as writeProjectFile,aa as wsDomain,lV as wsFavicon,cV as wsRootDomain};
|