@kortix/sdk 0.13.50 → 0.13.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +10 -0
  2. package/dist/core/client/kortix.d.ts +2 -0
  3. package/dist/core/client/kortix.d.ts.map +1 -1
  4. package/dist/core/client/project-core.d.ts.map +1 -1
  5. package/dist/core/client/session-handle.d.ts +1 -0
  6. package/dist/core/client/session-handle.d.ts.map +1 -1
  7. package/dist/core/client/session-lifecycle-security.d.ts +2 -0
  8. package/dist/core/client/session-lifecycle-security.d.ts.map +1 -1
  9. package/dist/core/client/session-lifecycle-security.js +2 -0
  10. package/dist/core/client/session-lifecycle-security.js.map +1 -1
  11. package/dist/core/rest/projects-client/projects.d.ts +4 -2
  12. package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
  13. package/dist/core/rest/projects-client/projects.js +0 -1
  14. package/dist/core/rest/projects-client/projects.js.map +1 -1
  15. package/dist/core/rest/projects-client/sessions.d.ts +29 -0
  16. package/dist/core/rest/projects-client/sessions.d.ts.map +1 -1
  17. package/dist/core/rest/projects-client/sessions.js +6 -0
  18. package/dist/core/rest/projects-client/sessions.js.map +1 -1
  19. package/dist/core/rest/projects-client/tokens.d.ts +21 -0
  20. package/dist/core/rest/projects-client/tokens.d.ts.map +1 -1
  21. package/dist/core/rest/projects-client/tokens.js +9 -0
  22. package/dist/core/rest/projects-client/tokens.js.map +1 -1
  23. package/dist/core/turns/errors.d.ts.map +1 -1
  24. package/dist/core/turns/errors.js +6 -2
  25. package/dist/core/turns/errors.js.map +1 -1
  26. package/dist/kortix.esm.min.js +30 -30
  27. package/dist/kortix.global.js +31 -31
  28. package/dist/react/index.d.ts +1 -0
  29. package/dist/react/index.d.ts.map +1 -1
  30. package/dist/react/index.js +1 -0
  31. package/dist/react/index.js.map +1 -1
  32. package/dist/react/query-keys.d.ts +2 -0
  33. package/dist/react/query-keys.d.ts.map +1 -1
  34. package/dist/react/query-keys.js +2 -0
  35. package/dist/react/query-keys.js.map +1 -1
  36. package/dist/react/use-opencode-sessions/commands.d.ts +1 -1
  37. package/dist/react/use-opencode-sessions/commands.js +1 -1
  38. package/dist/react/use-session-model-usage.d.ts +12 -0
  39. package/dist/react/use-session-model-usage.d.ts.map +1 -0
  40. package/dist/react/use-session-model-usage.js +24 -0
  41. package/dist/react/use-session-model-usage.js.map +1 -0
  42. package/dist/react/use-session-prompts.d.ts +16 -1
  43. package/dist/react/use-session-prompts.d.ts.map +1 -1
  44. package/dist/react/use-session-prompts.js +65 -10
  45. package/dist/react/use-session-prompts.js.map +1 -1
  46. package/package.json +2 -2
@@ -1,24 +1,24 @@
1
- var wy={backendUrl:"",getToken:async()=>null},jr=null,pn=null;function Dv(e){pn=e}function $v(){return pn}function Dr(e,t){t?.global!==!1&&(jr=e)}function R(){return pn?.()??jr??wy}function $r(){return jr!==null||pn?.()!==void 0}function vy(e){return new Promise(t=>setTimeout(t,e))}async function dn(e,t,n){let r=Math.max(1,t?.attempts??1),o=t?.baseDelayMs??0,s=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(s&&n?.(),o>0&&await vy(o)),i=await e(),i)return i;return i}var Ur=12e4;function Ay(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Ks(e,t,n=Ur){let r=e instanceof Request?e.signal:t?.signal;if(Ay(e))return r??void 0;let o=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,o]):r:o}function gn(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var b=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:o,...s}=n;Object.assign(this,s),r&&(this.name=r),o&&(this.stack=o);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},te=class extends b{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},De=class extends b{constructor(t,n,r,o={}){super(r||n.message||`Billing Error: ${t}`,{...o,status:t,detail:n}),this.name="BillingError"}},Ye=class extends b{constructor(t=431,n,r){let o="Request headers are too large";super(r||n?.message||o,{status:t,detail:{message:n?.message||o,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},ky="ENDPOINT_RETIRED";function F(e,t){let n=t?` ${t}`:"";return new b(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:ky})}var Lr="feature_disabled";function qs(e){if(!(e instanceof b)||e.status!==403||e.code!==Lr)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Gs(e){let t=qs(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function Bs(e){let t=qs(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function mn(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 De(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 Ws(e){return e instanceof De}function Hs(e){if(!(e instanceof De))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 le(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function ue(e,t){return new Promise((n,r)=>{let o=()=>{t.removeEventListener("abort",o),r(le())};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o)),t.aborted&&o()})}function fn(e,t){return new Promise((n,r)=>{let o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),r(le())},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.aborted?o():t?.addEventListener("abort",o,{once:!0})})}var Vs="request_deadline",Ry=/^Request exceeded the \d+s server processing deadline$/,zs=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Vs||Ry.test(n),Iy="git_mirror_unavailable",Ty=/^git mirror is temporarily unavailable$/,Cy=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Iy||Ty.test(n);async function Ey(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await ue(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 le();return{message:n,data:r}}function My(e,t,n){return zs(e,t,n)||Cy(e,t,n)||e===501&&t?.code===Qs||e===409&&(t?.code===Xs||t?.code===Js)||e===503&&(t?.code===Zs||t?.code===ei)}async function Ys(e,t,n,r){let{message:o,data:s}=await Ey(e,t),i=new b(o,{status:e.status,response:e,details:s||void 0,data:s,detail:s?.detail,code:zs(e.status,s,o)?Vs:s?.code||s?.error_code||s?.detail?.error_code||e.status.toString()});if(e.status===402&&(i=mn(i)),e.status===403&&s?.code==="account_mfa_required"&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent("kortix:mfa-required"))}catch{}return e.status===431&&(i=new Ye(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&&!My(e.status,s,o)&&R().onError?.(i,r),{error:i,success:!1}}var Oy="X-Kortix-Impersonate",Nr="kortix.impersonation",$e=null,yn=!1,Fr=new Set;function Kr(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function jy(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 Dy(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 ti(){for(let e of Fr)try{e()}catch{}}function $y(){return yn||(yn=!0,$e=Dy(Kr()?.getItem(Nr)??null)),$e&&!jy($e)?(ni(),null):$e}function Hv(e){if(yn=!0,!e){ni();return}$e=e;try{Kr()?.setItem(Nr,JSON.stringify(e))}catch{}ti()}function ni(){yn=!0;let e=$e!==null;$e=null;try{Kr()?.removeItem(Nr)}catch{}e&&ti()}function Vv(e){return Fr.add(e),()=>{Fr.delete(e)}}var Uy=/(^|\/)admin\/(api|analytics)(\/|$)/;function Ly(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Uy.test(t)}function ri(e){if(e!==void 0&&!Ly(e))return{};let t=$y();return t?{[Oy]:t.grantId}:{}}var Br=!1;function Fy(e){Br=e}function Ny(){return Br}function Ky(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function qr(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Pt(e,t,n){let r=t.toLowerCase();for(let o of Object.keys(e))o.toLowerCase()===r&&delete e[o];e[t]=n}function bn(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[o,s]of r.flatMap(Ky))Pt(n,o,s);return n}function Gr(e,t,n){let r={...t},o=R().clientVersion?.trim();o&&!qr(r,"x-kortix-client-version")&&Pt(r,"X-Kortix-Client-Version",o),Br&&Pt(r,"x-kortix-admin-bypass","1");for(let[s,i]of Object.entries(ri(e)))Pt(r,s,i);return qr(r,"authorization")||Pt(r,"Authorization",`Bearer ${n}`),r}async function si(e,t){let n=await hn();if(!n)throw new te;return{headers:new Headers(Gr(e,bn(e,{headers:t}),n)),rejected:()=>R().getToken.invalidate?.(n)}}function qy(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function oi(e,t,n,r,o){if(t instanceof Request){let a=new Headers(Gr(t.url,bn(t,n),r));return e(new Request(t,{headers:a,...o?{signal:o}:{}}))}let s=String(t),i=Gr(s,bn(t,n),r);return e(s,{...n,headers:i,...o?{signal:o}:{}})}async function hn(e){return dn(()=>R().getToken(),e)}async function Qe(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:o=Ur}=n,s=n.fetch??R().fetch??fetch,i=o===null?(e instanceof Request?e.signal:t.signal)??void 0:Ks(e,t,o);if(i?.aborted)throw le();let a=await(i?ue(hn(),i):hn());if(!a)throw new te;let c=r&&!qy(t)&&!qr(bn(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await oi(s,e,t,a,i);if(d.status!==401||!c)return d;R().getToken.invalidate?.(a);let g=await hn({attempts:2,baseDelayMs:200});return!g||g===a?d:oi(s,p,t,g,i)}var ii=()=>R().backendUrl||"",Gy=new Set([502,503,504]),By=e=>Gy.has(e),ai=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Wy=e=>ai(e)||(e??"GET").toUpperCase()==="DELETE",Hy=2,_n=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function he(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:o=3e4,deadlineCoversBody:s=!1,...i}=t,a=new AbortController,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await Vy(e,i,n,r,o,s,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function Vy(e,t,n,r,o,s,i,a){try{if(t.signal?.aborted)throw le();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},o);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Yy(e,t,c,o,s,i,a);if(p instanceof te)return{error:p,success:!1};if(!p.ok)return await Ys(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await ue(p.json(),a.activeController.signal):g?.includes("text/")?d=await ue(p.text(),a.activeController.signal):d=await ue(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return Qy(c,e,t.method,n,r,o,a)}finally{Pn(a)}}function Pn(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function zy(e,t,n){try{await ue(e.arrayBuffer(),t)}catch(r){if(_n(r))throw r}finally{Pn(n)}}async function Yy(e,t,n,r,o,s,i){let a=ai(t.method),c=Wy(t.method),p=c?Hy+1:1,d;for(let g=0;g<p;g++){g>0&&await fn(250*2**(g-1),t.signal??void 0);let m=g===0?s:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await ue(Qe(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 te)return new te;if(i.didTimeout&&_n(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(_n(f)||g===p-1)throw f;continue}if(!a||!By(d.status)||g===p-1)return o||Pn(i),d;await zy(d,m.signal,i)}return d}function Qy(e,t,n,r,o,s,i){Pn(i);let a=_n(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new b("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(ii(),"")||t;c=new b(`Request timed out after ${Math.round(s/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:s})}else e instanceof Error?(c=new b(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(ii(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&R().onError?.(c,o)):(c=new b(String(e)),r&&R().onError?.(c,o));return{error:c,success:!1}}var be=()=>R().backendUrl||"",Qs="feature_not_supported",Xs="model_not_servable",Js="provision_in_flight",Zs="analytics_unavailable",ei="accounts_list_unavailable",dA={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let o=new b(r.message||"Database error",{code:r.code,details:r});return R().onError?.(o,t),{error:o,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new b(n.message,{name:n.name||"ApiError",stack:n.stack}):new b(String(n));return R().onError?.(r,t),{error:r,success:!1}}}};async function Xy(e,t,n={}){let{timeout:r=3e4,fetch:o}=n,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await Qe(`${be()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:s.signal,credentials:"omit"},{timeoutMs:null,fetch:o})}catch(a){if(a instanceof te)return gn();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>he(`${be()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>he(`${be()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>he(`${be()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>he(`${be()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>he(`${be()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>he(`${be()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],he(`${be()}${e}`,{...o,method:"POST",body:t,headers:s})},uploadPut:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],he(`${be()}${e}`,{...o,method:"PUT",body:t,headers:s})},postStream:Xy};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function Wr(e){return e.replace(/\/v1\/?$/,"")}async function Xe(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=Wr(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 ci(){return u(await l.get("/accounts"))}async function li(e){return u(await l.post("/accounts",e))}async function ui(e){return u(await l.get(`/accounts/${e}`))}async function pi(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function di(e){return u(await l.get(`/accounts/${e}/branding`))}async function gi(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function mi(e,t,n,r){let o=new FormData;return o.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,o))}async function fi(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function yi(e){return u(await l.delete(`/accounts/${e}/branding`))}async function hi(e){return u(await l.get(`/accounts/${e}/members`))}async function bi(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function _i(e){return u(await l.get(`/accounts/${e}/invites`))}async function Pi(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function xi(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Si(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function wi(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function vi(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}async function Ai(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function ki(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function Ri(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Ii(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function _A(e){return Xe(e,"/v1/accounts")}async function Ti(){let e=await l.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var vA=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","apps","monitors","reminders","warm_sessions","secrets_egress","pi_worker","pooled_provider_secrets","pi_harness","config_releases","us_region"];async function Je(){return u(await l.get("/projects"))}async function Ei(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function xn(e,t){return u(await l.get(`/projects/${e}`,t))}async function Mi(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Oi(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function ji(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function AA(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function Sn(e,t){let n=u(await l.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function wn(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function vn(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function kA(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Di(e){return u(await l.post("/projects",e))}async function $i(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function Ui(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Ci=200;function Jy(e){let t=e.split(`
1
+ var vy={backendUrl:"",getToken:async()=>null},jr=null,pn=null;function $v(e){pn=e}function Uv(){return pn}function Dr(e,t){t?.global!==!1&&(jr=e)}function R(){return pn?.()??jr??vy}function $r(){return jr!==null||pn?.()!==void 0}function Ay(e){return new Promise(t=>setTimeout(t,e))}async function dn(e,t,n){let r=Math.max(1,t?.attempts??1),o=t?.baseDelayMs??0,s=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(s&&n?.(),o>0&&await Ay(o)),i=await e(),i)return i;return i}var Ur=12e4;function ky(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Ks(e,t,n=Ur){let r=e instanceof Request?e.signal:t?.signal;if(ky(e))return r??void 0;let o=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,o]):r:o}function gn(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var b=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:o,...s}=n;Object.assign(this,s),r&&(this.name=r),o&&(this.stack=o);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},te=class extends b{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},De=class extends b{constructor(t,n,r,o={}){super(r||n.message||`Billing Error: ${t}`,{...o,status:t,detail:n}),this.name="BillingError"}},Ye=class extends b{constructor(t=431,n,r){let o="Request headers are too large";super(r||n?.message||o,{status:t,detail:{message:n?.message||o,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},Ry="ENDPOINT_RETIRED";function F(e,t){let n=t?` ${t}`:"";return new b(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:Ry})}var Lr="feature_disabled";function qs(e){if(!(e instanceof b)||e.status!==403||e.code!==Lr)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Gs(e){let t=qs(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function Bs(e){let t=qs(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function mn(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 De(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 Ws(e){return e instanceof De}function Hs(e){if(!(e instanceof De))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 le(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function ue(e,t){return new Promise((n,r)=>{let o=()=>{t.removeEventListener("abort",o),r(le())};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o)),t.aborted&&o()})}function fn(e,t){return new Promise((n,r)=>{let o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),r(le())},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.aborted?o():t?.addEventListener("abort",o,{once:!0})})}var Vs="request_deadline",Iy=/^Request exceeded the \d+s server processing deadline$/,zs=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Vs||Iy.test(n),Ty="git_mirror_unavailable",Cy=/^git mirror is temporarily unavailable$/,Ey=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ty||Cy.test(n);async function My(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await ue(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 le();return{message:n,data:r}}function Oy(e,t,n){return zs(e,t,n)||Ey(e,t,n)||e===501&&t?.code===Qs||e===409&&(t?.code===Xs||t?.code===Js)||e===503&&(t?.code===Zs||t?.code===ei)}async function Ys(e,t,n,r){let{message:o,data:s}=await My(e,t),i=new b(o,{status:e.status,response:e,details:s||void 0,data:s,detail:s?.detail,code:zs(e.status,s,o)?Vs:s?.code||s?.error_code||s?.detail?.error_code||e.status.toString()});if(e.status===402&&(i=mn(i)),e.status===403&&s?.code==="account_mfa_required"&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent("kortix:mfa-required"))}catch{}return e.status===431&&(i=new Ye(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&&!Oy(e.status,s,o)&&R().onError?.(i,r),{error:i,success:!1}}var jy="X-Kortix-Impersonate",Nr="kortix.impersonation",$e=null,yn=!1,Fr=new Set;function Kr(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function Dy(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 $y(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 ti(){for(let e of Fr)try{e()}catch{}}function Uy(){return yn||(yn=!0,$e=$y(Kr()?.getItem(Nr)??null)),$e&&!Dy($e)?(ni(),null):$e}function Vv(e){if(yn=!0,!e){ni();return}$e=e;try{Kr()?.setItem(Nr,JSON.stringify(e))}catch{}ti()}function ni(){yn=!0;let e=$e!==null;$e=null;try{Kr()?.removeItem(Nr)}catch{}e&&ti()}function zv(e){return Fr.add(e),()=>{Fr.delete(e)}}var Ly=/(^|\/)admin\/(api|analytics)(\/|$)/;function Fy(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Ly.test(t)}function ri(e){if(e!==void 0&&!Fy(e))return{};let t=Uy();return t?{[jy]:t.grantId}:{}}var Br=!1;function Ny(e){Br=e}function Ky(){return Br}function qy(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function qr(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function Pt(e,t,n){let r=t.toLowerCase();for(let o of Object.keys(e))o.toLowerCase()===r&&delete e[o];e[t]=n}function bn(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[o,s]of r.flatMap(qy))Pt(n,o,s);return n}function Gr(e,t,n){let r={...t},o=R().clientVersion?.trim();o&&!qr(r,"x-kortix-client-version")&&Pt(r,"X-Kortix-Client-Version",o),Br&&Pt(r,"x-kortix-admin-bypass","1");for(let[s,i]of Object.entries(ri(e)))Pt(r,s,i);return qr(r,"authorization")||Pt(r,"Authorization",`Bearer ${n}`),r}async function si(e,t){let n=await hn();if(!n)throw new te;return{headers:new Headers(Gr(e,bn(e,{headers:t}),n)),rejected:()=>R().getToken.invalidate?.(n)}}function Gy(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function oi(e,t,n,r,o){if(t instanceof Request){let a=new Headers(Gr(t.url,bn(t,n),r));return e(new Request(t,{headers:a,...o?{signal:o}:{}}))}let s=String(t),i=Gr(s,bn(t,n),r);return e(s,{...n,headers:i,...o?{signal:o}:{}})}async function hn(e){return dn(()=>R().getToken(),e)}async function Qe(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:o=Ur}=n,s=n.fetch??R().fetch??fetch,i=o===null?(e instanceof Request?e.signal:t.signal)??void 0:Ks(e,t,o);if(i?.aborted)throw le();let a=await(i?ue(hn(),i):hn());if(!a)throw new te;let c=r&&!Gy(t)&&!qr(bn(e,t),"authorization"),p=c&&e instanceof Request?e.clone():e,d=await oi(s,e,t,a,i);if(d.status!==401||!c)return d;R().getToken.invalidate?.(a);let g=await hn({attempts:2,baseDelayMs:200});return!g||g===a?d:oi(s,p,t,g,i)}var ii=()=>R().backendUrl||"",By=new Set([502,503,504]),Wy=e=>By.has(e),ai=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Hy=e=>ai(e)||(e??"GET").toUpperCase()==="DELETE",Vy=2,_n=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function he(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:o=3e4,deadlineCoversBody:s=!1,...i}=t,a=new AbortController,c={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>c.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await zy(e,i,n,r,o,s,a,c)}finally{i.signal?.removeEventListener("abort",p)}}async function zy(e,t,n,r,o,s,i,a){try{if(t.signal?.aborted)throw le();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},o);let c={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Qy(e,t,c,o,s,i,a);if(p instanceof te)return{error:p,success:!1};if(!p.ok)return await Ys(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await ue(p.json(),a.activeController.signal):g?.includes("text/")?d=await ue(p.text(),a.activeController.signal):d=await ue(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(c){return Xy(c,e,t.method,n,r,o,a)}finally{Pn(a)}}function Pn(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Yy(e,t,n){try{await ue(e.arrayBuffer(),t)}catch(r){if(_n(r))throw r}finally{Pn(n)}}async function Qy(e,t,n,r,o,s,i){let a=ai(t.method),c=Hy(t.method),p=c?Vy+1:1,d;for(let g=0;g<p;g++){g>0&&await fn(250*2**(g-1),t.signal??void 0);let m=g===0?s:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await ue(Qe(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 te)return new te;if(i.didTimeout&&_n(f)&&!t.signal?.aborted&&c&&g<p-1){i.didTimeout=!1;continue}if(_n(f)||g===p-1)throw f;continue}if(!a||!Wy(d.status)||g===p-1)return o||Pn(i),d;await Yy(d,m.signal,i)}return d}function Xy(e,t,n,r,o,s,i){Pn(i);let a=_n(e);a&&(i.isAborted=!0);let c;if(a){if(!i.didTimeout)return{error:new b("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(ii(),"")||t;c=new b(`Request timed out after ${Math.round(s/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:s})}else e instanceof Error?(c=new b(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(ii(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&R().onError?.(c,o)):(c=new b(String(e)),r&&R().onError?.(c,o));return{error:c,success:!1}}var be=()=>R().backendUrl||"",Qs="feature_not_supported",Xs="model_not_servable",Js="provision_in_flight",Zs="analytics_unavailable",ei="accounts_list_unavailable",gA={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let o=new b(r.message||"Database error",{code:r.code,details:r});return R().onError?.(o,t),{error:o,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new b(n.message,{name:n.name||"ApiError",stack:n.stack}):new b(String(n));return R().onError?.(r,t),{error:r,success:!1}}}};async function Jy(e,t,n={}){let{timeout:r=3e4,fetch:o}=n,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await Qe(`${be()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:s.signal,credentials:"omit"},{timeoutMs:null,fetch:o})}catch(a){if(a instanceof te)return gn();throw a}finally{clearTimeout(i)}}var l={putRaw:(e,t,n)=>he(`${be()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>he(`${be()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>he(`${be()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>he(`${be()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>he(`${be()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>he(`${be()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],he(`${be()}${e}`,{...o,method:"POST",body:t,headers:s})},uploadPut:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],he(`${be()}${e}`,{...o,method:"PUT",body:t,headers:s})},postStream:Jy};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function Wr(e){return e.replace(/\/v1\/?$/,"")}async function Xe(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=Wr(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 ci(){return u(await l.get("/accounts"))}async function li(e){return u(await l.post("/accounts",e))}async function ui(e){return u(await l.get(`/accounts/${e}`))}async function pi(e,t){return u(await l.patch(`/accounts/${e}`,{name:t}))}async function di(e){return u(await l.get(`/accounts/${e}/branding`))}async function gi(e,t){return u(await l.put(`/accounts/${e}/branding`,t))}async function mi(e,t,n,r){let o=new FormData;return o.append("file",n,r??(n instanceof File?n.name:t)),u(await l.upload(`/accounts/${e}/branding/assets/${t}`,o))}async function fi(e,t){return u(await l.delete(`/accounts/${e}/branding/assets/${t}`))}async function yi(e){return u(await l.delete(`/accounts/${e}/branding`))}async function hi(e){return u(await l.get(`/accounts/${e}/members`))}async function bi(e,t){return u(await l.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function _i(e){return u(await l.get(`/accounts/${e}/invites`))}async function Pi(e,t){return u(await l.delete(`/accounts/${e}/invites/${t}`))}async function xi(e,t){return u(await l.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function Si(){return u(await l.get("/account-invites",{showErrors:!1})).invites}async function wi(e){return u(await l.get(`/account-invites/${e}`,{showErrors:!1}))}async function vi(e){return u(await l.post(`/account-invites/${e}/accept`,{}))}async function Ai(e){return u(await l.post(`/account-invites/${e}/decline`,{}))}async function ki(e,t){return u(await l.delete(`/accounts/${e}/members/${t}`))}async function Ri(e,t,n){return u(await l.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Ii(e){return u(await l.post(`/accounts/${e}/leave`,{}))}async function PA(e){return Xe(e,"/v1/accounts")}async function Ti(){let e=await l.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var AA=["marketplace","connectors_api_discover","agentmail_email","llm_gateway","meta_agent","apps","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","config_releases","us_region"];async function Je(){return u(await l.get("/projects"))}async function Ei(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/projects${t}`))}async function xn(e,t){return u(await l.get(`/projects/${e}`,t))}async function Mi(e,t,n="write"){return u(await l.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Oi(e,t){return u(await l.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function ji(e){return u(await l.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function kA(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function Sn(e,t){let n=u(await l.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function wn(e,t){return u(await l.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function vn(e,t){return u(await l.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function RA(e,t){return u(await l.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Di(e){return u(await l.post("/projects",e))}async function $i(e){return u(await l.post("/projects/create-repo",e,{showErrors:!1}))}async function Ui(e,t={}){return u(await l.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Ci=200;function Zy(e){let t=e.split(`
2
2
  `).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
3
- `);try{return JSON.parse(n)}catch(r){let o=n.length>Ci?`${n.slice(0,Ci)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${o})`,{cause:r})}}async function RA(e,t,n={}){let r=await l.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let c=await r.json().catch(()=>null);throw new b(c?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:c?.code})}let o=r.body?.getReader();if(!o)throw new Error("Provision stream is unavailable on this runtime (no response body)");let s=new TextDecoder,i="",a=null;try{for(;;){let{done:c,value:p}=await o.read();if(c)break;i+=s.decode(p,{stream:!0});let d=i.indexOf(`
3
+ `);try{return JSON.parse(n)}catch(r){let o=n.length>Ci?`${n.slice(0,Ci)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${o})`,{cause:r})}}async function IA(e,t,n={}){let r=await l.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let c=await r.json().catch(()=>null);throw new b(c?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:c?.code})}let o=r.body?.getReader();if(!o)throw new Error("Provision stream is unavailable on this runtime (no response body)");let s=new TextDecoder,i="",a=null;try{for(;;){let{done:c,value:p}=await o.read();if(c)break;i+=s.decode(p,{stream:!0});let d=i.indexOf(`
4
4
 
5
5
  `);for(;d!==-1;){let g=i.slice(0,d);i=i.slice(d+2),d=i.indexOf(`
6
6
 
7
- `);let m=Jy(g);if(m){if(t(m),m.type==="error")throw new b(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{o.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function IA(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function An(e,t){return u(await l.patch(`/projects/${e}`,t))}async function Li(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Fi(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function Ni(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function TA(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function CA(e,t){throw F("updateTemplateWarmPool")}async function Ki(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function EA(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function kn(e){return u(await l.delete(`/projects/${e}`))}async function MA(e,t){return Xe(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function OA(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Wr(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let o=await r.json().catch(()=>null);return o?.project_id?{ok:!0,project:o}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function qi(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function Gi(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Bi(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Wi(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Hi(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Vi(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let o=n?.search?.trim();return o&&r.set("search",o),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function zi(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await l.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function Yi(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function Qi(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Xi(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function Ji(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await l.delete(`/projects/github/installation?${n.toString()}`))}async function Zi(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function ea(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await l.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function GA(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function ta(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function na(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function ra(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function oa(e){return u(await l.get(`/projects/${e}/access`))}async function sa(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function ia(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function BA(e){return"status"in e&&e.status==="invited"}async function aa(e,t,n,r){return u(await l.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function ca(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function la(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function ua(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function pa(e){return u(await l.get(`/projects/${e}/group-grants`))}async function da(e,t,n,r){return u(await l.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function ga(e,t,n,r){return u(await l.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function ma(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function fa(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function ya(e,t){return u(await l.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function ha(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function ba(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function _a(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Pa(e,t,n,r={}){let o=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...o?{note:o}:{}}))}async function xa(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Sa(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function wa(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function va(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Aa(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function Hr(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function Vr(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function ka(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Zy=2e3,eh=3e3,th=10*6e4;async function zA(e){let{projectId:t,provider:n,input:r,onChallenge:o,isCancelled:s,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,c=()=>s?.()??!1,p=await Hr(t,n,r);if(c())return{status:"cancelled"};o?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Zy,p.interval_ms||eh),g=p.expires_at||a()+th;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await Vr(t,n,p.flow_id)}catch{continue}if(c())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return c()?{status:"cancelled"}:{status:"expired"}}async function Ra(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function Ia(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Ta(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Ca(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var zr=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,xt=(e,t)=>`${zr(e)}/${encodeURIComponent(t)}`,Ea=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Ma(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${zr(e)}${n}`))}async function Oa(e,t){return u(await l.post(zr(e),t))}async function ja(e,t,n){return u(await l.put(`${xt(e,t)}/value`,{value:n}))}async function Da(e,t){return u(await l.delete(xt(e,t)))}async function $a(e,t,n,r){return u(await l.put(`${xt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function Ua(e,t,n,r){return u(await l.delete(`${xt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function La(e,t,n,r){return u(await l.put(`${xt(e,t)}/access`,{mode:n,user_ids:r}))}async function Fa(e,t,n){return u(await l.get(Ea(e,t,n)))}async function Na(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function Ka(e,t,n,r){return u(await l.put(Ea(e,t,n),{secret_ids:r}))}async function Yr(){return R().getToken()}async function St(e){return dn(()=>R().getToken(),e,Qr)}function Qr(){}function rk(e){}function ok(e){}async function wt(){return Yr()}async function sk(e){return St(e)}async function D(e,t,n){try{return await Qe(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof te)return gn();throw r}}function Rn(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function In(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`${Rn(e,"catalog")}${r}`)).connectors??[]}async function Xr(e){let t=[];for(let n of await In(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 qa(e,t="",n={}){let r=t.trim().toLowerCase(),o=r.split(/\s+/).filter(Boolean),s=[],i=[];for(let a of await Xr(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?s.push(a):o.every(p=>c.includes(p))&&i.push(a)}return[...s,...i].slice(0,n.limit??20)}async function Ga(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let o=(await In(e,{slug:r,includeSchemas:!0})).find(s=>s.slug===r);if(!o)return null;for(let s of o.actions){let i=`${o.slug}.${s.path}`;if(i===t)return{tool:i,connector:o.slug,action:s.path,risk:s.risk,description:s.description||s.name,inputSchema:s.inputSchema}}return null}function nh(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}async function Ba(e,t,n={},r={}){let{connector:o,action:s}=nh(t),i=r.account?.trim(),a=r.approvalContext?.trim();return u(await l.post(Rn(e,"call"),{connector:o,action:s,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}}))}async function Wa(e,t){let n=await l.get(Rn(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function rh(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 oh(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 Ha(e,t,n){let r=n.filename.trim(),o=n.contentType.trim();if(!r)throw new Error("filename is required");if(!o)throw new Error("contentType is required");let s={"Content-Type":o,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(s["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(s["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=oh(R().backendUrl),a=Rn(e,"attachments"),c=await D(`${i}${a}`,{method:"POST",headers:s,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new b(rh(d,c.status),{status:c.status,code:String(d&&typeof d=="object"?d.code??c.status:c.status),details:d,response:c,endpoint:a});return d}function dk(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 Va(e){return u(await l.get(`/projects/${e}/connections`))}async function za(e){return u(await l.get(`/projects/${e}/connections/all`))}async function Ya(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function Qa(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function Xa(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function _e(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function gk(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function mk(e,t,n){return u(await l.put(_e(e,t,"application"),n))}async function fk(e,t){return u(await l.get(_e(e,t,"application")))}async function yk(e,t,n){return u(await l.post(_e(e,t,"discover"),n))}async function hk(e,t,n={}){return u(await l.post(_e(e,t,"discover-resource"),n))}async function bk(e,t,n){return u(await l.post(_e(e,t,"register"),n))}async function _k(e,t,n){return u(await l.post(_e(e,t,"authorize"),n))}async function Pk(e,t,n){return u(await l.post(_e(e,t,"device"),n))}async function xk(e,t,n){return u(await l.post(_e(e,t,`device/${encodeURIComponent(n)}`),{}))}async function Sk(e,t){return u(await l.get(_e(e,t,"status")))}async function Ja(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Za(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function ec(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function tc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function nc(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function rc(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function oc(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function sc(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function ic(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await l.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function ac(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function cc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function lc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function uc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function pc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function dc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function wk(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function vk(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function gc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function mc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function sh(e,t,n={}){return u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,n.owner?{owner:n.owner}:{}))}var fc=sh;async function Ak(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function yc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function hc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function bc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function _c(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/apps${s?`?${s}`:""}`))}async function Pc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function kk(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),o=u(await l.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in o)return o;let s=o.cursor?.trim()||void 0;return{provider:"composio",toolkits:o.items,nextCursor:s,hasMore:!!s}}async function Rk(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function Jr(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await l.get(`/connectors/projects/${e}/discover/connectors${s?`?${s}`:""}`))}async function xc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function Zr(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var Ik=Jr,Tk=Zr;async function Sc(){return u(await l.get("/connectors/connect-status"))}async function wc(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function Ck(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function ih(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var vc=ih;async function Ac(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function kc(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Rc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Ic(e){return u(await l.get(`/projects/${e}/snapshots`))}async function Tn(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Tc(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Cc(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Ec(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function Mc(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Oc(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function jc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Dc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function $c(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function Uc(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await l.get(`/projects/${e}/files/search?${r.toString()}`))}async function Lc(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}async function Fc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"",s=await St(),i=`${R().backendUrl||""}/projects/${e}/files/archive${o}`,a=await fetch(i,{method:"GET",headers:s?{Authorization:`Bearer ${s}`}:{}});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(c||`Failed to download (HTTP ${a.status})`)}return await a.blob()}var eo=52428800,ah=104857600,Nc=20;var En=e=>`/projects/${encodeURIComponent(e)}/attachments`,Mn={showErrors:!1,deadlineCoversBody:!0},Kc=3e4,ch=12e4,lh=6e4,uh=5*6e4,ph=6e4,dh=6e4;function Cn(){return new b("Request aborted",{name:"AbortError",code:"ABORTED"})}function vt(e){if(e?.aborted)throw Cn()}function gh(e){return!(e instanceof b)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function At(e,t,n=!1){let r;for(let o=0;;o++){vt(t);try{return await e()}catch(s){let i=n&&s instanceof b&&s.status===409&&s.code==="attachment_processing";if(t?.aborted||!(gh(s)||i))throw s;r??=Date.now()+(n?uh:lh);let a=Math.min(8e3,500*2**o)*(.5+Math.random()/2);if(Date.now()+a>=r)throw s;try{await fn(a,t)}catch{throw vt(t),s}}}}function mh(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function to(e,t,n){let r=e?.upload,o=e?.received_bytes,s=Number.isSafeInteger(o)&&o>=0&&o<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&mh(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(o===0||o===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(o===t.size||o%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!s||!i)throw new Error("Invalid attachment upload handle");return e}async function qc(e,t,n,r){return u(await l.post(En(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Mn,signal:n,timeout:Kc}),"Failed to start attachment upload")}async function Gc(e,t,n,r){let o=to({...await At(()=>qc(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(o),o}function Bc(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new b(r,{status:e,details:n,code:String(n?.statusCode??e)})}function fh(e){if(!(e instanceof b))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function yh(e,t,n,r){return new Promise((o,s)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?s(f):o())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new b("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},ph)},m=()=>{d(Cn()),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(Bc(i.status,i.responseText))},i.onerror=()=>d(new b("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(Cn()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function hh(e,t,n){let r=R().fetch??fetch,o;try{o=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(s){throw n.signal?.aborted||s instanceof Error&&s.name==="AbortError"?Cn():new b(s instanceof Error?s.message:String(s),{name:s instanceof Error?s.name:"TypeError"})}if(!o.ok)throw Bc(o.status,await o.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function bh(e,t,n){vt(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?yh(r,e,t,n):hh(e,t,n)}async function _h(e,t,n,r){let o=n,s=!1;for(r.onProgress?.(0,t.size);o.upload.kind==="direct";){let i=o.upload;try{await At(()=>bh(i,t,r),r.signal)}catch(a){let c=fh(a);if(c!==409){if(s||!(c===400||c===401||c===403))throw a;s=!0,o=await Gc(e,t,o,r);continue}}return o={...o,received_bytes:t.size},r.onUpload?.(o),o}return Wc(e,t,o,r)}async function Wc(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let o=n.upload.chunk_size,s=`${En(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){vt(r.signal);let a=i.received_bytes,c=Math.min(a+o,t.size),p=t.slice(a,c),d=await At(async()=>u(await l.putRaw(`${s}/chunks/${a/o}`,p,{...Mn,signal:r.signal,timeout:Kc}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==c)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:c},r.onUpload?.(i),r.onProgress?.(c,t.size)}return i}async function On(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");vt(n.signal);let r=n.resume?to({...n.resume},t):to({...await At(()=>qc(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()<dh&&(r=await Gc(e,t,r,n)),r=r.upload.kind==="direct"?await _h(e,t,r,n):await Wc(e,t,r,n)),n.onProcessing?.();let o=`${En(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await At(async()=>u(await l.post(`${o}/complete`,{},{...Mn,signal:n.signal,timeout:ch}),"Failed to complete attachment upload"),n.signal,!0)}catch(s){throw r.upload.kind==="direct"&&s instanceof b&&s.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),s}}async function kt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${En(e)}/${encodeURIComponent(t)}`,{...Mn,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function Hc(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/branches${r}`))}async function Vc(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/commits${r}`))}async function zc(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Yc(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${o}`))}async function Qc(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await l.get(`/projects/${e}/files/history?${r.toString()}`))}async function Xc(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await l.get(`/projects/${e}/version-diff?${n.toString()}`))}async function Jc(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit));let o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${o}`,{showErrors:!1,timeout:15e3}))}async function Zc(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function el(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function tl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function nl(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function rl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function ol(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function sl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function il(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function al(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}var no=new Set;function jn(e){e&&no.add(e)}function cl(e){return!!e&&no.has(e)}function tR(e){e&&no.delete(e)}function iR(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 aR=50,Ph=200,cR=Ph;function ll(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return t.size>0?`?${t}`:""}async function ul(e,t){let n=await l.get(`/projects/${e}/sessions${ll(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Ze(e,t){return u(await l.get(`/projects/${e}/sessions${ll(t)}`))}async function pl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function dl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}function lR(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 uR(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 gl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function ml(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function fl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function yl(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function et(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||jn(n?.session_id),n}async function hl(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||jn(r.session.session_id),r}async function bl(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return jn(n.session_id),n}async function Dn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function _l(e,t,n,r){let o=new URLSearchParams;n&&o.set("limit",String(n)),r?.cursor&&o.set("cursor",r.cursor),r?.includeEvents!=null&&o.set("include_events",String(r.includeEvents));let s=o.toString();return u(await l.get(`/projects/${e}/sessions/${t}/audit${s?`?${s}`:""}`,{showErrors:r?.showErrors}))}async function Pl(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let o=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/transcript${o?`?${o}`:""}`))}async function xl(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await l.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Sl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/turn`))}async function pR(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let o=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${o?`?${o}`:""}`,{signal:n?.signal,showErrors:!1}))}async function $n(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...n.placement?{placement:n.placement}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function wl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function vl(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Al(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function kl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Rl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Il(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function Tl(e,t){return u(await l.delete(`/projects/${e}/sessions/${t}`))}async function Un(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Ln(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}))}async function Cl(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function xh(e){let t=e.split(`
7
+ `);let m=Zy(g);if(m){if(t(m),m.type==="error")throw new b(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{o.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function TA(){try{return u(await l.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function An(e,t){return u(await l.patch(`/projects/${e}`,t))}async function Li(e,t,n){return u(await l.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Fi(e,t,n){return u(await l.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function Ni(e,t){return u(await l.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function CA(e,t){return u(await l.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function EA(e,t){throw F("updateTemplateWarmPool")}async function Ki(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{completed:t}))}async function MA(e,t){return u(await l.patch(`/projects/${e}/onboarding`,{profile:t}))}async function kn(e){return u(await l.delete(`/projects/${e}`))}async function OA(e,t){return Xe(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function jA(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Wr(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let o=await r.json().catch(()=>null);return o?.project_id?{ok:!0,project:o}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function qi(e){return u(await l.post("/projects/link-repository",e,{showErrors:!1}))}async function Gi(e){let{project_id:t,...n}=e;return u(await l.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Bi(e){return u(await l.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Wi(e){return u(await l.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Hi(e){return u(await l.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Vi(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let o=n?.search?.trim();return o&&r.set("search",o),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await l.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function zi(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await l.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function Yi(e){return u(await l.post("/projects/github/installation",e,{showErrors:!1}))}async function Qi(e){return u(await l.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Xi(e){return u(await l.post("/projects/github/user-token",e,{showErrors:!1}))}async function Ji(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await l.delete(`/projects/github/installation?${n.toString()}`))}async function Zi(){return u(await l.get("/projects/git/backend",{showErrors:!1}))}async function ea(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await l.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function BA(e,t){return u(await l.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function ta(e,t){return u(await l.get(`/projects/${e}/access-requests`,t))}async function na(e,t,n="member"){return u(await l.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function ra(e,t){return u(await l.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function oa(e){return u(await l.get(`/projects/${e}/access`))}async function sa(e,t,n){return u(await l.put(`/projects/${e}/access/${t}`,{role:n}))}async function ia(e,t){return u(await l.delete(`/projects/${e}/access/${t}`))}function WA(e){return"status"in e&&e.status==="invited"}async function aa(e,t,n,r){return u(await l.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function ca(e){return u(await l.get(`/projects/${e}/access/pending-invites`))}async function la(e,t){return u(await l.delete(`/projects/${e}/access/pending-invites/${t}`))}async function ua(e,t){return u(await l.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function pa(e){return u(await l.get(`/projects/${e}/group-grants`))}async function da(e,t,n,r){return u(await l.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function ga(e,t,n,r){return u(await l.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function ma(e,t){return u(await l.delete(`/projects/${e}/group-grants/${t}`))}async function fa(e){return u(await l.get(`/projects/${e}/resource-grants`))}async function ya(e,t){return u(await l.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function ha(e,t){return u(await l.delete(`/projects/${e}/resource-grants/${t}`))}async function ba(e,t){return u(await l.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function _a(e,t){return u(await l.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Pa(e,t,n,r={}){let o=r.note?.trim();return u(await l.post(`/projects/${e}/approvals/${t}`,{decision:n,...o?{note:o}:{}}))}async function xa(e){return u(await l.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Sa(e,t){return u(await l.post(`/projects/${e}/secrets`,t))}async function wa(e,t,n,r={}){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function va(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Aa(e){return u(await l.get(`/projects/${e}/oauth`)).items??[]}async function Hr(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function Vr(e,t,n){return u(await l.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function ka(e,t){return u(await l.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var eh=2e3,th=3e3,nh=10*6e4;async function YA(e){let{projectId:t,provider:n,input:r,onChallenge:o,isCancelled:s,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,c=()=>s?.()??!1,p=await Hr(t,n,r);if(c())return{status:"cancelled"};o?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(eh,p.interval_ms||th),g=p.expires_at||a()+nh;for(;!c()&&a()<g;){if(await i(d),c())return{status:"cancelled"};let m;try{m=await Vr(t,n,p.flow_id)}catch{continue}if(c())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return c()?{status:"cancelled"}:{status:"expired"}}async function Ra(e,t){return u(await l.put(`/projects/${e}/git-credential`,t))}async function Ia(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Ta(e,t,n){return u(await l.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Ca(e,t){return u(await l.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var zr=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,xt=(e,t)=>`${zr(e)}/${encodeURIComponent(t)}`,Ea=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Ma(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await l.get(`${zr(e)}${n}`))}async function Oa(e,t){return u(await l.post(zr(e),t))}async function ja(e,t,n){return u(await l.put(`${xt(e,t)}/value`,{value:n}))}async function Da(e,t){return u(await l.delete(xt(e,t)))}async function $a(e,t,n,r){return u(await l.put(`${xt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function Ua(e,t,n,r){return u(await l.delete(`${xt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function La(e,t,n,r){return u(await l.put(`${xt(e,t)}/access`,{mode:n,user_ids:r}))}async function Fa(e,t,n){return u(await l.get(Ea(e,t,n)))}async function Na(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await l.get(n))}async function Ka(e,t,n,r){return u(await l.put(Ea(e,t,n),{secret_ids:r}))}async function Yr(){return R().getToken()}async function St(e){return dn(()=>R().getToken(),e,Qr)}function Qr(){}function ok(e){}function sk(e){}async function wt(){return Yr()}async function ik(e){return St(e)}async function D(e,t,n){try{return await Qe(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof te)return gn();throw r}}function Rn(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function In(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`${Rn(e,"catalog")}${r}`)).connectors??[]}async function Xr(e){let t=[];for(let n of await In(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 qa(e,t="",n={}){let r=t.trim().toLowerCase(),o=r.split(/\s+/).filter(Boolean),s=[],i=[];for(let a of await Xr(e)){let c=`${a.tool} ${a.description}`.toLowerCase();!r||c.includes(r)?s.push(a):o.every(p=>c.includes(p))&&i.push(a)}return[...s,...i].slice(0,n.limit??20)}async function Ga(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let o=(await In(e,{slug:r,includeSchemas:!0})).find(s=>s.slug===r);if(!o)return null;for(let s of o.actions){let i=`${o.slug}.${s.path}`;if(i===t)return{tool:i,connector:o.slug,action:s.path,risk:s.risk,description:s.description||s.name,inputSchema:s.inputSchema}}return null}function rh(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}async function Ba(e,t,n={},r={}){let{connector:o,action:s}=rh(t),i=r.account?.trim(),a=r.approvalContext?.trim();return u(await l.post(Rn(e,"call"),{connector:o,action:s,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}}))}async function Wa(e,t){let n=await l.get(Rn(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function oh(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 sh(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 Ha(e,t,n){let r=n.filename.trim(),o=n.contentType.trim();if(!r)throw new Error("filename is required");if(!o)throw new Error("contentType is required");let s={"Content-Type":o,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(s["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(s["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=sh(R().backendUrl),a=Rn(e,"attachments"),c=await D(`${i}${a}`,{method:"POST",headers:s,body:t},{timeoutMs:6e4}),p=await c.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!c.ok)throw new b(oh(d,c.status),{status:c.status,code:String(d&&typeof d=="object"?d.code??c.status:c.status),details:d,response:c,endpoint:a});return d}function gk(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 Va(e){return u(await l.get(`/projects/${e}/connections`))}async function za(e){return u(await l.get(`/projects/${e}/connections/all`))}async function Ya(e,t){return u(await l.post(`/projects/${e}/connections`,t))}async function Qa(e,t){return u(await l.post(`/projects/${e}/connections/me`,t))}async function Xa(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/credential`,n))}function _e(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function mk(e,t){return u(await l.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function fk(e,t,n){return u(await l.put(_e(e,t,"application"),n))}async function yk(e,t){return u(await l.get(_e(e,t,"application")))}async function hk(e,t,n){return u(await l.post(_e(e,t,"discover"),n))}async function bk(e,t,n={}){return u(await l.post(_e(e,t,"discover-resource"),n))}async function _k(e,t,n){return u(await l.post(_e(e,t,"register"),n))}async function Pk(e,t,n){return u(await l.post(_e(e,t,"authorize"),n))}async function xk(e,t,n){return u(await l.post(_e(e,t,"device"),n))}async function Sk(e,t,n){return u(await l.post(_e(e,t,`device/${encodeURIComponent(n)}`),{}))}async function wk(e,t){return u(await l.get(_e(e,t,"status")))}async function Ja(e,t){return u(await l.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Za(e,t){return u(await l.put(`/projects/${e}/connections/${t}/activate`,{}))}async function ec(e,t){return u(await l.put(`/projects/${e}/connections/${t}/default`,{}))}async function tc(e,t,n){return u(await l.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function nc(e,t){return u(await l.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function rc(e,t,n=[]){return u(await l.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function oc(e,t,n={}){return u(await l.post(`/projects/${e}/connections/${t}/connect`,n))}async function sc(e,t){return u(await l.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function ic(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await l.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function ac(e){return u(await l.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function cc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function lc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function uc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function pc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function dc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function vk(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function Ak(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function gc(e,t){return u(await l.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function mc(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function ih(e,t,n={}){return u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,n.owner?{owner:n.owner}:{}))}var fc=ih;async function kk(e,t){return u(await l.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function yc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors`,t))}async function hc(e,t){return u(await l.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function bc(e,t){return u(await l.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function _c(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/apps${s?`?${s}`:""}`))}async function Pc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function Rk(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),o=u(await l.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in o)return o;let s=o.cursor?.trim()||void 0;return{provider:"composio",toolkits:o.items,nextCursor:s,hasMore:!!s}}async function Ik(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function Jr(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await l.get(`/connectors/projects/${e}/discover/connectors${s?`?${s}`:""}`))}async function xc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await l.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function Zr(e,t){let n=new URLSearchParams({id:t});return u(await l.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var Tk=Jr,Ck=Zr;async function Sc(){return u(await l.get("/connectors/connect-status"))}async function wc(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function Ek(e,t,n){return u(await l.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function ah(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await l.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var vc=ah;async function Ac(e){return u(await l.get(`/connectors/projects/${e}/policies`))}async function kc(e,t,n){return u(await l.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Rc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function Ic(e){return u(await l.get(`/projects/${e}/snapshots`))}async function Tn(e){return u(await l.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Tc(e,t){return u(await l.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Cc(e){return u(await l.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Ec(e,t){return u(await l.post(`/projects/${e}/sandbox-templates`,t))}async function Mc(e,t,n){return u(await l.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Oc(e,t){return u(await l.delete(`/projects/${e}/sandbox-templates/${t}`))}async function jc(e,t){return u(await l.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Dc(e){return u(await l.get(`/projects/${e}/sandboxes`))}async function $c(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function Uc(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await l.get(`/projects/${e}/files/search?${r.toString()}`))}async function Lc(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await l.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}async function Fc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"",s=await St(),i=`${R().backendUrl||""}/projects/${e}/files/archive${o}`,a=await fetch(i,{method:"GET",headers:s?{Authorization:`Bearer ${s}`}:{}});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(c||`Failed to download (HTTP ${a.status})`)}return await a.blob()}var eo=52428800,ch=104857600,Nc=20;var En=e=>`/projects/${encodeURIComponent(e)}/attachments`,Mn={showErrors:!1,deadlineCoversBody:!0},Kc=3e4,lh=12e4,uh=6e4,ph=5*6e4,dh=6e4,gh=6e4;function Cn(){return new b("Request aborted",{name:"AbortError",code:"ABORTED"})}function vt(e){if(e?.aborted)throw Cn()}function mh(e){return!(e instanceof b)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function At(e,t,n=!1){let r;for(let o=0;;o++){vt(t);try{return await e()}catch(s){let i=n&&s instanceof b&&s.status===409&&s.code==="attachment_processing";if(t?.aborted||!(mh(s)||i))throw s;r??=Date.now()+(n?ph:uh);let a=Math.min(8e3,500*2**o)*(.5+Math.random()/2);if(Date.now()+a>=r)throw s;try{await fn(a,t)}catch{throw vt(t),s}}}}function fh(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function to(e,t,n){let r=e?.upload,o=e?.received_bytes,s=Number.isSafeInteger(o)&&o>=0&&o<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&fh(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(o===0||o===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(o===t.size||o%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!s||!i)throw new Error("Invalid attachment upload handle");return e}async function qc(e,t,n,r){return u(await l.post(En(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Mn,signal:n,timeout:Kc}),"Failed to start attachment upload")}async function Gc(e,t,n,r){let o=to({...await At(()=>qc(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(o),o}function Bc(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new b(r,{status:e,details:n,code:String(n?.statusCode??e)})}function yh(e){if(!(e instanceof b))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function hh(e,t,n,r){return new Promise((o,s)=>{let i=new e,a=0,c=!1,p,d=f=>{c||(c=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?s(f):o())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new b("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},dh)},m=()=>{d(Cn()),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(Bc(i.status,i.responseText))},i.onerror=()=>d(new b("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(Cn()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function bh(e,t,n){let r=R().fetch??fetch,o;try{o=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(s){throw n.signal?.aborted||s instanceof Error&&s.name==="AbortError"?Cn():new b(s instanceof Error?s.message:String(s),{name:s instanceof Error?s.name:"TypeError"})}if(!o.ok)throw Bc(o.status,await o.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function _h(e,t,n){vt(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?hh(r,e,t,n):bh(e,t,n)}async function Ph(e,t,n,r){let o=n,s=!1;for(r.onProgress?.(0,t.size);o.upload.kind==="direct";){let i=o.upload;try{await At(()=>_h(i,t,r),r.signal)}catch(a){let c=yh(a);if(c!==409){if(s||!(c===400||c===401||c===403))throw a;s=!0,o=await Gc(e,t,o,r);continue}}return o={...o,received_bytes:t.size},r.onUpload?.(o),o}return Wc(e,t,o,r)}async function Wc(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let o=n.upload.chunk_size,s=`${En(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){vt(r.signal);let a=i.received_bytes,c=Math.min(a+o,t.size),p=t.slice(a,c),d=await At(async()=>u(await l.putRaw(`${s}/chunks/${a/o}`,p,{...Mn,signal:r.signal,timeout:Kc}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==c)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:c},r.onUpload?.(i),r.onProgress?.(c,t.size)}return i}async function On(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");vt(n.signal);let r=n.resume?to({...n.resume},t):to({...await At(()=>qc(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()<gh&&(r=await Gc(e,t,r,n)),r=r.upload.kind==="direct"?await Ph(e,t,r,n):await Wc(e,t,r,n)),n.onProcessing?.();let o=`${En(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await At(async()=>u(await l.post(`${o}/complete`,{},{...Mn,signal:n.signal,timeout:lh}),"Failed to complete attachment upload"),n.signal,!0)}catch(s){throw r.upload.kind==="direct"&&s instanceof b&&s.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),s}}async function kt(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await l.delete(`${En(e)}/${encodeURIComponent(t)}`,{...Mn,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function Hc(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/branches${r}`))}async function Vc(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await l.get(`/projects/${e}/commits${r}`))}async function zc(e,t){return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Yc(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${o}`))}async function Qc(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await l.get(`/projects/${e}/files/history?${r.toString()}`))}async function Xc(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await l.get(`/projects/${e}/version-diff?${n.toString()}`))}async function Jc(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit));let o=r.toString()?`?${r.toString()}`:"";return u(await l.get(`/projects/${e}/change-requests${o}`,{showErrors:!1,timeout:15e3}))}async function Zc(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}`))}async function el(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/diff`))}async function tl(e,t){return u(await l.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function nl(e,t){return u(await l.post(`/projects/${e}/change-requests`,t))}async function rl(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function ol(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function sl(e,t){return u(await l.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function il(e,t,n){return u(await l.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function al(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}var no=new Set;function jn(e){e&&no.add(e)}function cl(e){return!!e&&no.has(e)}function nR(e){e&&no.delete(e)}function aR(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 cR=50,xh=200,lR=xh;function ll(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return t.size>0?`?${t}`:""}async function ul(e,t){let n=await l.get(`/projects/${e}/sessions${ll(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Ze(e,t){return u(await l.get(`/projects/${e}/sessions${ll(t)}`))}async function pl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function dl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}function uR(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 pR(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 gl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/previews`))}async function ml(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function fl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function yl(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function et(e,t){let n=u(await l.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||jn(n?.session_id),n}async function hl(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await l.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||jn(r.session.session_id),r}async function bl(e,t){let n=u(await l.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return jn(n.session_id),n}async function Dn(e,t,n){return u(await l.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function _l(e,t,n,r){let o=new URLSearchParams;n&&o.set("limit",String(n)),r?.cursor&&o.set("cursor",r.cursor),r?.includeEvents!=null&&o.set("include_events",String(r.includeEvents));let s=o.toString();return u(await l.get(`/projects/${e}/sessions/${t}/audit${s?`?${s}`:""}`,{showErrors:r?.showErrors}))}async function Pl(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let o=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/transcript${o?`?${o}`:""}`))}async function xl(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await l.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Sl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/turn`))}async function dR(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let o=r.toString();return u(await l.get(`/projects/${e}/sessions/${t}/snapshot${o?`?${o}`:""}`,{signal:n?.signal,showErrors:!1}))}async function $n(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...n.placement?{placement:n.placement}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function wl(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function vl(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Al(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function kl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Rl(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Il(e,t,n){return u(await l.patch(`/projects/${e}/sessions/${t}`,n))}async function Tl(e,t){return u(await l.delete(`/projects/${e}/sessions/${t}`))}async function Un(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Ln(e,t){return u(await l.post(`/projects/${e}/sessions/${t}/stop`,{}))}async function Cl(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function Sh(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
9
  `))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function El(e,t,n={}){return u(await l.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function Ml(e,t,n,r,o={}){let s=await l.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,o);if(!s.ok){let d=await s.json().catch(()=>null);throw new b(d?.error||`Reload failed: HTTP ${s.status}`,{status:s.status,code:d?.code,data:d})}let i=s.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,c="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;c+=a.decode(g,{stream:!0});let m=c.indexOf(`
10
10
 
11
11
  `);for(;m!==-1;){let f=c.slice(0,m);c=c.slice(m+2),m=c.indexOf(`
12
12
 
13
- `);let h=xh(f);if(h){if(r(h),h.type==="error")throw new b(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function Ol(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function jl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function Dl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function $l(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function Ul(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function Ll(e){return u(await l.get(`/projects/${e}/triggers`))}async function Fl(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function Nl(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function Kl(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function ql(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function Gl(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}var ke=new Map;function ro(e,t){return`${e}::${t}`}function Bl(e,t){ke.delete(e),ke.set(e,t)}function Wl(e,t){let n=ro(e,t),r=ke.get(n);return r&&Bl(n,r),r}function Hl(e,t,n){let r=ro(e,t);if(!ke.has(r)&&ke.size>=512){let o=ke.keys().next().value;o!==void 0&&ke.delete(o)}Bl(r,n)}function Vl(e,t){ke.delete(ro(e,t))}function Sh(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Rt(){return Sh(R().backendUrl||"http://localhost:8008/v1")}function zl(){let e=R().sandboxId;return e?`${Rt()}/p/${e}/8000`:""}function wh(e,t=8e3){return`${Rt()}/p/${e}/${t}`}function tt(e,t=8e3){return wh(e,t)}function wR(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 oo=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 vR(e){return e instanceof Error&&e.name==="SessionStartError"}function vh(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,o=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new oo(o,{status:n,code:r,terminal:!0}):null}async function Ue(e,t,n){let r=typeof n=="number"?n:n?.waitMs,o=typeof n=="number"?void 0:n?.repositoryMode,s=new URLSearchParams;r&&r>0&&s.set("wait_ms",String(Math.floor(r))),o&&s.set("repository_mode",o);let i=s.size>0?`?${s.toString()}`:"",a=await l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1});if(!a.success||!a.data){let g=vh(a.error);if(g&&!(g.status===404&&cl(t)))throw g;return null}let c=a.data,p=c.sandbox?.external_id,d=c.runtime_session_id??c.opencode_session_id;return c.stage==="ready"&&p&&d&&Hl(e,t,{runtimeSessionId:d,opencodeSessionId:d,runtimeUrl:tt(p),sandboxId:p}),c}function AR(e,t){return["session-start",e,t]}async function Yl(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function Ql(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function Xl(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await l.delete(`/projects/${e}/model-defaults?${n}`))}async function MR(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Jl(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Ah(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Fn(e){let t=e.connectors_required?Jl(e.connectors_required):void 0,n=e.connectors_personal?Jl(e.connectors_personal):void 0;if(t&&n&&!Ah(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 Zl(e,t,n){let r=Fn(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function qR(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?so(n.block):null}}async function GR(e,t,n){let r=so(n,!0),o=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...o,block:o.block?so(o.block):null}}function so(e,t=!1){let n=Fn(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 BR(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function eu(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}function tu(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function kh(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function zR(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,isGrandfathered:t.is_grandfathered===!0};let n=e??tu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),o=(n.tier?.display_name||"").trim()||r;return{family:kh(r),label:o,sublabel:null,isGrandfathered:!1}}async function nu(e){let t=await l.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?tu():t.data}function ru(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 ou(e){return nu(`/billing/account-state${ru(e)}`)}async function su(e){return nu(`/billing/account-state/minimal${ru(e)}`)}async function iu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await l.get(`/billing/transactions${n?`?${n}`:""}`))}async function au(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await l.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function cu(){return u(await l.get("/billing/credit-breakdown"))}async function lu(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function uu(){return u(await l.get("/billing/tier-configurations"))}async function YR(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Xe(e,`/v1/billing/account-state${t}`)}async function pu(e){return u(await l.post("/billing/create-checkout-session",{account_id:e.accountId,tier_key:e.tierKey,success_url:e.successUrl,cancel_url:e.cancelUrl,commitment_type:e.commitmentType,locale:e.locale,server_type:e.serverType,location:e.location}),"Failed to create checkout session")}async function du(e,t){return u(await l.post("/billing/confirm-checkout-session",{account_id:t,session_id:e}),"Failed to confirm checkout session")}async function gu(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function mu(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function fu(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function yu(e,t,n){return u(await l.post("/billing/schedule-downgrade",{account_id:n,target_tier_key:e,commitment_type:t}),"Failed to schedule downgrade")}async function hu(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function bu(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),u(await l.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function _u(e){return u(await l.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Pu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function xu(e){return u(await l.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function QR(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function XR(e){return u(await l.post("/billing/create-per-seat-checkout",{account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale}),"Failed to create per-seat checkout")}async function JR(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function ZR(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function Su(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await l.get(`/usage${n?`?${n}`:""}`))}function io(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Nn(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Kn(e){return e.size>0?`?${e}`:""}async function vu(e={}){let t=new URLSearchParams;return io(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Nn(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/session-costs${Kn(t)}`))}async function qn(e,t={}){let n=new URLSearchParams;return io(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${Kn(n)}`))}async function sI(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Nn(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/cost-by-project${Kn(t)}`))}async function iI(e={}){let t=new URLSearchParams;return io(t,e),e.sessionId&&t.set("session_id",e.sessionId),Nn(t,e),u(await l.get(`/usage/cost-summary${Kn(t)}`))}function wu(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let o=t;o.ownerId&&n.set("owner_id",o.ownerId)}Nn(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`${R().backendUrl||""}${r}?${n}`}async function aI(e,t={}){let n=wu(e==="projects"?"projects":"sessions",t),r=await St(),o=await fetch(n,{method:"GET",headers:r?{Authorization:`Bearer ${r}`}:{}});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(c||`Failed to export CSV (HTTP ${o.status})`)}let s=o.headers.get("x-kortix-row-cap"),i=s!=null?Number(s):NaN;return{blob:await o.blob(),rowCap:Number.isFinite(i)?i:null}}async function Au(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function pI(e){return Au("slack",e)}function dI(e){return Au("teams",e)}async function ku(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function gI(e){return ku("slack",e)}function mI(e){return ku("teams",e)}async function Ru(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function Iu(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var Rh={oauth_available:!1,install_url:null};async function Tu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?Rh:t.data}async function Cu(e,t,n){return u(await l.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function Eu(e,t){return Cu("slack",e,t)}function Mu(e,t){return Cu("teams",e,t)}async function Ou(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function ju(e){let t=await l.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function Du(e,t){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function $u(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function ao(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 Ih={provider:"agentmail",managed_available:!1};async function Uu(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?ao(r.data):null}async function Lu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Ih:t.data}async function Fu(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return ao(n)}async function Nu(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function Ku(e,t,n){let r=u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return ao(r)}async function fI(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function yI(e,t,n){return u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function qu(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Gu(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Bu(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Wu(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Hu(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await l.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function Vu(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function zu(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Yu(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Qu(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Xu(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ju(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Zu(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function ep(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function tp(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function np(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function rp(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function op(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function sp(e,t,n,r,o){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...o&&Object.keys(o).length?{generationConfig:o}:{}}),"Gateway request failed")}async function PI(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function wI(){throw F("getReferralCode")}async function vI(){throw F("refreshReferralCode")}async function AI(e){throw F("validateReferralCode")}async function kI(){throw F("getReferralStats")}async function RI(e={}){throw F("listReferrals")}async function II(e){throw F("sendReferralEmails")}function M(e){return l.get(e,{showErrors:!1})}function S(e){return u(e,"Unexpected empty response")}async function ip(e){return S(await M(`/accounts/${e}/iam/groups`)).groups}async function ap(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}`))}async function cp(e,t){return S(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function lp(e,t,n){return S(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function up(e,t){return S(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function pp(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}/members`)).members}async function dp(e,t,n){return S(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function DI(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function gp(e,t,n){return S(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function $I(e,t){return S(await M(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function UI(e,t){let n=S(await M(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function Re(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}async function qI(e,t={}){let n=Re({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return S(await M(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function VI(e,t={}){let n=Re({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return S(await M(`/accounts/${e}/iam/policies${n}`)).policies}async function zI(e,t){return S(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function YI(e,t,n){return S(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function QI(e,t){return S(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function XI(e,t){return S(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function JI(e,t){return S(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function mp(e){return S(await M(`/accounts/${e}/iam/roles`)).roles}async function fp(e){return S(await M(`/accounts/${e}/iam/agent-identities`)).agents}async function yp(e){return S(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function hp(e,t){return S(await M(`/accounts/${e}/iam/roles/${t}/permissions`))}async function nT(e){return S(await M(`/accounts/${e}/iam/actions`)).actions}async function bp(e,t){return S(await M(`/accounts/${e}/iam/roles/${t}/usage`))}async function _p(e,t){return S(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Pp(e,t,n){return S(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function xp(e,t,n){return S(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Sp(e,t){return S(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function rT(e,t,n){return S(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function aT(e){return S(await M(`/accounts/${e}/iam/scim/tokens`)).tokens}async function cT(e,t){return S(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function lT(e,t){return S(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function gT(e){return S(await M(`/accounts/${e}/iam/mfa-required`))}async function mT(e){return S(await M(`/accounts/${e}/iam/mfa-required/preview`))}async function fT(e,t){return S(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function yT(e){return S(await M(`/accounts/${e}/iam/session-oversight`))}async function hT(e,t){return S(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function xT(e){return S(await M(`/accounts/${e}/iam/sso/provider`)).provider}async function ST(e,t){return S(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function wT(e,t){return S(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function vT(e){return S(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function AT(e){return S(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function kT(e){return S(await M(`/accounts/${e}/iam/sso/mappings`)).mappings}async function RT(e,t){return S(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function IT(e,t){return S(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function MT(e){return S(await M(`/accounts/${e}/iam/session-policy`))}async function OT(e,t){return S(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function jT(e){return S(await M(`/accounts/${e}/iam/sessions`)).sessions}async function DT(e,t){return S(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function $T(e){return S(await M(`/accounts/${e}/iam/pat-policy`))}async function UT(e,t){return S(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function KT(e){return S(await M(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function qT(e,t){return S(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function GT(e,t){return S(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function BT(e,t){return S(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function YT(e){return S(await M(`/accounts/${e}/audit/webhooks`)).webhooks}async function QT(e,t){return S(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function XT(e,t,n){return S(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function JT(e,t){return S(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function ZT(e,t={}){let n=Re({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return S(await M(`/accounts/${e}/audit${n}`))}async function wp(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),S(await M(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function vp(e,t,n){return n.length===0?[]:S(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function iC(e){return S(await M(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function aC(e,t){return S(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function Ap(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function kp(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function Rp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function Ip(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function Tp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Cp(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function Th(e){return Re({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 Ep(e,t){return u(await M(`/accounts/${e}/iam/assignments${Th(t)}`)).assignments}async function Mp(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await l.post(`/accounts/${e}/iam/assignments`,n))}async function Op(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function jp(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await M(`/accounts/${e}/iam/permissions${n}`)).permissions}async function _C(){let e=await l.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function PC(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function xC(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function SC(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function wC(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function RC(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function IC(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function TC(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function CC(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function EC(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function MC(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function OC(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var Dp="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function $C(e){throw F("getGoogleAuthUrl",Dp)}async function UC(e,t){throw F("convertPresentationToGoogleSlides",Dp)}async function $p(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind);let r=n.toString();return u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function Up(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function Lp(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function Fp(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function Np(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}var co="call:";function qC(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(co)&&e.length>co.length?{type:"connector_call",executionId:e.slice(co.length)}:{type:"review_item",reviewItemId:e}}function Ch(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function GC(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Ch(n.status)]+=1;return t}function BC(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 lo(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function qp(e){let t=e.indexOf(".");return t<=0?lo(e):`(${lo(e.slice(0,t))}) ${lo(e.slice(t+1))}`}function Eh(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Gn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,pe=e=>Array.isArray(e)?e:void 0,Kp=e=>typeof e=="number"?e:0,Mh=e=>e.split(`
14
- `).map(t=>t.trim()).filter(Boolean);function Oh(e,t){let n=Gn(e.advanced),r=U(e.description),o=pe(e.whatChanged)??(r?Mh(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:o,impact:U(e.impact)??"",verification:pe(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:pe(e.conflicts),requestedChanges:pe(e.requested_changes)??[],advanced:{headRef:U(n.headRef)??U(e.head_ref)??"",baseRef:U(n.baseRef)??U(e.base_ref)??"",headSha:U(n.headSha)??U(e.head_sha)??U(e.head_commit_sha)??"",baseSha:U(n.baseSha)??U(e.base_sha)??"",additions:Kp(n.additions),deletions:Kp(n.deletions),files:pe(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function jh(e,t){let n=pe(e.actions);if(n)return{actions:n.map((c,p)=>({id:U(c.id)??`${t.review_item_id}-${p}`,title:U(c.title)??"Action",connector:U(c.connector)??"",action:U(c.action)??"",consequence:U(c.consequence)??"",risk:U(c.risk)??t.risk,icon:U(c.icon)??"generic",argsPreview:pe(c.argsPreview)??[],policySource:U(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=U(e.action_path)??"",{connector:o,action:s}=Eh(r),i=Gn(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?qp(r):t.title||"Run action",connector:o,action:s,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,approvalContext:U(e.approval_context),connectorRisk:U(e.risk)??null,policySource:"Requires approval"}]}}function Dh(e,t){return{artifactKind:U(e.artifactKind)??"document",artifactLabel:U(e.artifactLabel)??"Output",previewUrl:U(e.previewUrl)??U(e.preview_url),preview:U(e.preview),files:pe(e.files),note:U(e.note)??t.summary??""}}function $h(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:pe(e.options)??[]}}function Uh(e,t){return{note:U(e.note)??t.summary??"",children:pe(e.children)??[]}}function Lh(e){let t=Gn(e.detail);switch(e.kind){case"change":return Oh(t,e);case"approval":return jh(t,e);case"output":return Dh(t,e);case"decision":return $h(t,e);case"batch":return Uh(t,e)}}function Fh(e,t){let n=typeof e.number=="number"?e.number:void 0,r=U(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function WC(e,t={}){let n=Gn(e.detail),r=e.origin_session_id??void 0,o=r?t.sessionLabels?.[r]:void 0,s=e.kind==="approval"?U(n.action_path):void 0,i=e.kind==="change"?Fh(n,e.summary):e.kind==="approval"?o??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:s?qp(s):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:Lh(e)}}async function Gp(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Bp(e){return u(await l.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Wp(e,t){let n=await l.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var uo=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Hp(e,t=""){return`${Rt()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Vp(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let o=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new uo(o,t.status)}return r}async function XC(e){return Vp(Hp(e))}async function JC(e){return Vp(Hp(e,"/messages"))}async function zp(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function Yp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Qp(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Xp(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}async function Jp(e){return u(await l.get(`/projects/${e}/reminders`))}async function Zp(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await l.get(`/accounts/tokens${r}`))}async function ed(e){let{accountId:t,expiresAt:n,projectId:r,name:o}=e;return u(await l.post("/accounts/tokens",{name:o,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function td(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function nd(){return u(await l.get("/oauth/grants")).grants}async function rd(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function od(e){return u(await l.get(`/projects/${e}/cli-token`))}async function sd(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function id(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function nt(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,o]of Object.entries(e))n.includes(` ${r} `)&&o!=null&&o!==""&&t.set(r,String(o));return t}function po(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 ad(e,t){let n=nt(po(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function cd(e,t){let n=nt(po({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function ld(e,t){let n=nt(po(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function ud(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function pd(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function dd(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function gd(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function md(e,t){return u(await l.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function fd(e,t){return u(await l.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function gE(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function yd(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await l.get(`/marketplace/items${n}`))}async function hd(){return u(await l.get("/marketplace/marketplaces"))}async function bd(){return u(await l.get("/marketplace/marketplaces/featured"))}async function _d(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Pd(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function xd(){return u(await l.get("/marketplace/sources"))}async function Sd(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function wd(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function hE(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function PE(e){throw F("getTemplate")}async function xE(e,t){throw F("installTemplate")}async function vd(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Ad(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function kd(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Rd(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Id(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Td(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Cd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function Ed(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Md(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function go(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function mo(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function Nh(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function Kh(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 Od(e,t,n={}){let r=await Nh(t),o=n.mediaType??"application/gzip",s=await go(e,{kind:"archive",media_type:o});if(!s.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>s.upload.max_bytes)throw new Error(`App artifact exceeds ${s.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(s.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:o}),signal:n.signal,headers:{"content-type":o,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),mo(e,s.artifact.artifact_id,{sha256:await Kh(r),size_bytes:r.byteLength})}async function jd(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Dd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function $d(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Ud(e,t,n,r={}){let o=new URLSearchParams;r.after!==void 0&&o.set("after",String(r.after)),r.limit!==void 0&&o.set("limit",String(r.limit));let s=o.size?`?${o.toString()}`:"";return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${s}`),"Failed to load App logs")}async function Ld(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Fd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Nd(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Kd(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}async function Bn(e){return u(await l.get(`/projects/${e}/model-access`))}async function Wn(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function TE(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:o,previewHasError:s,previewIsLinkOnly:i}=e;return t||n?!1:o?s&&!i:r==="error"}function fo(e){return typeof e=="string"&&e.trim().length>0}function qd(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return fo(t)||fo(n)||fo(r)}function qh(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 Hn(e){if(!e)return!0;let t=qh(e.items);return t?!t.some(qd):!qd(e)}function ae(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function ME(e){return ae(e)==="bash"}function OE(e){let t=ae(e);return t==="question"||t==="ask"}function jE(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Gh=new Set(["show","show_user"]);function Gd(e){return Gh.has(ae(e))}function DE(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Bd(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||yo(e))}function yo(e){let t=ae(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:Hn(e.state?.input)}var Bh=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Wd(e){return Bh.has(ae(e))}var Wh=50*1024*1024,ho="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Hh=new RegExp(`^kortix-attachment://(${ho})/(${ho})/(${ho})$`);function _o(e){if(typeof e!="string")return null;let t=Hh.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function qE(e){return _o(e)!==null}var bo=new WeakMap;async function Hd(e,t,n,r={}){if(n.size>Wh)throw new Error("Attachments must be 50 MiB or smaller.");let o=`${e}/${t}`,s=r.attachmentId?void 0:bo.get(n)?.get(o);if(s?.promise)return s.promise;let i=s??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let c=bo.get(n)??new Map;c.set(o,i),bo.set(n,c)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=l.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(c=>{throw i.promise=void 0,c}),i.promise}async function Vd(e,t){let n=_o(e);if(!n)throw new Error("Invalid attachment reference");let r=R().backendUrl.replace(/\/$/,""),o=await D(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!o.ok)throw new b("Could not load attachment",{status:o.status});return o.blob()}var Vh=new Set(["show","show_user"]);function zh(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let o=r+5;if(o>=e.length||!/\s/.test(e[o])){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return t;let i=e.indexOf("</file>",s+1);if(i===-1)return t;t.push(e.slice(o,s).trimStart()),n=i+7}}var rt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),It=e=>typeof e=="string"&&e.length>0?e:null,zd=e=>typeof e=="string"?It(e.split("/").pop()):null;function Vn(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Yh(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 Qh(e,t){for(let n of zh(e))t(Vn(n,"attachment"),Vn(n,"filename")??zd(Vn(n,"path")),Vn(n,"mime"))}function Xh(e,t){for(let n of[e,...Yh(e.items)])rt(n)&&t(n.attachment,zd(n.path),null)}function GE(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!rt(r)||!rt(r.info)||!Array.isArray(r.parts))continue;let o=It(r.info.id);if(!o)continue;let s=It(r.info.role)??"unknown",i=(a,c,p)=>{let d=_o(a);!d||n.has(a)||(n.add(a),t.push({url:a,attachment_id:d.attachmentId,filename:c,mime:p,message_id:o,role:s}))};for(let a of r.parts)rt(a)&&(a.type==="file"?i(a.url,It(a.filename),It(a.mime)):a.type==="text"&&typeof a.text=="string"?Qh(a.text,i):a.type==="tool"&&typeof a.tool=="string"&&Vh.has(ae(a.tool))&&rt(a.state)&&rt(a.state.input)&&Xh(a.state.input,i))}return t}function zn(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function Jh(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 zE(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 Po(e,t,n){return e!==void 0?e:Jh(zn(t),n)}var Yd={get disableMobileAdvertising(){return Po(R().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Po(R().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Po(R().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var Zh=new Set(["project-manager"]);function xo(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Yd.enableProjects||!Zh.has(e.name)}function XE(e){let t=e.agents.filter(xo),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function Qd(){return{projects:{list:Je,listForAccount:Ei,get:xn,detail:Sn,create:Di,createRepo:$i,provision:Ui,update:An,archive:kn,llmCatalog:wn,modelPicker:vn,modelAccess:Bn,setModelAccess:Wn,sandboxHealth:Tn,sandboxTemplates:Rc,sessions:Ze,createSession:et},github:{linkRepository:qi,replaceProjectRepository:Gi,getInstallation:Bi,listInstallations:Wi,listLinkableInstallations:Hi,listRepositories:Vi,listRepositoryBranches:zi,linkInstallation:Qi,saveInstallation:Yi,deleteInstallation:Ji,storeUserToken:Xi},gitBackend:{get:Zi,repositories:ea},connectStatus:Sc,marketplace:{items:s=>yd(s),item:s=>_d(s),itemFile:(s,i)=>Pd(s,i),marketplaces:()=>hd(),featured:()=>bd(),sources:{list:()=>xd(),add:s=>Sd(s),remove:s=>wd(s)}}}}function Xd(){return{billing:{accountState:ou,accountStateMinimal:su,transactions:iu,transactionsSummary:au,creditBreakdown:cu,usageHistory:lu,usageRollup:Su,sessionCosts:{list:vu,get:qn},tierConfigurations:uu,checkout:{createSession:n=>pu(n),confirmSession:(n,r)=>du(n,r)},subscription:{createPortalSession:(n,r)=>gu(n,r),cancel:(n,r)=>mu(n,r),reactivate:n=>fu(n),scheduleDowngrade:(n,r,o)=>yu(n,r,o),cancelScheduledChange:n=>hu(n),prorationPreview:(n,r)=>bu(n,r)},credits:{purchase:n=>_u(n),autoTopupSettings:n=>Pu(n),configureAutoTopup:n=>xu(n)}},sandboxShares:{list:Gp,create:Bp,revoke:Wp}}}function de(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var Ie={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function Te(){let e=zn("BACKEND_URL")||R().backendUrl;return e||"http://localhost:8008/v1"}function Ct(e){let t=de(e);return t.endsWith("/v1")?t:`${t}/v1`}function Tt(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=Tt(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return Tt(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function eb(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 So(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"daytona",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${Te()}/p/${n.external_id}/${Ie.KORTIX_MASTER}`:""),status:eb(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 wo(){let e=await Je(),t=[];for(let n of e){let r=await Ze(n.project_id).catch(()=>[]);for(let o of r)t.push({project:n,session:o,runtime:null,sandbox:So(n,o,null)})}return t.sort((n,r)=>{let o={active:0,provisioning:1,stopped:2,error:3},s=(o[n.sandbox.status]??99)-(o[r.sandbox.status]??99);return s!==0?s:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Le(e){let t=await wo();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}var Et=class extends Error{constructor(n,r,o){super(r);this.code=n;this.status=o;this.name="HeadlessAuthError"}code;status};async function z(e,t,n){let r=n?.fetch??R().fetch??((p,d)=>fetch(p,d)),o=de(n?.backendUrl??R().backendUrl??"");if(!o)throw new Et("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let i=await r(`${Ct(o)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:s,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new Et(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return c}function vo(e,t){return z("/auth/signup",{body:e},t)}function Ao(e,t){return z("/auth/sign-in/password",{body:e},t)}function ko(e,t){return z("/auth/sign-in/magic-link",{body:e},t)}function Ro(e,t){return z("/auth/verify-otp",{body:e},t)}function Io(e,t){return z("/auth/sign-in/oauth",{body:e},t)}function To(e,t){return z("/auth/oauth/exchange",{body:e},t)}function Mt(e,t){return z("/auth/refresh",{body:e},t)}function Co(e,t){return z("/auth/password/reset",{body:e},t)}function Eo(e,t,n){return z("/auth/password/update",{body:e,bearer:t},n)}function Mo(e,t){return z("/auth/user",{bearer:e},t)}function Oo(e,t,n){return z("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function jo(e,t){return z("/auth/sign-in/sso",{body:e},t)}var Do={enroll:(e,t,n)=>z("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function $o(e,t={},n){return z("/auth/sign-out",{body:t,bearer:e},n)}function Uo(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,o=null,s=!e.storage,i=null,a=null,c=0,p=new Set,d=w=>(w.expires_at??0)*1e3,g=w=>d(w)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:o})):await e.storage.remove());for(let w of[...p])try{w(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(s)return r;if(!i){let w=c,L=(async()=>{let O=await e.storage.get();if(w===c&&O)try{let j=JSON.parse(O);j.session?.access_token&&j.session?.refresh_token&&(r=j.session,o=j.user??null)}catch{r=null}return s=!0,r})();i=L,L.then(()=>{i===L&&(i=null)},()=>{i===L&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let w=r.refresh_token,L=c,O=Mt({refresh_token:w},e.request).then(async j=>(L!==c||(r=j.session,j.user&&(o=j.user),await m()),r)).catch(async j=>{if(L!==c)return r;let y=j&&typeof j=="object"&&"status"in j?j.status:0;if(y>=400&&y<500)return r=null,o=null,await m(),null;throw j}).finally(()=>{a===O&&(a=null)});a=O}return a}return{subscribe(w){return p.add(w),()=>{p.delete(w)}},current:()=>r,user:()=>o,load:f,async set(w,L){await f(),c+=1,a=null,r=w,L!==void 0&&(o=L),w||(o=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){c+=1,a=null,r=null,o=null,s=!0,await m()}}}function Jd(){return{list:ci,get:ui,create:li,secretResources:{list:Ma,create:Oa,rotate:ja,remove:Da,grant:$a,revoke:Ua,setAccess:La},updateName:pi,branding:{get:di,update:gi,uploadAsset:mi,removeAsset:fi,reset:yi},leave:Ii,members:hi,invite:bi,removeMember:ki,updateMemberRole:Ri,invites:_i,cancelInvite:Pi,resendInvite:xi,tokens:{list:Zp,create:ed,revoke:td},connectedApps:{list:nd,revoke:rd},audit:{log:ad,export:ld,webhooks:{list:ud,create:pd,update:dd,remove:gd}}}}function Zd(){return{assignments:{list:Ep,create:Mp,revoke:Op},permissions:{list:jp,forRole:hp},roles:{list:mp,create:_p,update:Pp,setPermissions:xp,remove:Sp,usage:bp},groups:{list:ip,get:ap,create:cp,update:lp,remove:up,members:{list:pp,add:dp,remove:gp}},agentIdentities:fp,oauthClients:{list:Ap,get:kp,create:Rp,update:Ip,rotateSecret:Tp,remove:Cp},can:wp,canBatch:vp}}function eg(){let e={signUp:vo,signInWithPassword:Ao,sendMagicLink:ko,verifyOtp:Ro,signInWithProvider:Io,exchangeCode:To,refresh:Mt,resetPassword:Co,updatePassword:Eo,updateUserMetadata:Oo,signInWithSso:jo,mfa:Do,user:Mo,signOut:$o,session:Uo},t=Jd(),n=Zd();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Si,describe:wi,accept:vi,decline:Ai}}}var Ot=new Map,Lo=new Map;function Fo(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function tg(e){return Ot.get(Fo(e))??null}function ng(){return[...Ot.values()].filter(e=>typeof e=="string")}function rg(e){return Ot.has(Fo(e))}async function ot(e){let t=Fo(e),n=Ot.get(t);if(n!==void 0)return n;let r=Lo.get(t);if(r)return r;let o=(async()=>{try{let s=await l.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!s.success)return null;let i=typeof s.data?.preview_url_template=="string"?s.data.preview_url_template:null;return Ot.set(t,i),i}catch{return null}finally{Lo.delete(t)}})();return Lo.set(t,o),o}function og(e){let{apiBaseUrl:t}=e;return rg(t)||ot(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:tg(t)}}function sg(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new b(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let o=R().backendUrl??e.backendUrl,s=80,i=t(o);return i&&(s=i.port?Number(i.port):i.protocol==="https:"?443:80),og({sandboxId:r,apiBaseUrl:o,backendPort:s})}}function ig(e,t){let n=null;async function r(){n||(n=Dn(e,t,{showErrors:!1}).then(o=>{let s=$l(o)??"",i=s.indexOf("/"),a=i>0&&i<s.length-1?{providerID:s.slice(0,i),modelID:s.slice(i+1)}:void 0,c=o.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(o){throw n=null,o}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var jt=new Map;function ag(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let o=n?.evidence?.error;return o&&o!==n?.message&&r.push(o),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var st=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};var it={url:null,sandboxId:null,dbSandboxId:null,version:0},nb=new Set;function cg(e,t=null,n=null){if(!(it.url===e&&it.sandboxId===t&&it.dbSandboxId===n)){it={url:e,sandboxId:t,dbSandboxId:n,version:it.version+1};for(let r of nb)r()}}function lg(){return it.url}function ug(e,t){async function n(r){let o=Date.now()+r,s=()=>Math.max(0,o-Date.now()),i=await Ue(e,t,Math.min(3e4,s()));for(;Date.now()<o&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,s()))),i=await Ue(e,t,Math.min(3e4,s()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new b(ag(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new b("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=tt(c);return cg(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function pg(e,t,n){let r=null;function o(){if(r)return r;let p=Wl(e,t);return p&&(r=p),r}let s=ug(e,t);async function i(p){let d=o();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=ot(R().backendUrl??n.backendUrl).catch(()=>null),f=`${e}
15
- ${t}`,h=jt.get(f);if(h)return r=await h,await m,r;let w=s(g);jt.set(f,w);try{return r=await w,await m,r}finally{jt.get(f)===w&&jt.delete(f)}}function a(p){let d=o();if(!d)throw new st(p);return d}function c(){r=null,Vl(e,t)}return{ensureReady:i,tryResolveReady:o,requireReady:a,forgetReady:c}}var K=["directory","workspace"],dg=["messageID","model","agent","noReply","tools","format","system","variant","parts"],k=(e,t,n=K,r=[],o)=>({method:e,path:t,query:n,body:r,bodyParam:o}),rb={"session.list":k("GET","/session",[...K,"scope","path","roots","start","search","limit"]),"session.get":k("GET","/session/{sessionID}"),"session.create":k("POST","/session",K,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":k("DELETE","/session/{sessionID}"),"session.update":k("PATCH","/session/{sessionID}",K,["title","metadata","permission","time"]),"session.status":k("GET","/session/status"),"session.messages":k("GET","/session/{sessionID}/message",[...K,"limit","before"]),"session.prompt":k("POST","/session/{sessionID}/message",K,dg),"session.promptAsync":k("POST","/session/{sessionID}/prompt_async",K,dg),"session.abort":k("POST","/session/{sessionID}/abort"),"session.revert":k("POST","/session/{sessionID}/revert",K,["messageID","partID"]),"session.unrevert":k("POST","/session/{sessionID}/unrevert"),"session.summarize":k("POST","/session/{sessionID}/summarize",K,["providerID","modelID","auto"]),"session.command":k("POST","/session/{sessionID}/command",K,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":k("POST","/session/{sessionID}/share"),"session.unshare":k("DELETE","/session/{sessionID}/share"),"session.fork":k("POST","/session/{sessionID}/fork",K,["messageID"]),"session.diff":k("GET","/session/{sessionID}/diff",[...K,"messageID"]),"session.todo":k("GET","/session/{sessionID}/todo"),"permission.list":k("GET","/permission"),"permission.reply":k("POST","/permission/{requestID}/reply",K,["reply","message"]),"question.list":k("GET","/question"),"question.reply":k("POST","/question/{requestID}/reply",K,["answers"]),"question.reject":k("POST","/question/{requestID}/reject"),"part.update":k("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",K,[],"part"),"part.delete":k("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":k("GET","/file",[...K,"path"]),"file.read":k("GET","/file/content",[...K,"path"]),"find.files":k("GET","/find/file",[...K,"query","dirs","type","limit"]),"vcs.diff":k("GET","/vcs/diff",[...K,"mode","context"]),"global.health":k("GET","/global/health",[]),"global.dispose":k("POST","/global/dispose",[]),"global.config.get":k("GET","/global/config",[]),"global.config.update":k("PATCH","/global/config",[],[],"config"),"provider.list":k("GET","/provider"),"provider.auth":k("GET","/provider/auth"),"provider.oauth.authorize":k("POST","/provider/{providerID}/oauth/authorize",K,["method","inputs"]),"provider.oauth.callback":k("POST","/provider/{providerID}/oauth/callback",K,["method","code"]),"auth.set":k("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":k("GET","/agent"),"app.skills":k("GET","/skill"),"app.log":k("POST","/log",K,["service","level","message","extra"]),"command.list":k("GET","/command"),"tool.ids":k("GET","/experimental/tool/ids"),"tool.list":k("GET","/experimental/tool",[...K,"provider","model"]),"mcp.status":k("GET","/mcp"),"mcp.add":k("POST","/mcp",K,["name","config"]),"mcp.connect":k("POST","/mcp/{name}/connect"),"mcp.disconnect":k("POST","/mcp/{name}/disconnect"),"mcp.auth.start":k("POST","/mcp/{name}/auth"),"mcp.auth.callback":k("POST","/mcp/{name}/auth/callback",K,["code"]),"mcp.auth.remove":k("DELETE","/mcp/{name}/auth"),"project.list":k("GET","/project"),"project.current":k("GET","/project/current"),"path.get":k("GET","/path")};function ob(e,t){let n=[];for(let r of e.query){let o=t[r];o!=null&&n.push(`${r}=${encodeURIComponent(String(o))}`)}return n.length?`?${n.join("&")}`:""}function sb(e,t,n={},r={}){let o=rb[t],s=o.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(o.bodyParam)i=n[o.bodyParam],a=i!==void 0;else for(let p of o.body)p in n&&(i={...i,[p]:n[p]},a=!0);let c=new Headers(r.headers);return a&&c.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${s}${ob(o,n)}`,{method:o.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function ib(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 ab(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=ib(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let o=await r.text(),s=o;try{s=JSON.parse(o)}catch{}return{error:s||{},request:t,response:r}}function No(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let o=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!o.ok)throw Object.assign(new Error(`SSE failed: ${o.status} ${o.statusText}`),{status:o.status});if(!o.body)throw new Error("No body in SSE response");let s=o.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{s.cancel()}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:c,value:p}=await s.read();if(c)break;a=(a+p).replace(/\r\n/g,`
13
+ `);let h=Sh(f);if(h){if(r(h),h.type==="error")throw new b(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function Ol(e,t){return u(await l.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function jl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function Dl(e,t,n){return u(await l.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function $l(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function Ul(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function Ll(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}async function Fl(e){return u(await l.get(`/projects/${e}/triggers`))}async function Nl(e,t){return u(await l.post(`/projects/${e}/triggers`,t))}async function Kl(e,t,n){return u(await l.patch(`/projects/${e}/triggers/${t}`,n))}async function ql(e,t){return u(await l.delete(`/projects/${e}/triggers/${t}`))}async function Gl(e,t){return u(await l.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function Bl(e,t){return u(await l.post(`/projects/${e}/triggers/${t}/fire`,{}))}var ke=new Map;function ro(e,t){return`${e}::${t}`}function Wl(e,t){ke.delete(e),ke.set(e,t)}function Hl(e,t){let n=ro(e,t),r=ke.get(n);return r&&Wl(n,r),r}function Vl(e,t,n){let r=ro(e,t);if(!ke.has(r)&&ke.size>=512){let o=ke.keys().next().value;o!==void 0&&ke.delete(o)}Wl(r,n)}function zl(e,t){ke.delete(ro(e,t))}function wh(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Rt(){return wh(R().backendUrl||"http://localhost:8008/v1")}function Yl(){let e=R().sandboxId;return e?`${Rt()}/p/${e}/8000`:""}function vh(e,t=8e3){return`${Rt()}/p/${e}/${t}`}function tt(e,t=8e3){return vh(e,t)}function vR(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 oo=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 AR(e){return e instanceof Error&&e.name==="SessionStartError"}function Ah(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,o=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new oo(o,{status:n,code:r,terminal:!0}):null}async function Ue(e,t,n){let r=typeof n=="number"?n:n?.waitMs,o=typeof n=="number"?void 0:n?.repositoryMode,s=new URLSearchParams;r&&r>0&&s.set("wait_ms",String(Math.floor(r))),o&&s.set("repository_mode",o);let i=s.size>0?`?${s.toString()}`:"",a=await l.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1});if(!a.success||!a.data){let g=Ah(a.error);if(g&&!(g.status===404&&cl(t)))throw g;return null}let c=a.data,p=c.sandbox?.external_id,d=c.runtime_session_id??c.opencode_session_id;return c.stage==="ready"&&p&&d&&Vl(e,t,{runtimeSessionId:d,opencodeSessionId:d,runtimeUrl:tt(p),sandboxId:p}),c}function kR(e,t){return["session-start",e,t]}async function Ql(e){return u(await l.get(`/projects/${e}/model-defaults`))}async function Xl(e,t){return u(await l.put(`/projects/${e}/model-defaults`,t))}async function Jl(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await l.delete(`/projects/${e}/model-defaults?${n}`))}async function OR(e,t){return u(await l.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Zl(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function kh(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Fn(e){let t=e.connectors_required?Zl(e.connectors_required):void 0,n=e.connectors_personal?Zl(e.connectors_personal):void 0;if(t&&n&&!kh(t,n))throw new Error("connectors_personal must match connectors_required when both fields are present");let r={...e};return delete r.connectors_personal,(t!==void 0||n!==void 0)&&(r.connectors_required=t??n),r}async function eu(e,t,n){let r=Fn(n);return u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function GR(e,t){let n=u(await l.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?so(n.block):null}}async function BR(e,t,n){let r=so(n,!0),o=u(await l.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...o,block:o.block?so(o.block):null}}function so(e,t=!1){let n=Fn(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 WR(e,t,n){return u(await l.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function tu(e,t){return u(await l.put(`/projects/${e}/default-agent`,{agent:t}))}function nu(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function Rh(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function YR(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,isGrandfathered:t.is_grandfathered===!0};let n=e??nu(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),o=(n.tier?.display_name||"").trim()||r;return{family:Rh(r),label:o,sublabel:null,isGrandfathered:!1}}async function ru(e){let t=await l.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?nu():t.data}function ou(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 su(e){return ru(`/billing/account-state${ou(e)}`)}async function iu(e){return ru(`/billing/account-state/minimal${ou(e)}`)}async function au(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await l.get(`/billing/transactions${n?`?${n}`:""}`))}async function cu(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await l.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function lu(){return u(await l.get("/billing/credit-breakdown"))}async function uu(e){let t=e!=null?`?days=${e}`:"";return u(await l.get(`/billing/usage-history${t}`))}async function pu(){return u(await l.get("/billing/tier-configurations"))}async function QR(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Xe(e,`/v1/billing/account-state${t}`)}async function du(e){return u(await l.post("/billing/create-checkout-session",{account_id:e.accountId,tier_key:e.tierKey,success_url:e.successUrl,cancel_url:e.cancelUrl,commitment_type:e.commitmentType,locale:e.locale,server_type:e.serverType,location:e.location}),"Failed to create checkout session")}async function gu(e,t){return u(await l.post("/billing/confirm-checkout-session",{account_id:t,session_id:e}),"Failed to confirm checkout session")}async function mu(e,t){return u(await l.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function fu(e,t){return u(await l.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function yu(e){return u(await l.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function hu(e,t,n){return u(await l.post("/billing/schedule-downgrade",{account_id:n,target_tier_key:e,commitment_type:t}),"Failed to schedule downgrade")}async function bu(e){return u(await l.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function _u(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),u(await l.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function Pu(e){return u(await l.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function xu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function Su(e){return u(await l.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function XR(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await l.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function JR(e){return u(await l.post("/billing/create-per-seat-checkout",{account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale}),"Failed to create per-seat checkout")}async function ZR(e){return u(await l.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function eI(e){return u(await l.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function wu(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await l.get(`/usage${n?`?${n}`:""}`))}function io(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Nn(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Kn(e){return e.size>0?`?${e}`:""}async function Au(e={}){let t=new URLSearchParams;return io(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Nn(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/session-costs${Kn(t)}`))}async function qn(e,t={}){let n=new URLSearchParams;return io(n,t),u(await l.get(`/usage/session-costs/${encodeURIComponent(e)}${Kn(n)}`))}async function iI(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Nn(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await l.get(`/usage/cost-by-project${Kn(t)}`))}async function aI(e={}){let t=new URLSearchParams;return io(t,e),e.sessionId&&t.set("session_id",e.sessionId),Nn(t,e),u(await l.get(`/usage/cost-summary${Kn(t)}`))}function vu(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let o=t;o.ownerId&&n.set("owner_id",o.ownerId)}Nn(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`${R().backendUrl||""}${r}?${n}`}async function cI(e,t={}){let n=vu(e==="projects"?"projects":"sessions",t),r=await St(),o=await fetch(n,{method:"GET",headers:r?{Authorization:`Bearer ${r}`}:{}});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(c||`Failed to export CSV (HTTP ${o.status})`)}let s=o.headers.get("x-kortix-row-cap"),i=s!=null?Number(s):NaN;return{blob:await o.blob(),rowCap:Number.isFinite(i)?i:null}}async function ku(e,t){return u(await l.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function dI(e){return ku("slack",e)}function gI(e){return ku("teams",e)}async function Ru(e,t){return u(await l.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function mI(e){return Ru("slack",e)}function fI(e){return Ru("teams",e)}async function Iu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function Tu(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var Ih={oauth_available:!1,install_url:null};async function Cu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?Ih:t.data}async function Eu(e,t,n){return u(await l.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function Mu(e,t){return Eu("slack",e,t)}function Ou(e,t){return Eu("teams",e,t)}async function ju(e){return u(await l.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Du(e){let t=await l.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function $u(e,t){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function Uu(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function ao(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 Th={provider:"agentmail",managed_available:!1};async function Lu(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?ao(r.data):null}async function Fu(e){let t=await l.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Th:t.data}async function Nu(e,t){let n=u(await l.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return ao(n)}async function Ku(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await l.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function qu(e,t,n){let r=u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return ao(r)}async function yI(e){return u(await l.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function hI(e,t,n){return u(await l.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function Gu(e){return u(await l.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Bu(e,t){return u(await l.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Wu(e){return u(await l.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Hu(e,t){return u(await l.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Vu(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await l.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function zu(e,t){return u(await l.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function Yu(e,t){return u(await l.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Qu(e,t){return u(await l.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Xu(e,t){return u(await l.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ju(e,t){return u(await l.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Zu(e,t){return u(await l.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function ep(e){return u(await l.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function tp(e,t){return u(await l.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function np(e,t){return u(await l.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function rp(e){return u(await l.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function op(e,t){return u(await l.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function sp(e,t){return u(await l.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function ip(e,t,n,r,o){return u(await l.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...o&&Object.keys(o).length?{generationConfig:o}:{}}),"Gateway request failed")}async function xI(e,t){return u(await l.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function vI(){throw F("getReferralCode")}async function AI(){throw F("refreshReferralCode")}async function kI(e){throw F("validateReferralCode")}async function RI(){throw F("getReferralStats")}async function II(e={}){throw F("listReferrals")}async function TI(e){throw F("sendReferralEmails")}function M(e){return l.get(e,{showErrors:!1})}function S(e){return u(e,"Unexpected empty response")}async function ap(e){return S(await M(`/accounts/${e}/iam/groups`)).groups}async function cp(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}`))}async function lp(e,t){return S(await l.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function up(e,t,n){return S(await l.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function pp(e,t){return S(await l.delete(`/accounts/${e}/iam/groups/${t}`))}async function dp(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}/members`)).members}async function gp(e,t,n){return S(await l.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function $I(e,t){return S(await M(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function mp(e,t,n){return S(await l.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function UI(e,t){return S(await M(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function LI(e,t){let n=S(await M(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function Re(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}async function GI(e,t={}){let n=Re({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return S(await M(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function zI(e,t={}){let n=Re({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return S(await M(`/accounts/${e}/iam/policies${n}`)).policies}async function YI(e,t){return S(await l.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function QI(e,t,n){return S(await l.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function XI(e,t){return S(await l.delete(`/accounts/${e}/iam/policies/${t}`))}async function JI(e,t){return S(await l.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function ZI(e,t){return S(await l.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function fp(e){return S(await M(`/accounts/${e}/iam/roles`)).roles}async function yp(e){return S(await M(`/accounts/${e}/iam/agent-identities`)).agents}async function hp(e){return S(await l.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function bp(e,t){return S(await M(`/accounts/${e}/iam/roles/${t}/permissions`))}async function rT(e){return S(await M(`/accounts/${e}/iam/actions`)).actions}async function _p(e,t){return S(await M(`/accounts/${e}/iam/roles/${t}/usage`))}async function Pp(e,t){return S(await l.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function xp(e,t,n){return S(await l.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Sp(e,t,n){return S(await l.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function wp(e,t){return S(await l.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function oT(e,t,n){return S(await l.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function cT(e){return S(await M(`/accounts/${e}/iam/scim/tokens`)).tokens}async function lT(e,t){return S(await l.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function uT(e,t){return S(await l.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function mT(e){return S(await M(`/accounts/${e}/iam/mfa-required`))}async function fT(e){return S(await M(`/accounts/${e}/iam/mfa-required/preview`))}async function yT(e,t){return S(await l.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function hT(e){return S(await M(`/accounts/${e}/iam/session-oversight`))}async function bT(e,t){return S(await l.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function ST(e){return S(await M(`/accounts/${e}/iam/sso/provider`)).provider}async function wT(e,t){return S(await l.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function vT(e,t){return S(await l.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function AT(e){return S(await l.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function kT(e){return S(await l.delete(`/accounts/${e}/iam/sso/provider`))}async function RT(e){return S(await M(`/accounts/${e}/iam/sso/mappings`)).mappings}async function IT(e,t){return S(await l.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function TT(e,t){return S(await l.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function OT(e){return S(await M(`/accounts/${e}/iam/session-policy`))}async function jT(e,t){return S(await l.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function DT(e){return S(await M(`/accounts/${e}/iam/sessions`)).sessions}async function $T(e,t){return S(await l.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function UT(e){return S(await M(`/accounts/${e}/iam/pat-policy`))}async function LT(e,t){return S(await l.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function qT(e){return S(await M(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function GT(e,t){return S(await l.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function BT(e,t){return S(await l.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function WT(e,t){return S(await l.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function QT(e){return S(await M(`/accounts/${e}/audit/webhooks`)).webhooks}async function XT(e,t){return S(await l.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function JT(e,t,n){return S(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function ZT(e,t){return S(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function eC(e,t={}){let n=Re({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return S(await M(`/accounts/${e}/audit${n}`))}async function vp(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),S(await M(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Ap(e,t,n){return n.length===0?[]:S(await l.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function aC(e){return S(await M(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function cC(e,t){return S(await l.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function kp(e){return u(await l.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function Rp(e,t){return u(await l.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function Ip(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function Tp(e,t,n){return u(await l.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function Cp(e,t){return u(await l.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Ep(e,t){return u(await l.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function Ch(e){return Re({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 Mp(e,t){return u(await M(`/accounts/${e}/iam/assignments${Ch(t)}`)).assignments}async function Op(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await l.post(`/accounts/${e}/iam/assignments`,n))}async function jp(e,t){return u(await l.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function Dp(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await M(`/accounts/${e}/iam/permissions${n}`)).permissions}async function PC(){let e=await l.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function xC(e="User requested deletion"){return u(await l.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function SC(){return u(await l.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function wC(){return u(await l.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function vC(){return(await l.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function IC(){return l.get("/admin/api/provider-distribution").then(e=>u(e))}function TC(e=300){return l.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function CC(e){return l.put("/admin/api/provider-distribution",e).then(t=>u(t))}function EC(e){return l.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function MC(e,t){return l.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function OC(){return l.get("/admin/api/provider-fallback").then(e=>u(e))}function jC(e){return l.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var $p="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function UC(e){throw F("getGoogleAuthUrl",$p)}async function LC(e,t){throw F("convertPresentationToGoogleSlides",$p)}async function Up(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind);let r=n.toString();return u(await l.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function Lp(e,t){return u(await l.get(`/projects/${e}/review/items/${t}`))}async function Fp(e,t){return u(await l.post(`/projects/${e}/review/items`,t))}async function Np(e,t,n){return u(await l.post(`/projects/${e}/review/items/${t}/act`,n))}async function Kp(e,t){return u(await l.post(`/projects/${e}/review/bulk`,t))}var co="call:";function GC(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(co)&&e.length>co.length?{type:"connector_call",executionId:e.slice(co.length)}:{type:"review_item",reviewItemId:e}}function Eh(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function BC(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Eh(n.status)]+=1;return t}function WC(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function lo(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Gp(e){let t=e.indexOf(".");return t<=0?lo(e):`(${lo(e.slice(0,t))}) ${lo(e.slice(t+1))}`}function Mh(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Gn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,pe=e=>Array.isArray(e)?e:void 0,qp=e=>typeof e=="number"?e:0,Oh=e=>e.split(`
14
+ `).map(t=>t.trim()).filter(Boolean);function jh(e,t){let n=Gn(e.advanced),r=U(e.description),o=pe(e.whatChanged)??(r?Oh(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:o,impact:U(e.impact)??"",verification:pe(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:pe(e.conflicts),requestedChanges:pe(e.requested_changes)??[],advanced:{headRef:U(n.headRef)??U(e.head_ref)??"",baseRef:U(n.baseRef)??U(e.base_ref)??"",headSha:U(n.headSha)??U(e.head_sha)??U(e.head_commit_sha)??"",baseSha:U(n.baseSha)??U(e.base_sha)??"",additions:qp(n.additions),deletions:qp(n.deletions),files:pe(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function Dh(e,t){let n=pe(e.actions);if(n)return{actions:n.map((c,p)=>({id:U(c.id)??`${t.review_item_id}-${p}`,title:U(c.title)??"Action",connector:U(c.connector)??"",action:U(c.action)??"",consequence:U(c.consequence)??"",risk:U(c.risk)??t.risk,icon:U(c.icon)??"generic",argsPreview:pe(c.argsPreview)??[],policySource:U(c.policySource)??"Requires approval",decided:c.decided==="approved"||c.decided==="denied"?c.decided:void 0}))};let r=U(e.action_path)??"",{connector:o,action:s}=Mh(r),i=Gn(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?Gp(r):t.title||"Run action",connector:o,action:s,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([c,p])=>({key:c,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,approvalContext:U(e.approval_context),connectorRisk:U(e.risk)??null,policySource:"Requires approval"}]}}function $h(e,t){return{artifactKind:U(e.artifactKind)??"document",artifactLabel:U(e.artifactLabel)??"Output",previewUrl:U(e.previewUrl)??U(e.preview_url),preview:U(e.preview),files:pe(e.files),note:U(e.note)??t.summary??""}}function Uh(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:pe(e.options)??[]}}function Lh(e,t){return{note:U(e.note)??t.summary??"",children:pe(e.children)??[]}}function Fh(e){let t=Gn(e.detail);switch(e.kind){case"change":return jh(t,e);case"approval":return Dh(t,e);case"output":return $h(t,e);case"decision":return Uh(t,e);case"batch":return Lh(t,e)}}function Nh(e,t){let n=typeof e.number=="number"?e.number:void 0,r=U(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function HC(e,t={}){let n=Gn(e.detail),r=e.origin_session_id??void 0,o=r?t.sessionLabels?.[r]:void 0,s=e.kind==="approval"?U(n.action_path):void 0,i=e.kind==="change"?Nh(n,e.summary):e.kind==="approval"?o??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:s?Gp(s):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:Fh(e)}}async function Bp(e){return u(await l.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Wp(e){return u(await l.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Hp(e,t){let n=await l.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var uo=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function Vp(e,t=""){return`${Rt()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function zp(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let o=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new uo(o,t.status)}return r}async function JC(e){return zp(Vp(e))}async function ZC(e){return zp(Vp(e,"/messages"))}async function Yp(e,t){return u(await l.get(`/projects/${e}/sessions/${t}/reminders`))}async function Qp(e,t,n){return u(await l.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function Xp(e,t,n,r){return u(await l.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Jp(e,t,n){return u(await l.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}async function Zp(e){return u(await l.get(`/projects/${e}/reminders`))}async function ed(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await l.get(`/accounts/tokens${r}`))}async function td(e){let{accountId:t,expiresAt:n,projectId:r,name:o}=e;return u(await l.post("/accounts/tokens",{name:o,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function nd(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await l.delete(`/accounts/tokens/${e}${n}`))}async function rd(){return u(await l.get("/oauth/grants")).grants}async function od(e){return u(await l.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function iE(){return u(await l.get("/accounts/me/devices")).devices}async function aE(e){return u(await l.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function sd(e){return u(await l.get(`/projects/${e}/cli-token`))}async function id(e,t){return u(await l.post(`/projects/${e}/cli-token`,t??{}))}async function ad(e,t){return u(await l.delete(`/projects/${e}/cli-token/${t}`))}function nt(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,o]of Object.entries(e))n.includes(` ${r} `)&&o!=null&&o!==""&&t.set(r,String(o));return t}function po(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 cd(e,t){let n=nt(po(t)).toString();return u(await l.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function ld(e,t){let n=nt(po({...t,projectId:void 0})).toString();return u(await l.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function ud(e,t){let n=nt(po(t)).toString();return u(await l.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function pd(e){return u(await l.get(`/accounts/${e}/audit/webhooks`))}async function dd(e,t){return u(await l.post(`/accounts/${e}/audit/webhooks`,t))}async function gd(e,t,n){return u(await l.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function md(e,t){return u(await l.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function fd(e,t){return u(await l.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function yd(e,t){return u(await l.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function yE(e){return u(await l.get(`/approval-links/${e}`),"Failed to load approval")}async function hd(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await l.get(`/marketplace/items${n}`))}async function bd(){return u(await l.get("/marketplace/marketplaces"))}async function _d(){return u(await l.get("/marketplace/marketplaces/featured"))}async function Pd(e){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function xd(e,t){return u(await l.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Sd(){return u(await l.get("/marketplace/sources"))}async function wd(e){return u(await l.post("/marketplace/sources",e),"Failed to add marketplace source")}async function vd(e){return u(await l.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function PE(e,t){return u(await l.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function wE(e){throw F("getTemplate")}async function vE(e,t){throw F("installTemplate")}async function Ad(e){return u(await l.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function kd(e,t){return u(await l.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Rd(e,t){return u(await l.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Id(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Td(e,t){return u(await l.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Cd(e,t){return u(await l.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Ed(e,t){return u(await l.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function Md(e,t,n){return u(await l.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Od(e,t){return u(await l.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function go(e,t){return u(await l.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function mo(e,t,n){return u(await l.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function Kh(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function qh(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 jd(e,t,n={}){let r=await Kh(t),o=n.mediaType??"application/gzip",s=await go(e,{kind:"archive",media_type:o});if(!s.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>s.upload.max_bytes)throw new Error(`App artifact exceeds ${s.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(s.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:o}),signal:n.signal,headers:{"content-type":o,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),mo(e,s.artifact.artifact_id,{sha256:await qh(r),size_bytes:r.byteLength})}async function Dd(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function $d(e,t){return u(await l.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Ud(e,t,n){return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Ld(e,t,n,r={}){let o=new URLSearchParams;r.after!==void 0&&o.set("after",String(r.after)),r.limit!==void 0&&o.set("limit",String(r.limit));let s=o.size?`?${o.toString()}`:"";return u(await l.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${s}`),"Failed to load App logs")}async function Fd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Nd(e,t){return u(await l.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Kd(e,t,n){return u(await l.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function qd(e,t,n){return u(await l.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}async function Bn(e){return u(await l.get(`/projects/${e}/model-access`))}async function Wn(e,t){return u(await l.put(`/projects/${e}/model-access`,t))}function ME(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:o,previewHasError:s,previewIsLinkOnly:i}=e;return t||n?!1:o?s&&!i:r==="error"}function fo(e){return typeof e=="string"&&e.trim().length>0}function Gd(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return fo(t)||fo(n)||fo(r)}function Gh(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 Hn(e){if(!e)return!0;let t=Gh(e.items);return t?!t.some(Gd):!Gd(e)}function ae(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function DE(e){return ae(e)==="bash"}function $E(e){let t=ae(e);return t==="question"||t==="ask"}function UE(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Bh=new Set(["show","show_user"]);function Bd(e){return Bh.has(ae(e))}function LE(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Wd(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||yo(e))}function yo(e){let t=ae(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:Hn(e.state?.input)}var Wh=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Hd(e){return Wh.has(ae(e))}var Hh=50*1024*1024,ho="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Vh=new RegExp(`^kortix-attachment://(${ho})/(${ho})/(${ho})$`);function _o(e){if(typeof e!="string")return null;let t=Vh.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function WE(e){return _o(e)!==null}var bo=new WeakMap;async function Vd(e,t,n,r={}){if(n.size>Hh)throw new Error("Attachments must be 50 MiB or smaller.");let o=`${e}/${t}`,s=r.attachmentId?void 0:bo.get(n)?.get(o);if(s?.promise)return s.promise;let i=s??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let c=bo.get(n)??new Map;c.set(o,i),bo.set(n,c)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=l.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(c=>{throw i.promise=void 0,c}),i.promise}async function zd(e,t){let n=_o(e);if(!n)throw new Error("Invalid attachment reference");let r=R().backendUrl.replace(/\/$/,""),o=await D(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!o.ok)throw new b("Could not load attachment",{status:o.status});return o.blob()}var zh=new Set(["show","show_user"]);function Yh(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let o=r+5;if(o>=e.length||!/\s/.test(e[o])){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return t;let i=e.indexOf("</file>",s+1);if(i===-1)return t;t.push(e.slice(o,s).trimStart()),n=i+7}}var rt=e=>!!e&&typeof e=="object"&&!Array.isArray(e),It=e=>typeof e=="string"&&e.length>0?e:null,Yd=e=>typeof e=="string"?It(e.split("/").pop()):null;function Vn(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Qh(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 Xh(e,t){for(let n of Yh(e))t(Vn(n,"attachment"),Vn(n,"filename")??Yd(Vn(n,"path")),Vn(n,"mime"))}function Jh(e,t){for(let n of[e,...Qh(e.items)])rt(n)&&t(n.attachment,Yd(n.path),null)}function HE(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!rt(r)||!rt(r.info)||!Array.isArray(r.parts))continue;let o=It(r.info.id);if(!o)continue;let s=It(r.info.role)??"unknown",i=(a,c,p)=>{let d=_o(a);!d||n.has(a)||(n.add(a),t.push({url:a,attachment_id:d.attachmentId,filename:c,mime:p,message_id:o,role:s}))};for(let a of r.parts)rt(a)&&(a.type==="file"?i(a.url,It(a.filename),It(a.mime)):a.type==="text"&&typeof a.text=="string"?Xh(a.text,i):a.type==="tool"&&typeof a.tool=="string"&&zh.has(ae(a.tool))&&rt(a.state)&&rt(a.state.input)&&Jh(a.state.input,i))}return t}function zn(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function Zh(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 XE(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 Po(e,t,n){return e!==void 0?e:Zh(zn(t),n)}var Qd={get disableMobileAdvertising(){return Po(R().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Po(R().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Po(R().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var eb=new Set(["project-manager"]);function xo(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:Qd.enableProjects||!eb.has(e.name)}function eM(e){let t=e.agents.filter(xo),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function Xd(){return{projects:{list:Je,listForAccount:Ei,get:xn,detail:Sn,create:Di,createRepo:$i,provision:Ui,update:An,archive:kn,llmCatalog:wn,modelPicker:vn,modelAccess:Bn,setModelAccess:Wn,sandboxHealth:Tn,sandboxTemplates:Rc,sessions:Ze,createSession:et},github:{linkRepository:qi,replaceProjectRepository:Gi,getInstallation:Bi,listInstallations:Wi,listLinkableInstallations:Hi,listRepositories:Vi,listRepositoryBranches:zi,linkInstallation:Qi,saveInstallation:Yi,deleteInstallation:Ji,storeUserToken:Xi},gitBackend:{get:Zi,repositories:ea},connectStatus:Sc,marketplace:{items:s=>hd(s),item:s=>Pd(s),itemFile:(s,i)=>xd(s,i),marketplaces:()=>bd(),featured:()=>_d(),sources:{list:()=>Sd(),add:s=>wd(s),remove:s=>vd(s)}}}}function Jd(){return{billing:{accountState:su,accountStateMinimal:iu,transactions:au,transactionsSummary:cu,creditBreakdown:lu,usageHistory:uu,usageRollup:wu,sessionCosts:{list:Au,get:qn},tierConfigurations:pu,checkout:{createSession:n=>du(n),confirmSession:(n,r)=>gu(n,r)},subscription:{createPortalSession:(n,r)=>mu(n,r),cancel:(n,r)=>fu(n,r),reactivate:n=>yu(n),scheduleDowngrade:(n,r,o)=>hu(n,r,o),cancelScheduledChange:n=>bu(n),prorationPreview:(n,r)=>_u(n,r)},credits:{purchase:n=>Pu(n),autoTopupSettings:n=>xu(n),configureAutoTopup:n=>Su(n)}},sandboxShares:{list:Bp,create:Wp,revoke:Hp}}}function de(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var Ie={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function Te(){let e=zn("BACKEND_URL")||R().backendUrl;return e||"http://localhost:8008/v1"}function Ct(e){let t=de(e);return t.endsWith("/v1")?t:`${t}/v1`}function Tt(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=Tt(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return Tt(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function tb(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 So(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"daytona",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${Te()}/p/${n.external_id}/${Ie.KORTIX_MASTER}`:""),status:tb(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 wo(){let e=await Je(),t=[];for(let n of e){let r=await Ze(n.project_id).catch(()=>[]);for(let o of r)t.push({project:n,session:o,runtime:null,sandbox:So(n,o,null)})}return t.sort((n,r)=>{let o={active:0,provisioning:1,stopped:2,error:3},s=(o[n.sandbox.status]??99)-(o[r.sandbox.status]??99);return s!==0?s:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Le(e){let t=await wo();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}var Et=class extends Error{constructor(n,r,o){super(r);this.code=n;this.status=o;this.name="HeadlessAuthError"}code;status};async function z(e,t,n){let r=n?.fetch??R().fetch??((p,d)=>fetch(p,d)),o=de(n?.backendUrl??R().backendUrl??"");if(!o)throw new Et("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let i=await r(`${Ct(o)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:s,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),c=null;try{c=a?JSON.parse(a):null}catch{c=a}if(!i.ok){let p=c&&typeof c=="object"?c:{};throw new Et(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return c}function vo(e,t){return z("/auth/signup",{body:e},t)}function Ao(e,t){return z("/auth/sign-in/password",{body:e},t)}function ko(e,t){return z("/auth/sign-in/magic-link",{body:e},t)}function Ro(e,t){return z("/auth/verify-otp",{body:e},t)}function Io(e,t){return z("/auth/sign-in/oauth",{body:e},t)}function To(e,t){return z("/auth/oauth/exchange",{body:e},t)}function Mt(e,t){return z("/auth/refresh",{body:e},t)}function Co(e,t){return z("/auth/password/reset",{body:e},t)}function Eo(e,t,n){return z("/auth/password/update",{body:e,bearer:t},n)}function Mo(e,t){return z("/auth/user",{bearer:e},t)}function Oo(e,t,n){return z("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function jo(e,t){return z("/auth/sign-in/sso",{body:e},t)}var Do={enroll:(e,t,n)=>z("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>z(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function $o(e,t={},n){return z("/auth/sign-out",{body:t,bearer:e},n)}function Uo(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,o=null,s=!e.storage,i=null,a=null,c=0,p=new Set,d=w=>(w.expires_at??0)*1e3,g=w=>d(w)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:o})):await e.storage.remove());for(let w of[...p])try{w(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(s)return r;if(!i){let w=c,L=(async()=>{let O=await e.storage.get();if(w===c&&O)try{let j=JSON.parse(O);j.session?.access_token&&j.session?.refresh_token&&(r=j.session,o=j.user??null)}catch{r=null}return s=!0,r})();i=L,L.then(()=>{i===L&&(i=null)},()=>{i===L&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let w=r.refresh_token,L=c,O=Mt({refresh_token:w},e.request).then(async j=>(L!==c||(r=j.session,j.user&&(o=j.user),await m()),r)).catch(async j=>{if(L!==c)return r;let y=j&&typeof j=="object"&&"status"in j?j.status:0;if(y>=400&&y<500)return r=null,o=null,await m(),null;throw j}).finally(()=>{a===O&&(a=null)});a=O}return a}return{subscribe(w){return p.add(w),()=>{p.delete(w)}},current:()=>r,user:()=>o,load:f,async set(w,L){await f(),c+=1,a=null,r=w,L!==void 0&&(o=L),w||(o=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){c+=1,a=null,r=null,o=null,s=!0,await m()}}}function Zd(){return{list:ci,get:ui,create:li,secretResources:{list:Ma,create:Oa,rotate:ja,remove:Da,grant:$a,revoke:Ua,setAccess:La},updateName:pi,branding:{get:di,update:gi,uploadAsset:mi,removeAsset:fi,reset:yi},leave:Ii,members:hi,invite:bi,removeMember:ki,updateMemberRole:Ri,invites:_i,cancelInvite:Pi,resendInvite:xi,tokens:{list:ed,create:td,revoke:nd},connectedApps:{list:rd,revoke:od},audit:{log:cd,export:ud,webhooks:{list:pd,create:dd,update:gd,remove:md}}}}function eg(){return{assignments:{list:Mp,create:Op,revoke:jp},permissions:{list:Dp,forRole:bp},roles:{list:fp,create:Pp,update:xp,setPermissions:Sp,remove:wp,usage:_p},groups:{list:ap,get:cp,create:lp,update:up,remove:pp,members:{list:dp,add:gp,remove:mp}},agentIdentities:yp,oauthClients:{list:kp,get:Rp,create:Ip,update:Tp,rotateSecret:Cp,remove:Ep},can:vp,canBatch:Ap}}function tg(){let e={signUp:vo,signInWithPassword:Ao,sendMagicLink:ko,verifyOtp:Ro,signInWithProvider:Io,exchangeCode:To,refresh:Mt,resetPassword:Co,updatePassword:Eo,updateUserMetadata:Oo,signInWithSso:jo,mfa:Do,user:Mo,signOut:$o,session:Uo},t=Zd(),n=eg();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:Si,describe:wi,accept:vi,decline:Ai}}}var Ot=new Map,Lo=new Map;function Fo(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function ng(e){return Ot.get(Fo(e))??null}function rg(){return[...Ot.values()].filter(e=>typeof e=="string")}function og(e){return Ot.has(Fo(e))}async function ot(e){let t=Fo(e),n=Ot.get(t);if(n!==void 0)return n;let r=Lo.get(t);if(r)return r;let o=(async()=>{try{let s=await l.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!s.success)return null;let i=typeof s.data?.preview_url_template=="string"?s.data.preview_url_template:null;return Ot.set(t,i),i}catch{return null}finally{Lo.delete(t)}})();return Lo.set(t,o),o}function sg(e){let{apiBaseUrl:t}=e;return og(t)||ot(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:ng(t)}}function ig(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new b(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let o=R().backendUrl??e.backendUrl,s=80,i=t(o);return i&&(s=i.port?Number(i.port):i.protocol==="https:"?443:80),sg({sandboxId:r,apiBaseUrl:o,backendPort:s})}}function ag(e,t){let n=null;async function r(){n||(n=Dn(e,t,{showErrors:!1}).then(o=>{let s=$l(o)??"",i=s.indexOf("/"),a=i>0&&i<s.length-1?{providerID:s.slice(0,i),modelID:s.slice(i+1)}:void 0,c=o.agent_name?.trim()||void 0;return{model:a,agent:c}}));try{return await n}catch(o){throw n=null,o}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var jt=new Map;function cg(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let o=n?.evidence?.error;return o&&o!==n?.message&&r.push(o),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var st=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};var it={url:null,sandboxId:null,dbSandboxId:null,version:0},rb=new Set;function lg(e,t=null,n=null){if(!(it.url===e&&it.sandboxId===t&&it.dbSandboxId===n)){it={url:e,sandboxId:t,dbSandboxId:n,version:it.version+1};for(let r of rb)r()}}function ug(){return it.url}function pg(e,t){async function n(r){let o=Date.now()+r,s=()=>Math.max(0,o-Date.now()),i=await Ue(e,t,Math.min(3e4,s()));for(;Date.now()<o&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,s()))),i=await Ue(e,t,Math.min(3e4,s()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new b(cg(i),{code:"RUNTIME_UNAVAILABLE"});let c=i.sandbox.external_id;if(!c)throw new b("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=tt(c);return lg(p,c),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:c}}return n}function dg(e,t,n){let r=null;function o(){if(r)return r;let p=Hl(e,t);return p&&(r=p),r}let s=pg(e,t);async function i(p){let d=o();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=ot(R().backendUrl??n.backendUrl).catch(()=>null),f=`${e}
15
+ ${t}`,h=jt.get(f);if(h)return r=await h,await m,r;let w=s(g);jt.set(f,w);try{return r=await w,await m,r}finally{jt.get(f)===w&&jt.delete(f)}}function a(p){let d=o();if(!d)throw new st(p);return d}function c(){r=null,zl(e,t)}return{ensureReady:i,tryResolveReady:o,requireReady:a,forgetReady:c}}var K=["directory","workspace"],gg=["messageID","model","agent","noReply","tools","format","system","variant","parts"],k=(e,t,n=K,r=[],o)=>({method:e,path:t,query:n,body:r,bodyParam:o}),ob={"session.list":k("GET","/session",[...K,"scope","path","roots","start","search","limit"]),"session.get":k("GET","/session/{sessionID}"),"session.create":k("POST","/session",K,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":k("DELETE","/session/{sessionID}"),"session.update":k("PATCH","/session/{sessionID}",K,["title","metadata","permission","time"]),"session.status":k("GET","/session/status"),"session.messages":k("GET","/session/{sessionID}/message",[...K,"limit","before"]),"session.prompt":k("POST","/session/{sessionID}/message",K,gg),"session.promptAsync":k("POST","/session/{sessionID}/prompt_async",K,gg),"session.abort":k("POST","/session/{sessionID}/abort"),"session.revert":k("POST","/session/{sessionID}/revert",K,["messageID","partID"]),"session.unrevert":k("POST","/session/{sessionID}/unrevert"),"session.summarize":k("POST","/session/{sessionID}/summarize",K,["providerID","modelID","auto"]),"session.command":k("POST","/session/{sessionID}/command",K,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":k("POST","/session/{sessionID}/share"),"session.unshare":k("DELETE","/session/{sessionID}/share"),"session.fork":k("POST","/session/{sessionID}/fork",K,["messageID"]),"session.diff":k("GET","/session/{sessionID}/diff",[...K,"messageID"]),"session.todo":k("GET","/session/{sessionID}/todo"),"permission.list":k("GET","/permission"),"permission.reply":k("POST","/permission/{requestID}/reply",K,["reply","message"]),"question.list":k("GET","/question"),"question.reply":k("POST","/question/{requestID}/reply",K,["answers"]),"question.reject":k("POST","/question/{requestID}/reject"),"part.update":k("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",K,[],"part"),"part.delete":k("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":k("GET","/file",[...K,"path"]),"file.read":k("GET","/file/content",[...K,"path"]),"find.files":k("GET","/find/file",[...K,"query","dirs","type","limit"]),"vcs.diff":k("GET","/vcs/diff",[...K,"mode","context"]),"global.health":k("GET","/global/health",[]),"global.dispose":k("POST","/global/dispose",[]),"global.config.get":k("GET","/global/config",[]),"global.config.update":k("PATCH","/global/config",[],[],"config"),"provider.list":k("GET","/provider"),"provider.auth":k("GET","/provider/auth"),"provider.oauth.authorize":k("POST","/provider/{providerID}/oauth/authorize",K,["method","inputs"]),"provider.oauth.callback":k("POST","/provider/{providerID}/oauth/callback",K,["method","code"]),"auth.set":k("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":k("GET","/agent"),"app.skills":k("GET","/skill"),"app.log":k("POST","/log",K,["service","level","message","extra"]),"command.list":k("GET","/command"),"tool.ids":k("GET","/experimental/tool/ids"),"tool.list":k("GET","/experimental/tool",[...K,"provider","model"]),"mcp.status":k("GET","/mcp"),"mcp.add":k("POST","/mcp",K,["name","config"]),"mcp.connect":k("POST","/mcp/{name}/connect"),"mcp.disconnect":k("POST","/mcp/{name}/disconnect"),"mcp.auth.start":k("POST","/mcp/{name}/auth"),"mcp.auth.callback":k("POST","/mcp/{name}/auth/callback",K,["code"]),"mcp.auth.remove":k("DELETE","/mcp/{name}/auth"),"project.list":k("GET","/project"),"project.current":k("GET","/project/current"),"path.get":k("GET","/path")};function sb(e,t){let n=[];for(let r of e.query){let o=t[r];o!=null&&n.push(`${r}=${encodeURIComponent(String(o))}`)}return n.length?`?${n.join("&")}`:""}function ib(e,t,n={},r={}){let o=ob[t],s=o.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(o.bodyParam)i=n[o.bodyParam],a=i!==void 0;else for(let p of o.body)p in n&&(i={...i,[p]:n[p]},a=!0);let c=new Headers(r.headers);return a&&c.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${s}${sb(o,n)}`,{method:o.method,headers:c,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function ab(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 cb(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=ab(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let o=await r.text(),s=o;try{s=JSON.parse(o)}catch{}return{error:s||{},request:t,response:r}}function No(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let o=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!o.ok)throw Object.assign(new Error(`SSE failed: ${o.status} ${o.statusText}`),{status:o.status});if(!o.body)throw new Error("No body in SSE response");let s=o.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{s.cancel()}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:c,value:p}=await s.read();if(c)break;a=(a+p).replace(/\r\n/g,`
16
16
  `).replace(/\r/g,`
17
17
  `);let d=a.split(`
18
18
 
19
19
  `);a=d.pop()??"";for(let g of d){let m={},f=[];for(let h of g.split(`
20
20
  `))if(h.startsWith("data:"))f.push(h.replace(/^data:\s*/,""));else if(h.startsWith("id:"))m.id=h.replace(/^id:\s*/,"");else if(h.startsWith("retry:")){let w=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(w)||(m.retry=w)}f.length&&(m.data=f.join(`
21
- `)),yield m}}}finally{r.removeEventListener("abort",i),s.releaseLock()}}}async function*cb(e,t,n){let r=e.eventTransport??No(e.fetch??globalThis.fetch),o=n.signal??new AbortController().signal,s=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!o.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal:o}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(s=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(c){if(n.onSseError?.(c),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(s*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function Dt(e){let t=o=>(s,i)=>ab(e,sb(e.baseUrl,o,s,i)),n=o=>s=>t(o)(void 0,s);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(o={})=>({stream:cb(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,o)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var gg=200;async function lb(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 Fe(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new b(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function mg(e){let t=e.runtimeUrl.replace(/\/$/,""),n=Dt({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let o=encodeURIComponent(r.conversationId??e.rootId),s=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${o}${d.size?`?${d}`:""}`,m=w=>e.fetch(new Request(`${t}${w}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new b(`Reading the session transcript failed: ${await lb(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await s(r.limit===void 0?void 0:Math.min(r.limit,gg),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await s(Math.min(r.limit-a.length,gg),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,o,s]=await Promise.all([n.session.status().then(i=>Fe(i,"Reading the session status failed")),n.permission.list().then(i=>Fe(i,"Reading permission requests failed")),n.question.list().then(i=>Fe(i,"Reading questions failed"))]);return{statuses:r??{},permissions:o??[],questions:s??[]}},answerPermission:async(r,o,s)=>{Fe(await n.permission.reply({requestID:r,reply:o,...s!==void 0?{message:s}:{}}),"Answering the permission request failed")},answerQuestion:async(r,o)=>{if(o===null){Fe(await n.question.reject({requestID:r}),"Dismissing the question failed");return}Fe(await n.question.reply({requestID:r,answers:o}),"Answering the question failed")},compact:async r=>{let o=r;if(!o){let s=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof s?.model=="string"?s.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(o={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!o)throw new b("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return Fe(await n.session.summarize({sessionID:e.rootId,providerID:o.providerID,modelID:o.modelID}),"Compacting the session failed"),o}}}function fg(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return mg({runtimeUrl:r,rootId:n,fetch:D})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,o)=>(await t()).answerPermission(n,r,o),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function yg(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await Dl(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var $t=BigInt(4096),Ce=BigInt(0xffffffffffff),hg=Ce+BigInt(1),ub=hg/BigInt(2),Ne=BigInt(3600*1e3)*$t,Ko=120*1e3,pb=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,db=/^msg_([0-9a-f]{12})/,bg="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function at(e){let t=db.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function Ut(e){return BigInt(Math.trunc(e))*$t&Ce}function ct(e,t){let n=e-t&Ce;return n>=ub&&(n-=hg),n}function _g(e){let t=null;for(let n of e)n!=null&&(t===null||ct(n,t)>BigInt(0))&&(t=n);return t}function gb(e,t){let n=at(e);return n===null?!1:ct(n,Ut(t))>Ne}function mb(e,t){let n=t===void 0?null:Ut(t);return Pg(e,r=>n===null||ct(r,n)<=Ne)}function Pg(e,t){let n=[];for(let r of e){let o=at(r);o!==null&&t(o)&&n.push(o)}return _g(n)}function fb(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=bg[n%62])}return e}function xg(e){let t=e.random,n=Ut(e.nowMs-(e.backdateMs??Ko)),r=e.newestKnownTime??null;if(r!==null){let s=ct(r,n);s>=BigInt(0)&&s<=Ne&&(n=r+BigInt(1)&Ce)}let o="";if(t)for(let s=0;s<14;s++)o+=bg[Math.min(61,Math.floor(t()*62))];else o=fb();return{id:`msg_${n.toString(16).padStart(12,"0")}${o}`,time:n}}function qo(e={}){let t=e.nowMs??Date.now(),n=Ut(t-Ko),r=Pg(e.after??[],o=>{let s=ct(o,n);return s>=BigInt(0)&&s<=Ne});return xg({nowMs:t,newestKnownTime:r}).id}function Sg(e){return{scope:()=>Ol(e.projectId,e.sessionId),providerSecretPool:{list:()=>Na(e.projectId,e.sessionId),get:t=>Fa(e.projectId,e.sessionId,t),set:(t,n)=>Ka(e.projectId,e.sessionId,t,n)},rescope:t=>jl(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,o=n?.agent??e.agent,s=r&&o?{}:await e.persistedPromptDefaults(),i=r??s.model,a=o??s.agent,c=qo(),p=await $n(e.projectId,e.sessionId,{clientMessageId:c,messageId:c,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new b("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var eO="kortix.transcript.v1",yb=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function tO(e){return typeof e=="string"&&yb.includes(e)}var nO=["once","always","reject"],rO=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];function Pe(){let e=lg();return e||(R().billingEnabled??!1?"":zl())}async function Go(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Bo(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function wg(e){let t=Bo(e),n=await D(`${t}/env`);if(!n.ok)throw new Error(await Go(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function vg(e,t,n){let r=Bo(e),o=await D(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!o.ok)throw new Error(await Go(o,"Failed to save secret"))}async function Ag(e,t){let n=Bo(e),r=await D(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Go(r,"Failed to delete secret"))}var hb={list:wg,set:vg,delete:Ag};async function bb(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let o=await D(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),s=await o.json();if(!o.ok)throw new Error(s?.error||s?.message||`Request failed with ${o.status}`);return s}async function Yn(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function Lt(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return de(e)}async function kg(e){let t=Lt(e),n=await D(`${t}/kortix/pty`);if(!n.ok)throw new Error(await Yn(n,"Failed to list terminals"));return n.json()}async function Rg(e,t){let n=Lt(e),r=await D(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await Yn(r,"Failed to create terminal"));return r.json()}async function Ig(e,t,n){let r=Lt(e),o=await D(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(await Yn(o,"Failed to update terminal"));return o.json()}async function Tg(e,t){let n=Lt(e),r=await D(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Yn(r,"Failed to remove terminal"))}async function Cg(e,t,n){let r=Lt(t),s=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),de(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await wt();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${s}${s.includes("?")?"&":"?"}${c}`:s}function _b(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 Ee="\x1B",Eg="\x07",Pb="\0",Wo=`(?:${Eg}|${Ee}\\\\)`,xb=[new RegExp(`${Ee}\\]697;[^${Eg}${Ee}]*${Wo}`,"g"),new RegExp(`${Pb}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${Ee}\\][0-9]+;rgb:[0-9a-fA-F/]+${Wo}`,"g"),new RegExp(`${Ee}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Wo}`,"g"),new RegExp(`${Ee}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${Ee}\\[\\d+;\\d+R`,"g"),new RegExp(`${Ee}\\[\\?[0-9;]*c`,"g")];function Sb(e){let t=e;for(let n of xb)t=t.replace(n,"");return t}var wb={list:kg,create:Rg,update:Ig,remove:Tg,webSocketUrl:Cg};async function I(e,t,n,r){let o=e;for(;o.endsWith("/");)o=o.slice(0,-1);let s=await D(`${o}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await s.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!s.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${s.status}`);return a}async function _O(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return I(e,`/kortix/tasks${r}`)}async function PO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function xO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function SO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function wO(e,t){return I(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function vO(e,t,n){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function AO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function kO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function RO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function IO(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return I(e,`/kortix/tickets${n}`)}async function TO(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function CO(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function EO(e,t){return I(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function MO(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function OO(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function jO(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function DO(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function $O(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function UO(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function LO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function FO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function NO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function KO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function qO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function GO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function BO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function WO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function HO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function VO(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function zO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function YO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function QO(e,t,n=200){return I(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function XO(e){return I(e,"/kortix/projects")}async function JO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function ZO(e,t){return I(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function ej(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function tj(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function nj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function rj(e,t,n="all"){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function oj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function sj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function ij(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function aj(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function cj(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function lj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function uj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function pj(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function dj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function gj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function mj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function fj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var vb=1e4,Ab={retryOnAuthError:!1};function lt(e,t,n){return I(e,t,{signal:AbortSignal.timeout(vb),...n},Ab)}async function yj(e,t=!1){return(await lt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function hj(e){return(await lt(e,"/kortix/services/templates")).templates??[]}async function bj(e,t){return(await lt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function _j(e,t,n){let r=n==="delete",o=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return lt(e,o,{method:r?"DELETE":"POST"})}async function Pj(e,t){return lt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function xj(e,t){return lt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Qn=new Map,Ft=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function Ke(){let e=Pe();if(!e)throw new Ft;return xe(e)}function xe(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Qn.get(e);if(t)return t;if(!$r())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=Dt({baseUrl:e,fetch:D,eventTransport:kb});return Qn.set(e,n),n}var kb=async function*(e){let t=R().eventStreamTransport;if(!t){yield*No(D)(e);return}let{headers:n,rejected:r}=await si(e.url,e.headers);try{yield*t({...e,headers:n})}catch(o){throw o?.status===401&&r(),o}};function Tj(e){Qn.delete(e)}function Cj(){Qn.clear()}var Xn=new Map;function Ej(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=Xn.get(e);if(t)return t;let n=Dt({baseUrl:e,fetch});return Xn.set(e,n),n}function Mj(e){Xn.delete(e)}function Oj(){Xn.clear()}async function Rb(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 jj(e){let t=Pe();if(!t)throw new b("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await D(`${t}${n}`,{method:"POST"}),o=r.headers.get("content-type")??"",s=/^application\/([\w.+-]+\+)?json\b/i.test(o.trim());if(!r.ok)throw new b(`System reload failed (${r.status}): ${await Rb(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!s)throw new b(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new b(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var Mg="frontend";function Jn(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Mg}] ${t}`,...n?[n]:[]);try{Ke().app.log({service:Mg,level:e,message:t,extra:n})}catch{}}var Me={debug:(e,t)=>Jn("debug",e,t),info:(e,t)=>Jn("info",e,t),warn:(e,t)=>Jn("warn",e,t),error:(e,t)=>Jn("error",e,t)};function Ib(e){return{type:"heartbeat-gap",gapMs:e}}function Tb(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 Cb={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Eb=16,Mb=8,Ob=6e4,jb=5e3,Db=250,$b=1e3,Ub=3e4,Lb=5,Fb=3e3,Nb=3e4,Kb=2e4,qb=2e3,Gb=8;function Bb(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function Wb(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let o=e.coalesced??[e];return o.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:o}}function Og(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}var Zn=new WeakMap;function Hb(e,t,n){let r=t.timers??Cb,o=t.connectTimeoutMs??Kb,s=t.heartbeatTimeoutMs??Ob,i=t.maxConsecutiveHardFailures??Gb,a=new AbortController;function c(y,...P){for(let v of n){let $=y(v);if($)try{$(...P)}catch(x){console.warn("[opencode-events] subscriber handler threw, skipping",x)}}}let p=null,d=y=>{p!==y&&(p=y,y&&c(P=>P.onConnectionChange,y))},g=r.now(),m=null,f=[],h,w=0,L=new Map,O=()=>{if(h&&r.clearTimeout(h),h=void 0,f.length===0)return;let y=f;f=[],L.clear(),w=r.now(),g=r.now();for(let P of y)P&&c(v=>v.onEvent,P.event)},j=()=>{if(h)return;let y=r.now()-w;h=r.setTimeout(O,Math.max(0,Eb-y))};return(async()=>{let y=0,P=0;for(;!a.signal.aborted;){let v=!1,$=!1,x=!1,_,A,T=null,C=r.now(),E=new AbortController;d("connecting");let N=Og(a.signal);N.promise.then(()=>E.abort());try{let ie=await new Promise((Ve,je)=>{let ne=!1;A=r.setTimeout(()=>{ne||(ne=!0,Me.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:o}),E.abort(),je(new Error(`SSE connect timed out after ${o}ms`)))},o),e.global.event({signal:E.signal,sseDefaultRetryDelay:Fb,sseMaxRetryDelay:Nb,sseMaxRetryAttempts:1}).then(fe=>{ne||(ne=!0,r.clearTimeout(A),Ve(fe))},fe=>{ne||(ne=!0,r.clearTimeout(A),je(fe))})}),{stream:V}=ie;if(m){let Ve=r.now()-m.lastActivityAt,je=m.eventful;m=null,(je||Ve>jb)&&c(ne=>ne.onGapRehydrate,Ve)}g=r.now();let ee=()=>{r.clearTimeout(_),_=r.setTimeout(()=>{Me.warn("SSE heartbeat timeout, forcing reconnect"),E.abort()},s)};ee();let He=r.now(),Sy=V[Symbol.asyncIterator]();for(;!E.signal.aborted;){let Ve=Sy.next().then(ye=>({kind:"next",result:ye}),ye=>({kind:"error",error:ye})),je=Og(E.signal),ne=await Promise.race([Ve,je.promise.then(()=>({kind:"aborted"}))]);if(je.cleanup(),ne.kind==="aborted")break;if(ne.kind==="error")throw ne.error;if(ne.result.done)break;v=!0,d("open"),ee();let fe=ne.result.value,ze=fe&&typeof fe=="object"&&"payload"in fe?fe.payload:fe;if(!ze?.type)continue;ze.type!=="server.connected"&&($=!0);let Or=Wb(f[f.length-1]?.event,ze);if(Or)f[f.length-1]={type:Or.type,event:Or};else{let ye=Bb(ze);if(ye){let Ns=L.get(ye);Ns!==void 0&&(f[Ns]=void 0),L.set(ye,f.length)}f.push({type:ze.type,event:ze})}j(),!(r.now()-He<Mb)&&(He=r.now(),await new Promise(ye=>r.setTimeout(ye,0)))}x=v}catch(ie){if(a.signal.aborted)break;T=ie;let V=String(ie),ee=V.includes("401")||V.includes("403")||V.includes("Unauthorized")||V.includes("Token refresh failed");if(Me.error("SSE event stream error",{error:V,retryCount:y,isAuthError:ee}),ee)try{Qr(),await Yr(),Me.info("SSE: refreshed auth token after auth error")}catch(He){Me.error("SSE: failed to refresh auth token",{error:String(He)})}}finally{r.clearTimeout(_),r.clearTimeout(A),E.abort(),N.cleanup(),O()}if(a.signal.aborted)break;let Z=r.now()-C,Y=T?.cause?.status;if(P=!v&&(typeof Y=="number"&&Y>=400||Z<qb)?P+1:0,P>=i){Me.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:P,lastError:String(T)}),p=null,c(ie=>ie.onParked,{consecutiveFailures:P,lastError:T});break}d("lost"),m={lastActivityAt:g,eventful:(m?.eventful??!1)||$},x?y=0:(y++,y>1&&Me.warn("SSE event stream reconnecting",{retryCount:y}));let Ae=x?Db:Math.min($b*2**Math.min(y-1,Lb),Ub);await new Promise(ie=>{let V=r.setTimeout(ie,Ae),ee=()=>{r.clearTimeout(V),ie()};a.signal.addEventListener("abort",ee,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,teardown:()=>{p=null,a.abort(),h&&r.clearTimeout(h)}}}function Ho(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o,signal:s}=e,i=e.client??(e.url?xe(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o},c=Zn.get(i);if(!c)c=Hb(i,e,new Set([a])),Zn.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&o?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,s&&s.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),Zn.get(i)===p&&Zn.delete(i)))},m=()=>g();return s&&(s.aborted?g():s.addEventListener("abort",m,{once:!0})),{close:g}}function jg(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return xe(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return xe(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return xe(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return Ho({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Lg(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new b(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function ut(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function Q(e){let t=(e??Pe()).trim();if(!t)throw new Ft;return t}async function tr(e,t){let n=await D(`${Q(t)}${e}`);if(!n.ok)throw new b(await ut(n),{status:n.status,response:n});return n.json()}var Yo=["/workspace","/tmp","/home","/opt"],Vb=Yo.filter(e=>e!=="/workspace");function Fg(e){return Yo.some(t=>e===t||e.startsWith(`${t}/`))}function Gt(e){return Fg(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function pt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(Vb.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Ng=pt;async function Bt(e,t){let n=Q(t),r=pt(e)||".";return(await tr(`/file?path=${encodeURIComponent(r)}`,n)).map(s=>({...s,path:s.absolute||`/workspace/${s.path}`}))}async function Wt(e,t){let n=Q(t),r=pt(e),o=await D(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!o.ok)throw new b(await ut(o),{status:o.status,response:o});return o.json()}async function zb(e,t,n){let r=Q(n),o=pt(e),s=await D(`${r}/file/raw?path=${encodeURIComponent(o)}`);if(!s.ok)throw new b(await ut(s),{status:s.status,response:s});if((s.headers.get("content-type")||"").includes("text/html"))throw new b("File could not be loaded (raw byte route unavailable)",{status:s.status,response:s,code:"INVALID_CONTENT_TYPE"});let i=await s.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}async function Ht(e,t){let n=Q(t);try{return await zb(e,void 0,n)}catch{}let r=await Wt(e,n);if(r.encoding==="base64"&&r.content){let o=Uint8Array.from(atob(r.content),s=>s.charCodeAt(0));return new Blob([o],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}async function nr(e){return tr("/file/status",Q(e))}async function rr(e,t,n){let r=Q(n),o=new URLSearchParams({query:e});return t?.type&&o.set("type",t.type),t?.limit&&o.set("limit",String(t.limit)),tr(`/find/file?${o.toString()}`,r)}async function or(e,t){let n=Q(t);return(await tr(`/find?pattern=${encodeURIComponent(e)}`,n)).map(o=>({path:typeof o.path=="string"?o.path:o.path?.text??"",lines:typeof o.lines=="string"?o.lines:o.lines?.text??"",line_number:o.line_number,absolute_offset:o.absolute_offset,submatches:(o.submatches??[]).map(s=>({start:s.start,end:s.end}))}))}var Nt=[400,1200],Yb=e=>e===408||e===429||e===502||e===503||e===504,Dg=e=>new Promise(t=>setTimeout(t,e));function Qb(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Vo=3e4,Xb=15*6e4,Jb=256;function Kt(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Vo;let t=Vo+e/Jb;return Math.min(Xb,Math.max(Vo,Math.round(t)))}async function Zb(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 er(e,t){let n;for(let o=0;o<=Nt.length;o++){let s;try{s=await t(e())}catch(a){if(n=a,Qb(a)||o===Nt.length)break;await Dg(Nt[o]);continue}if(s.ok)return s.json();let i=await Zb(s);if(n=new b(`Upload failed (${s.status}): ${i}`,{status:s.status,response:s}),!Yb(s.status)||o===Nt.length)throw n;await Dg(Nt[o])}if(n instanceof b)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new b(`Upload failed: ${r}`)}var zo=8*1024*1024;function e_(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new b(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function $g(e,t){try{e?.onProgress?.(t)}catch{}}function Ug(e,t,n){let r=new FormData,o=(t??"").trim();return o&&r.append("path",o.startsWith("/")?o:`/${o}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function t_(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function Vt(e,t,n,r,o){let s=typeof r=="string"?r:void 0,i=typeof r=="string"?o:r,a=Q(s),c=Kt(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=zo){let f=await er(()=>Ug(e,t,p),h=>D(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return e_(f[0],e.size),$g(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await er(()=>Ug(new Blob([],{type:e.type}),t,p),f=>D(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:Kt(0)})))[0]?.path;if(!g)throw new b("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=t_(g);if(!m.name)throw new b(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=zo){let h=Math.min(e.size,f+zo),w=e.slice(f,h,e.type),L=await er(()=>{let O=new FormData;return m.parent&&O.append("path",m.parent),O.append("filename",m.name),O.append("first",f===0?"true":"false"),O.append("offset",String(f)),O.append("file",w,m.name),O},O=>D(`${a}/file/append`,{method:"POST",body:O},{timeoutMs:Kt(w.size)}));if(L.path!==g||L.size!==h)throw new b(`Upload verification failed for ${g}: expected ${h} bytes, received ${L.size}`,{code:"UPLOAD_SIZE_MISMATCH"});$g(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await dt(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function n_(e,t,n){let r=Q(n),o=Kt(t.size);return er(()=>{let s=new FormData;return s.append(e,t,e.split("/").pop()||"file"),s},s=>D(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:o}))}var qt=class extends b{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function sr(e,t){let n=Q(t),r=e.trim(),s=(r.startsWith("/")?r:`/${r}`).split("/"),i=s.pop()||"untitled",a=s.join("/")||"/workspace",c=Gt(`${a}/${i}`),p=[];try{p=await Bt(Kg(c),n)}catch(g){if(!(g instanceof b&&g.status===404))throw g}if(p.some(g=>g.name===qg(c)))throw new qt(c);let d=await Gg(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function ir(e,t,n){let r=Q(n);return n_(t,await Ht(e,r),r)}function r_(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Kg(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function qg(e){return e.slice(e.lastIndexOf("/")+1)}function o_(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function ar(e,t,n){let r=Q(n),o=Gt(r_(e.trim()));return Gg(o,t,r,{overwrite:!0})}async function Gg(e,t,n,r){let o=qg(e);if(!o)throw new b(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let s=Kg(e);await zt(s,n).catch(()=>{});let i=o_(),a=await Vt(t,s,`.${o}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new b(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=Gt(c);try{await Bg(p,e,n,r.overwrite)}catch(g){throw await dt(p,n).catch(()=>{}),!r.overwrite&&g instanceof b&&g.status===409?new qt(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function dt(e,t){let n=await D(`${Q(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Delete failed (${n.status}): ${await ut(n)}`,{status:n.status,response:n});return n.json()}async function zt(e,t){let n=await D(`${Q(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Mkdir failed (${n.status}): ${await ut(n)}`,{status:n.status,response:n});return n.json()}async function cr(e,t,n){return Bg(e,t,Q(n),!0)}async function Bg(e,t,n,r){let o=await D(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!o.ok)throw new b(`Rename failed (${o.status}): ${await ut(o)}`,{status:o.status,response:o});return o.json()}async function Wg(){return Lg(await Ke().project.current())}async function Qo(){return Lg(await Ke().global.health())}async function Hg(){try{return(await Qo()).healthy===!0}catch{return!1}}var s_={list:Bt,read:Wt,readBlob:Ht,status:nr,findFiles:rr,findText:or,upload:Vt,write:ar,create:sr,copy:ir,remove:dt,mkdir:zt,rename:cr,currentProject:Wg,health:Qo,isReachable:Hg,toDaemonPath:pt,toSandboxAbsolutePath:Gt,toWorkspaceRelative:Ng};function Vg(e){return{list:async t=>Bt(t,(await e()).runtimeUrl),read:async t=>Wt(t,(await e()).runtimeUrl),readBlob:async t=>Ht(t,(await e()).runtimeUrl),status:async()=>nr((await e()).runtimeUrl),findFiles:async(t,n)=>rr(t,n,(await e()).runtimeUrl),findText:async t=>or(t,(await e()).runtimeUrl),upload:async(t,n,r,o)=>Vt(t,n,r,(await e()).runtimeUrl,o),write:async(t,n)=>ar(t,n,(await e()).runtimeUrl),create:async t=>sr(t,(await e()).runtimeUrl),copy:async(t,n)=>ir(t,n,(await e()).runtimeUrl),remove:async t=>dt(t,(await e()).runtimeUrl),mkdir:async t=>zt(t,(await e()).runtimeUrl),rename:async(t,n)=>cr(t,n,(await e()).runtimeUrl)}}function zg(e){return{get:t=>Dn(e.projectId,e.sessionId,t),presence:t=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1}),cost:()=>qn(e.sessionId,{projectId:e.projectId}),update:t=>Il(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),Tl(e.projectId,e.sessionId)),start:(...t)=>Ue(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Un(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Ln(e.projectId,e.sessionId)),configState:()=>Cl(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),El(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),Ml(e.projectId,e.sessionId,...t)),setSharing:t=>pl(e.projectId,e.sessionId,t),previews:()=>gl(e.projectId,e.sessionId),participants:()=>dl(e.projectId,e.sessionId),commit:t=>al(e.projectId,e.sessionId,t),publicShares:{list:()=>ml(e.projectId,e.sessionId),create:(...t)=>fl(e.projectId,e.sessionId,...t),revoke:(...t)=>yl(e.projectId,e.sessionId,...t)}}}function Yg(e){return{reminders:{list:()=>zp(e.projectId,e.sessionId),create:t=>Yp(e.projectId,e.sessionId,t),update:(t,n)=>Qp(e.projectId,e.sessionId,t,n),remove:t=>Xp(e.projectId,e.sessionId,t)},audit:(t,n)=>_l(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Hd(e.projectId,e.sessionId,t,n),read:(t,n)=>Vd(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Pl(e.projectId,e.sessionId,t),messageAuthors:()=>Ul(e.projectId,e.sessionId),transcriptSync:t=>xl(e.projectId,e.sessionId,t),turn:()=>Sl(e.projectId,e.sessionId),prompts:{create:t=>$n(e.projectId,e.sessionId,t),list:()=>wl(e.projectId,e.sessionId),remove:t=>vl(e.projectId,e.sessionId,t),retry:t=>kl(e.projectId,e.sessionId,t),edit:(t,n)=>Al(e.projectId,e.sessionId,t,n),hold:t=>Rl(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function a_(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var c_=["control_plane","provider_ingress","daemon","upstream_port"];function Qg(e){return typeof e=="string"&&c_.includes(e)?e:null}function Xg(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 Jg(e,t){let n=(e===void 0?Pe():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await D(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),o=await r.text().catch(()=>""),s=null;try{s=o?JSON.parse(o):null}catch{s=null}let i=s,a=Qg(r.headers.get("X-Kortix-Proxy-Hop"))??Qg(s?.hop),c=Number(r.headers.get("X-Kortix-Upstream-Status")),p=s?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:o,hop:a,upstreamStatus:d}}var Zg=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,em=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,tm=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,nm=new Set([22,4096,parseInt(Ie.KORTIX_MASTER,10)]);function l_(e){return em.test(e)}function lr(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 u_(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var p_=new Set(["'",'"',"`","<","(","["]),d_=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function g_(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&&p_.has(e[t]);)t++;for(;n>t&&d_.has(e[n-1]);)n--;return e.slice(t,n)}function m_(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var f_=/^\/proxy\/(\d{1,5})(\/.*)?$/,y_=/^\/(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 h_(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:y_.test(t.pathname)}catch{return!1}}function ur(e){if(!e)return null;let t=g_(u_(e.trim())),n=am(t);if(n){let r=lr(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let o=parseInt(r.port,10);if(!Number.isInteger(o)||o<1||o>65535)return null;let s=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(Ie.KORTIX_MASTER,10);if(o===i){let c=r.pathname.match(f_);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return o=p,s=lr(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${o}${s}`,port:o,path:s}}}let a=lr(s);return{originalUrl:`${r.protocol}//${r.hostname}:${o}${a}`,port:o,path:a}}catch{let r=m_(e);return r&&r!==e?ur(r):null}}function b_(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let o=/`[^`\n]+`/g;for(;(r=o.exec(e))!==null;){let s=r.index,i=s+r[0].length;t.some(([c,p])=>s>=c&&i<=p)||t.push([s,i])}return t}function __(e,t){return t.some(([n,r])=>e>=n&&e<r)}function P_(e){let t=[],n=new Set,r=b_(e);Zg.lastIndex=0;let o;for(;(o=Zg.exec(e))!==null;){let s=ur(o[0]);if(!s)continue;let{originalUrl:i,port:a,path:c}=s;a<1||a>65535||nm.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:o.index,endIndex:o.index+i.length,inCodeBlock:__(o.index,r)}))}return t}function lD(e){return P_(e).length>0}function x_(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function rm(e){return e.trim().toLowerCase().split("_").join("-")}function om(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function S_(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let o=r.split("{port}").join(String(e)).split("{sandbox}").join(rm(n.sandboxId));return`${om(o)}${t}`}function w_(e){return e.sandboxId.trim().length>0}function qe(e,t,n){let r=lr(t);if(!w_(n))return R_(e,r);let o=S_(e,r,n);return o||(x_(n.apiBaseUrl)?`http://p${e}-${rm(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${om(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function uD(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(o=>encodeURIComponent(o)).join("/");return qe(3211,`/open?path=/workspace/${r}`,t)}function v_(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function pD(e){return`http://localhost:3211${v_(e)}`}function A_(){return"/health"}function dD(e){return qe(3211,A_(),e)}function gD(e,t){return qe(e,"/",t)}function k_(e){let t=ur(e);return!(!t||nm.has(t.port)||h_(e))}function sm(e,t){if(!e)return e;let n=ur(e);return n?k_(n.originalUrl)?qe(n.port,n.path,t):n.originalUrl:e}function R_(e,t="/"){return`http://localhost:${e}${t}`}var im=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function am(e){let t=e.match(em);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(tm);if(n){let o=443;try{let s=new URL(e);o=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:o,path:n[4]||"/"}}let r=e.match(im);if(r)try{let o=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(o.port,10)||(o.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function mD(e){try{let t=am(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function fD(e){return l_(e)||tm.test(e)||im.test(e)}function yD(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Yt="/web-proxy/";function hD(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),o=`${Yt}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,s=parseInt(Ie.KORTIX_MASTER,10);return`${qe(s,"/",t).replace(/\/$/,"")}${o}`}catch{return null}}function bD(e){try{let t=new URL(e),n=t.pathname.indexOf(Yt);if(n===-1)return null;let o=t.pathname.slice(n+Yt.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!o)return null;let s=o[1],i=o[2],a=o[3]||"/";return`${s}://${i}${a}${t.search}${t.hash}`}catch{return null}}function _D(e){try{return new URL(e).pathname.includes(Yt)}catch{return e.includes(Yt)}}function PD(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 xD(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 cm(e){return{health:t=>Jg(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>qe(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>sm(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>tt(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Xo(e,t,n,r){let o,s,{persistedPromptDefaults:i,clearPersistedDefaults:a}=ig(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=pg(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return o},set model(f){o=f},get agent(){return s},set agent(f){s=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...zg(m),...Yg(m),...cm(m),...yg(m),...Sg(m),...jg(m),files:Vg(c),...fg(m),get runtime(){return xe(d("runtime").runtimeUrl)}}}function lm(e){return{apps:{list:()=>vd(e),create:t=>Ad(e,t),get:t=>kd(e,t),update:(...t)=>Rd(e,...t),access:{get:(...t)=>Td(e,...t),update:(...t)=>Ed(e,...t),session:(...t)=>Md(e,...t),agents:t=>Cd(e,t)},remove:t=>Id(e,t),artifacts:{register:t=>go(e,t),uploadArchive:(...t)=>Od(e,...t),finalize:(...t)=>mo(e,...t)},deployments:{create:(...t)=>jd(e,...t),list:t=>Dd(e,t),get:(...t)=>$d(e,...t),logs:(...t)=>Ud(e,...t),remove:(...t)=>Nd(e,...t)},start:t=>Ld(e,t),stop:t=>Fd(e,t),rollback:(...t)=>Kd(e,...t)}}}function um(e){return{list:()=>oa(e),invite:(...t)=>aa(e,...t),update:(...t)=>sa(e,...t),revoke:t=>ia(e,t),pendingInvites:()=>ca(e),resendInvite:(...t)=>ua(e,...t),revokeInvite:(...t)=>la(e,...t),requests:()=>ta(e),approveRequest:(...t)=>na(e,...t),rejectRequest:(...t)=>ra(e,...t),groupGrants:()=>pa(e),attachGroupGrant:(...t)=>da(e,...t),updateGroupGrant:(...t)=>ga(e,...t),detachGroupGrant:t=>ma(e,t),resourceGrants:{list:()=>fa(e),create:t=>ya(e,t),remove:t=>ha(e,t)}}}function pm(e){return{tokens:{list:()=>od(e),create:t=>sd(e,t),revoke:t=>id(e,t)},setupLinks:{requestSecret:t=>md(e,t),requestConnector:t=>fd(e,t)},validateManifest:t=>Oi(e,t),gitToken:()=>ji(e),agentIdentities:()=>yp(e),secrets:{list:()=>xa(e),upsert:t=>Sa(e,t),setStrategy:(...t)=>wa(e,...t),broker:(...t)=>va(e,...t),remove:t=>Ia(e,t),setPersonal:(...t)=>Ta(e,...t),removePersonal:t=>Ca(e,t),setGitCredential:t=>Ra(e,t),listProviderOAuth:()=>Aa(e),startProviderOAuth:(...t)=>Hr(e,...t),pollProviderOAuth:(...t)=>Vr(e,...t),removeProviderOAuth:t=>ka(e,t)},access:um(e)}}function dm(e){return{list:()=>Va(e),listAll:()=>za(e),reconcile:(...t)=>Ya(e,...t),reconcileMember:(...t)=>Qa(e,...t),updateCredential:(...t)=>Xa(e,...t),revoke:(...t)=>Ja(e,...t),activate:(...t)=>Za(e,...t),setDefault:(...t)=>ec(e,...t),rename:(...t)=>tc(e,...t),share:(...t)=>rc(e,...t),addComputer:(...t)=>nc(e,...t),pipedreamConnect:(...t)=>oc(e,...t),pipedreamFinalize:(...t)=>sc(e,...t)}}function pr(e){return{catalog:t=>In(e,t),tools:()=>Xr(e),search:(...t)=>qa(e,...t),describe:(...t)=>Ga(e,...t),call:(...t)=>Ba(e,...t),accounts:(...t)=>Wa(e,...t),uploadAttachment:(...t)=>Ha(e,...t)}}var I_=100,T_=0,C_=new Set(["attachment_size_mismatch","attachment_failed"]),gm=()=>new b("Attachment expired. Attach the file again.",{code:"attachment_expired"});function mm(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 fm(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,o=new Set,s=new Set,i=0,a=!1,c,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,P){y.removalDeleted||(y.removalDeleted=!0,kt(e,P).catch(()=>{}))}function m(){c&&clearTimeout(c);let y=d().map(({item:v})=>v);(y.length!==p.attachments.length||y.some((v,$)=>v!==p.attachments[$]))&&(p={attachments:y});let P=Math.min(...y.filter(v=>v.status==="ready").map(v=>Date.parse(v.attachment.expires_at)));Number.isFinite(P)&&!a&&(c=setTimeout(()=>{for(let v of d())v.item.status==="ready"&&Date.parse(v.item.attachment.expires_at)<=Date.now()&&(v.item={...v.item,status:"error",error:gm()});m()},Math.min(2147483647,Math.max(0,P-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let v of o)v();for(let v of[...s])v()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(y){f();let P=d();if(P.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some($=>!Number.isSafeInteger($)||$<=0||$>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(P.reduce(($,x)=>$+x.item.size,0)+y.reduce(($,x)=>$+x,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function w(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let P=y.item.file;i++;let v=++y.generation,$=new AbortController;y.abort=$,y.item={...y.item,status:"uploading",error:void 0};let x=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===v,_,A=0,T,C=()=>{T=void 0,!(!x()||y.item.status!=="uploading"||_===void 0)&&(y.item={...y.item,receivedBytes:_},_=void 0,A=Date.now(),m())},E=N=>Math.floor(N*100/y.item.size);On(e,P,{resume:y.upload,signal:$.signal,onUpload:N=>{y.upload=N,y.removed&&($.abort(),g(y,N.attachment_id))},onProgress:N=>{if(!x()||E(N)===E(y.item.receivedBytes)||(_=N,T))return;let Z=A+I_-Date.now();if(Z<=0)return C();T=setTimeout(C,Z),typeof T=="object"&&"unref"in T&&T.unref()},onProcessing:()=>{T&&clearTimeout(T),T=void 0,_=void 0,x()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then(N=>{x()&&(y.item={...y.item,status:"ready",attachment:mm(N),receivedBytes:N.size})}).catch(N=>{N instanceof b&&C_.has(N.code??"")&&(y.upload=void 0),x()&&(y.item={...y.item,status:N instanceof b&&N.code==="ABORTED"?"aborted":"error",error:N instanceof Error?N:new Error(String(N))})}).finally(()=>{i--,T&&clearTimeout(T),y.abort===$&&(y.abort=void 0),m(),w()})}m()}function L(y){h(y.map(v=>v.size));let P=y.map(v=>{let $=`attachment-${++T_}`;return r.set($,{generation:0,item:{id:$,file:v,filename:v.name,mime:v.type||"application/octet-stream",size:v.size,status:"pending",receivedBytes:0}}),$});return m(),w(),P}function O(y){let P=r.get(y);!P||P.item.status==="ready"||(P.generation++,P.abort?.abort(),P.item={...P.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function j(y,{signal:P}={}){let v=[...y];return new Promise(($,x)=>{let _=()=>{s.delete(C),P?.removeEventListener("abort",T)},A=E=>{_(),x(E)},T=()=>A(le()),C=()=>{let E=!1;for(let Z of v){let Y=r.get(Z);if(!Y)return A(new Error("Attachment was removed before it was sent"));if(a&&!Y.handedOff)return A(new Error("Attachment controller is disposed"));if(Y.item.status==="error"||Y.item.status==="aborted")return A(Y.item.error??new Error("Attachment upload failed"));Y.item.status!=="ready"&&(E=!0)}if(E)return;let N;try{N=v.map(Z=>{let Y=mm(r.get(Z).item.attachment);return{type:"file",attachment_id:Y.attachment_id,filename:Y.filename,mime:Y.mime}})}catch(Z){return A(Z instanceof Error?Z:new Error(String(Z)))}_(),$(N)};if(P?.aborted)return T();s.add(C),P?.addEventListener("abort",T,{once:!0}),C()})}return{add:y=>L([y])[0],addMany:L,retry(y){let P=r.get(y);if(P?.handedOff||f(),!(!P||P.item.status==="ready"||P.item.status==="uploading"||P.item.status==="processing"||P.item.status==="pending")){if(!P.item.file||P.upload&&Date.parse(P.upload.expires_at)<=Date.now())throw gm();P.item={...P.item,status:"pending",error:void 0},w()}},async remove(y){let P=r.get(y);if(!P)return;P.removed=!0,P.generation++,r.delete(y);let v=P.upload?.attachment_id??P.item.attachment?.attachment_id;v&&P.abort?.abort(),m(),w(),v&&g(P,v)},abort:O,submit(y){if(!a){for(let P of y){let v=r.get(P);v&&(v.handedOff=!0)}m()}},reclaim(y){if(!a){for(let P of y){let v=r.get(P);v&&(v.handedOff=!1)}m()}},whenReady:j,forget(y=d().map(P=>P.item.id)){for(let P of y){let v=r.get(P);v&&(v.generation++,v.abort?.abort(),r.delete(P))}m(),w()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let P=y.upload?.attachment_id??y.item.attachment?.attachment_id;P&&e&&kt(e,P).catch(()=>{})}o.clear(),m()}},getSnapshot:()=>p,subscribe(y){return o.add(y),()=>{o.delete(y)}}}}function ym(e){return{attachments:{upload:(...t)=>On(e,...t),delete:(...t)=>kt(e,...t),createController:t=>fm(e,t)},get:t=>xn(e,t),detail:()=>Sn(e),audit:t=>cd(e,t),update:t=>An(e,t),archive:()=>kn(e),llmCatalog:()=>wn(e),modelPicker:()=>vn(e),modelAccess:()=>Bn(e),setModelAccess:t=>Wn(e,t),sandboxHealth:()=>Tn(e),onboardingComplete:(...t)=>Ki(e,...t)}}function hm(e){return{sessions:{list:t=>Ze(e,t),listPage:t=>ul(e,t),create:t=>et(e,t),ensureWarm:()=>hl(e),claimWarm:t=>bl(e,t)},review:{list:t=>$p(e,t),get:t=>Up(e,t),submit:t=>Lp(e,t),act:(...t)=>Fp(e,...t),bulkAct:t=>Np(e,t)},approvals:{list:t=>ba(e,t),resolve:(...t)=>Pa(e,...t),sessionsNeedingInput:t=>_a(e,t)}}}function bm(e){return{files:{list:t=>$c(e,t),read:(t,n)=>Lc(e,t,n),search:(...t)=>Uc(e,...t),archive:(...t)=>Fc(e,...t),history:(...t)=>Qc(e,...t)},git:{commits:()=>Vc(e),commit:t=>zc(e,t),commitDiff:t=>Yc(e,t),branches:()=>Hc(e),versionDiff:(...t)=>Xc(e,...t),inviteCollaborator:(...t)=>Mi(e,...t)},changeRequests:{list:()=>Jc(e),get:t=>Zc(e,t),diff:t=>el(e,t),mergePreview:t=>tl(e,t),open:(...t)=>nl(e,...t),merge:(...t)=>rl(e,...t),close:(...t)=>ol(e,...t),reopen:(...t)=>sl(e,...t),requestChanges:(...t)=>il(e,...t)},...hm(e)}}function _m(e){return{policies:{list:()=>Ac(e),set:(...t)=>kc(e,...t)},reminders:{list:()=>Jp(e)},triggers:{list:()=>Ll(e),create:(...t)=>Fl(e,...t),update:(...t)=>Nl(e,...t),remove:(...t)=>Kl(e,...t),fire:(...t)=>Gl(e,...t),setActivation:(...t)=>ql(e,...t)},...bm(e)}}function Pm(e,t){return{connectors:{...pr(e),list:()=>ic(e),config:(...n)=>gc(e,...n),create:(...n)=>yc(e,...n),remove:(...n)=>bc(e,...n),sync:()=>ac(e),auth:{discover:(...n)=>hc(e,...n)},setName:(...n)=>mc(e,...n),setCredentialMode:(...n)=>cc(e,...n),setAuthorizationStrategy:(...n)=>lc(e,...n),setCredential:(...n)=>wc(e,...n),setSensitive:(...n)=>uc(e,...n),connections:t,policies:{get:(...n)=>pc(e,...n),set:(...n)=>dc(e,...n)},pipedream:{listApps:(...n)=>_c(e,...n),listSections:(...n)=>Pc(e,...n),connect:(...n)=>fc(e,...n),finalize:(...n)=>vc(e,...n)},discover:{list:(...n)=>Jr(e,...n),sections:(...n)=>xc(e,...n),detail:(...n)=>Zr(e,...n)}},..._m(e)}}function xm(e){return{gateway:{logs:t=>Hu(e,t),log:t=>Vu(e,t),overview:t=>zu(e,t),series:t=>Yu(e,t),breakdown:t=>Qu(e,t),sessions:t=>Xu(e,t),errors:t=>Ju(e,t),budgets:()=>Zu(e),setBudget:t=>ep(e,t),deleteBudget:t=>tp(e,t),keys:()=>np(e),createKey:t=>rp(e,t),revokeKey:t=>op(e,t),routing:{get:()=>qu(e),set:t=>Gu(e,t),reset:()=>Bu(e),preview:t=>Wu(e,t)},playground:(t,n,r)=>sp(e,t,n,r)}}}function Sm(e){return{modelDefaults:{get:()=>Yl(e),set:t=>Ql(e,t),clear:t=>Xl(e,t)},setDefaultAgent:t=>eu(e,t),sandbox:{list:()=>Dc(e),snapshots:()=>Ic(e),rebuildSnapshot:t=>Tc(e,t),fixWithAgent:()=>Cc(e),createTemplate:t=>Ec(e,t),updateTemplate:(...t)=>Mc(e,...t),removeTemplate:t=>Oc(e,t),buildTemplate:t=>jc(e,t),setProvider:t=>Ni(e,t)},setAgentScope:(...t)=>Zl(e,...t)}}function wm(e){return{channels:{slack:{installation:()=>Ru(e),connect:t=>Iu(e,t),mode:()=>Tu(e),completeInstall:t=>Eu(e,t),manifest:()=>Ou(e),disconnect:()=>ju(e),getFile:t=>Du(e,t),uploadFile:t=>$u(e,t)},teams:{completeInstall:t=>Mu(e,t)},email:{installation:t=>Uu(e,t),mode:()=>Lu(e),connect:t=>Fu(e,t),disconnect:t=>Nu(e,t),updatePolicy:(...t)=>Ku(e,...t)}},updateFeatureFlag:(...t)=>Li(e,...t),updateExperimentalFeature:(...t)=>Fi(e,...t),...Sm(e)}}function E_(){return Ke()}function M_(e,t){Dr(e,t);let n=sg(e),{auth:r,accounts:o,iam:s,accountInvites:i}=eg(),{billing:a,sandboxShares:c}=Xd(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=Qd();function h(w){let L=dm(w);return{...ym(w),...lm(w),...pm(w),...Pm(w,L),...xm(w),...wm(w),session:O=>Xo(w,O,e,n)}}return{config:e,auth:r,accounts:o,iam:s,accountInvites:i,projects:p,connectors:pr(),project:h,session:(w,L)=>Xo(w,L,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,validateToken:Ti,runtime:E_}}function O_(){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 j_(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function gt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function D_(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function $_(e){if(gt(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 U_(e){let t=gt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function L_(e,t){let n=gt(e);if(n.length===0)return e;let r=e.pending.filter(o=>n.includes(o.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(o=>!n.includes(o.id)),failed:[...e.failed,...r.map(o=>({...o,lastError:t}))],inFlightId:null,inFlightIds:[]}}function F_(e,t){let n=e.failed.find(s=>s.id===t);if(!n)return e;let{lastError:r,...o}=n;return{...e,pending:[...e.pending,o],failed:e.failed.filter(s=>s.id!==t)}}function N_(e,t){return gt(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 K_(e,t,n){return gt(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 q_(e,t,n){let r=gt(e);if(r.includes(t))return e;let o=e.pending.findIndex(p=>p.id===t);if(o===-1)return e;let s=r.length,i=Math.min(Math.max(n,s),e.pending.length-1);if(i===o)return e;let a=[...e.pending],[c]=a.splice(o,1);return a.splice(i,0,c),{...e,pending:a}}var vm={thinking:!1,toolDetails:!0,assistantMetadata:!0};function G_(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function B_(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 W_(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
21
+ `)),yield m}}}finally{r.removeEventListener("abort",i),s.releaseLock()}}}async function*lb(e,t,n){let r=e.eventTransport??No(e.fetch??globalThis.fetch),o=n.signal??new AbortController().signal,s=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!o.aborted;a++)try{let c=new Headers(n.headers);i!==void 0&&c.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:c,signal:o}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(s=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(c){if(n.onSseError?.(c),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(s*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function Dt(e){let t=o=>(s,i)=>cb(e,ib(e.baseUrl,o,s,i)),n=o=>s=>t(o)(void 0,s);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(o={})=>({stream:lb(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,o)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var mg=200;async function ub(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 Fe(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new b(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function fg(e){let t=e.runtimeUrl.replace(/\/$/,""),n=Dt({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let o=encodeURIComponent(r.conversationId??e.rootId),s=async(c,p)=>{let d=new URLSearchParams;c!==void 0&&d.set("limit",String(c)),p&&d.set("before",p);let g=`/messages/${o}${d.size?`?${d}`:""}`,m=w=>e.fetch(new Request(`${t}${w}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new b(`Reading the session transcript failed: ${await ub(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await s(r.limit===void 0?void 0:Math.min(r.limit,mg),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await s(Math.min(r.limit-a.length,mg),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,o,s]=await Promise.all([n.session.status().then(i=>Fe(i,"Reading the session status failed")),n.permission.list().then(i=>Fe(i,"Reading permission requests failed")),n.question.list().then(i=>Fe(i,"Reading questions failed"))]);return{statuses:r??{},permissions:o??[],questions:s??[]}},answerPermission:async(r,o,s)=>{Fe(await n.permission.reply({requestID:r,reply:o,...s!==void 0?{message:s}:{}}),"Answering the permission request failed")},answerQuestion:async(r,o)=>{if(o===null){Fe(await n.question.reject({requestID:r}),"Dismissing the question failed");return}Fe(await n.question.reply({requestID:r,answers:o}),"Answering the question failed")},compact:async r=>{let o=r;if(!o){let s=await n.global.config.get().then(c=>c.error===void 0?c.data:null),i=typeof s?.model=="string"?s.model:"",a=i.indexOf("/");a>0&&a<i.length-1&&(o={providerID:i.slice(0,a),modelID:i.slice(a+1)})}if(!o)throw new b("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});return Fe(await n.session.summarize({sessionID:e.rootId,providerID:o.providerID,modelID:o.modelID}),"Compacting the session failed"),o}}}function yg(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return fg({runtimeUrl:r,rootId:n,fetch:D})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,o)=>(await t()).answerPermission(n,r,o),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function hg(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await Dl(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var $t=BigInt(4096),Ce=BigInt(0xffffffffffff),bg=Ce+BigInt(1),pb=bg/BigInt(2),Ne=BigInt(3600*1e3)*$t,Ko=120*1e3,db=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,gb=/^msg_([0-9a-f]{12})/,_g="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function at(e){let t=gb.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function Ut(e){return BigInt(Math.trunc(e))*$t&Ce}function ct(e,t){let n=e-t&Ce;return n>=pb&&(n-=bg),n}function Pg(e){let t=null;for(let n of e)n!=null&&(t===null||ct(n,t)>BigInt(0))&&(t=n);return t}function mb(e,t){let n=at(e);return n===null?!1:ct(n,Ut(t))>Ne}function fb(e,t){let n=t===void 0?null:Ut(t);return xg(e,r=>n===null||ct(r,n)<=Ne)}function xg(e,t){let n=[];for(let r of e){let o=at(r);o!==null&&t(o)&&n.push(o)}return Pg(n)}function yb(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=_g[n%62])}return e}function Sg(e){let t=e.random,n=Ut(e.nowMs-(e.backdateMs??Ko)),r=e.newestKnownTime??null;if(r!==null){let s=ct(r,n);s>=BigInt(0)&&s<=Ne&&(n=r+BigInt(1)&Ce)}let o="";if(t)for(let s=0;s<14;s++)o+=_g[Math.min(61,Math.floor(t()*62))];else o=yb();return{id:`msg_${n.toString(16).padStart(12,"0")}${o}`,time:n}}function qo(e={}){let t=e.nowMs??Date.now(),n=Ut(t-Ko),r=xg(e.after??[],o=>{let s=ct(o,n);return s>=BigInt(0)&&s<=Ne});return Sg({nowMs:t,newestKnownTime:r}).id}function wg(e){return{scope:()=>Ol(e.projectId,e.sessionId),providerSecretPool:{list:()=>Na(e.projectId,e.sessionId),get:t=>Fa(e.projectId,e.sessionId,t),set:(t,n)=>Ka(e.projectId,e.sessionId,t,n)},rescope:t=>jl(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,o=n?.agent??e.agent,s=r&&o?{}:await e.persistedPromptDefaults(),i=r??s.model,a=o??s.agent,c=qo(),p=await $n(e.projectId,e.sessionId,{clientMessageId:c,messageId:c,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new b("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var rO="kortix.transcript.v1",hb=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function oO(e){return typeof e=="string"&&hb.includes(e)}var sO=["once","always","reject"],iO=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];function Pe(){let e=ug();return e||(R().billingEnabled??!1?"":Yl())}async function Go(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Bo(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function vg(e){let t=Bo(e),n=await D(`${t}/env`);if(!n.ok)throw new Error(await Go(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Ag(e,t,n){let r=Bo(e),o=await D(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!o.ok)throw new Error(await Go(o,"Failed to save secret"))}async function kg(e,t){let n=Bo(e),r=await D(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Go(r,"Failed to delete secret"))}var bb={list:vg,set:Ag,delete:kg};async function _b(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let o=await D(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),s=await o.json();if(!o.ok)throw new Error(s?.error||s?.message||`Request failed with ${o.status}`);return s}async function Yn(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function Lt(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return de(e)}async function Rg(e){let t=Lt(e),n=await D(`${t}/kortix/pty`);if(!n.ok)throw new Error(await Yn(n,"Failed to list terminals"));return n.json()}async function Ig(e,t){let n=Lt(e),r=await D(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await Yn(r,"Failed to create terminal"));return r.json()}async function Tg(e,t,n){let r=Lt(e),o=await D(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(await Yn(o,"Failed to update terminal"));return o.json()}async function Cg(e,t){let n=Lt(e),r=await D(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Yn(r,"Failed to remove terminal"))}async function Eg(e,t,n){let r=Lt(t),s=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),de(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await wt();a&&i.set("token",a),n?.wake&&i.set("wake","1");let c=i.toString();return c?`${s}${s.includes("?")?"&":"?"}${c}`:s}function Pb(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 Ee="\x1B",Mg="\x07",xb="\0",Wo=`(?:${Mg}|${Ee}\\\\)`,Sb=[new RegExp(`${Ee}\\]697;[^${Mg}${Ee}]*${Wo}`,"g"),new RegExp(`${xb}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${Ee}\\][0-9]+;rgb:[0-9a-fA-F/]+${Wo}`,"g"),new RegExp(`${Ee}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Wo}`,"g"),new RegExp(`${Ee}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${Ee}\\[\\d+;\\d+R`,"g"),new RegExp(`${Ee}\\[\\?[0-9;]*c`,"g")];function wb(e){let t=e;for(let n of Sb)t=t.replace(n,"");return t}var vb={list:Rg,create:Ig,update:Tg,remove:Cg,webSocketUrl:Eg};async function I(e,t,n,r){let o=e;for(;o.endsWith("/");)o=o.slice(0,-1);let s=await D(`${o}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await s.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!s.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${s.status}`);return a}async function SO(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return I(e,`/kortix/tasks${r}`)}async function wO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function vO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function AO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function kO(e,t){return I(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function RO(e,t,n){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function IO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function TO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function CO(e,t){return I(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function EO(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return I(e,`/kortix/tickets${n}`)}async function MO(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function OO(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function jO(e,t){return I(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function DO(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function $O(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function UO(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function LO(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function FO(e,t,n){return I(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function NO(e,t){return I(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function KO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function qO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function GO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function BO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function WO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function HO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function VO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function zO(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function YO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function QO(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function XO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function JO(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function ZO(e,t,n=200){return I(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function ej(e){return I(e,"/kortix/projects")}async function tj(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function nj(e,t){return I(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function rj(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function oj(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function sj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function ij(e,t,n="all"){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function aj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function cj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function lj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function uj(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function pj(e,t,n,r){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function dj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function gj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function mj(e,t){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function fj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function yj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function hj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function bj(e,t,n){return I(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var Ab=1e4,kb={retryOnAuthError:!1};function lt(e,t,n){return I(e,t,{signal:AbortSignal.timeout(Ab),...n},kb)}async function _j(e,t=!1){return(await lt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function Pj(e){return(await lt(e,"/kortix/services/templates")).templates??[]}async function xj(e,t){return(await lt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function Sj(e,t,n){let r=n==="delete",o=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return lt(e,o,{method:r?"DELETE":"POST"})}async function wj(e,t){return lt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function vj(e,t){return lt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Qn=new Map,Ft=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function Ke(){let e=Pe();if(!e)throw new Ft;return xe(e)}function xe(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Qn.get(e);if(t)return t;if(!$r())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=Dt({baseUrl:e,fetch:D,eventTransport:Rb});return Qn.set(e,n),n}var Rb=async function*(e){let t=R().eventStreamTransport;if(!t){yield*No(D)(e);return}let{headers:n,rejected:r}=await si(e.url,e.headers);try{yield*t({...e,headers:n})}catch(o){throw o?.status===401&&r(),o}};function Mj(e){Qn.delete(e)}function Oj(){Qn.clear()}var Xn=new Map;function jj(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=Xn.get(e);if(t)return t;let n=Dt({baseUrl:e,fetch});return Xn.set(e,n),n}function Dj(e){Xn.delete(e)}function $j(){Xn.clear()}async function Ib(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 Uj(e){let t=Pe();if(!t)throw new b("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await D(`${t}${n}`,{method:"POST"}),o=r.headers.get("content-type")??"",s=/^application\/([\w.+-]+\+)?json\b/i.test(o.trim());if(!r.ok)throw new b(`System reload failed (${r.status}): ${await Ib(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!s)throw new b(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(c){throw new b(`System reload returned malformed JSON from ${n}: ${c instanceof Error?c.message:String(c)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var Og="frontend";function Jn(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Og}] ${t}`,...n?[n]:[]);try{Ke().app.log({service:Og,level:e,message:t,extra:n})}catch{}}var Me={debug:(e,t)=>Jn("debug",e,t),info:(e,t)=>Jn("info",e,t),warn:(e,t)=>Jn("warn",e,t),error:(e,t)=>Jn("error",e,t)};function Tb(e){return{type:"heartbeat-gap",gapMs:e}}function Cb(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 Eb={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Mb=16,Ob=8,jb=6e4,Db=5e3,$b=250,Ub=1e3,Lb=3e4,Fb=5,Nb=3e3,Kb=3e4,qb=2e4,Gb=2e3,Bb=8;function Wb(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function Hb(e,t){if(e?.type!=="message.part.delta"||t.type!=="message.part.delta")return;let n=e.properties,r=t.properties;if(n.partID!==r.partID||n.field!==r.field||n.messageID!==r.messageID||n.sessionID!==r.sessionID)return;let o=e.coalesced??[e];return o.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:o}}function jg(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}var Zn=new WeakMap;function Vb(e,t,n){let r=t.timers??Eb,o=t.connectTimeoutMs??qb,s=t.heartbeatTimeoutMs??jb,i=t.maxConsecutiveHardFailures??Bb,a=new AbortController;function c(y,...P){for(let v of n){let $=y(v);if($)try{$(...P)}catch(x){console.warn("[opencode-events] subscriber handler threw, skipping",x)}}}let p=null,d=y=>{p!==y&&(p=y,y&&c(P=>P.onConnectionChange,y))},g=r.now(),m=null,f=[],h,w=0,L=new Map,O=()=>{if(h&&r.clearTimeout(h),h=void 0,f.length===0)return;let y=f;f=[],L.clear(),w=r.now(),g=r.now();for(let P of y)P&&c(v=>v.onEvent,P.event)},j=()=>{if(h)return;let y=r.now()-w;h=r.setTimeout(O,Math.max(0,Mb-y))};return(async()=>{let y=0,P=0;for(;!a.signal.aborted;){let v=!1,$=!1,x=!1,_,A,T=null,C=r.now(),E=new AbortController;d("connecting");let N=jg(a.signal);N.promise.then(()=>E.abort());try{let ie=await new Promise((Ve,je)=>{let ne=!1;A=r.setTimeout(()=>{ne||(ne=!0,Me.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:o}),E.abort(),je(new Error(`SSE connect timed out after ${o}ms`)))},o),e.global.event({signal:E.signal,sseDefaultRetryDelay:Nb,sseMaxRetryDelay:Kb,sseMaxRetryAttempts:1}).then(fe=>{ne||(ne=!0,r.clearTimeout(A),Ve(fe))},fe=>{ne||(ne=!0,r.clearTimeout(A),je(fe))})}),{stream:V}=ie;if(m){let Ve=r.now()-m.lastActivityAt,je=m.eventful;m=null,(je||Ve>Db)&&c(ne=>ne.onGapRehydrate,Ve)}g=r.now();let ee=()=>{r.clearTimeout(_),_=r.setTimeout(()=>{Me.warn("SSE heartbeat timeout, forcing reconnect"),E.abort()},s)};ee();let He=r.now(),wy=V[Symbol.asyncIterator]();for(;!E.signal.aborted;){let Ve=wy.next().then(ye=>({kind:"next",result:ye}),ye=>({kind:"error",error:ye})),je=jg(E.signal),ne=await Promise.race([Ve,je.promise.then(()=>({kind:"aborted"}))]);if(je.cleanup(),ne.kind==="aborted")break;if(ne.kind==="error")throw ne.error;if(ne.result.done)break;v=!0,d("open"),ee();let fe=ne.result.value,ze=fe&&typeof fe=="object"&&"payload"in fe?fe.payload:fe;if(!ze?.type)continue;ze.type!=="server.connected"&&($=!0);let Or=Hb(f[f.length-1]?.event,ze);if(Or)f[f.length-1]={type:Or.type,event:Or};else{let ye=Wb(ze);if(ye){let Ns=L.get(ye);Ns!==void 0&&(f[Ns]=void 0),L.set(ye,f.length)}f.push({type:ze.type,event:ze})}j(),!(r.now()-He<Ob)&&(He=r.now(),await new Promise(ye=>r.setTimeout(ye,0)))}x=v}catch(ie){if(a.signal.aborted)break;T=ie;let V=String(ie),ee=V.includes("401")||V.includes("403")||V.includes("Unauthorized")||V.includes("Token refresh failed");if(Me.error("SSE event stream error",{error:V,retryCount:y,isAuthError:ee}),ee)try{Qr(),await Yr(),Me.info("SSE: refreshed auth token after auth error")}catch(He){Me.error("SSE: failed to refresh auth token",{error:String(He)})}}finally{r.clearTimeout(_),r.clearTimeout(A),E.abort(),N.cleanup(),O()}if(a.signal.aborted)break;let Z=r.now()-C,Y=T?.cause?.status;if(P=!v&&(typeof Y=="number"&&Y>=400||Z<Gb)?P+1:0,P>=i){Me.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:P,lastError:String(T)}),p=null,c(ie=>ie.onParked,{consecutiveFailures:P,lastError:T});break}d("lost"),m={lastActivityAt:g,eventful:(m?.eventful??!1)||$},x?y=0:(y++,y>1&&Me.warn("SSE event stream reconnecting",{retryCount:y}));let Ae=x?$b:Math.min(Ub*2**Math.min(y-1,Fb),Lb);await new Promise(ie=>{let V=r.setTimeout(ie,Ae),ee=()=>{r.clearTimeout(V),ie()};a.signal.addEventListener("abort",ee,{once:!0})})}})(),{subscribers:n,connectionState:()=>p,teardown:()=>{p=null,a.abort(),h&&r.clearTimeout(h)}}}function Ho(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o,signal:s}=e,i=e.client??(e.url?xe(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o},c=Zn.get(i);if(!c)c=Vb(i,e,new Set([a])),Zn.set(i,c);else{c.subscribers.add(a);let f=c.connectionState();f&&o?.(f)}let p=c,d=!1,g=()=>{d||(d=!0,s&&s.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),Zn.get(i)===p&&Zn.delete(i)))},m=()=>g();return s&&(s.aborted?g():s.addEventListener("abort",m,{once:!0})),{close:g}}function Dg(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return xe(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return xe(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return xe(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return Ho({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Fg(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new b(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function ut(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function Q(e){let t=(e??Pe()).trim();if(!t)throw new Ft;return t}async function tr(e,t){let n=await D(`${Q(t)}${e}`);if(!n.ok)throw new b(await ut(n),{status:n.status,response:n});return n.json()}var Yo=["/workspace","/tmp","/home","/opt"],zb=Yo.filter(e=>e!=="/workspace");function Ng(e){return Yo.some(t=>e===t||e.startsWith(`${t}/`))}function Gt(e){return Ng(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function pt(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(zb.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Kg=pt;async function Bt(e,t){let n=Q(t),r=pt(e)||".";return(await tr(`/file?path=${encodeURIComponent(r)}`,n)).map(s=>({...s,path:s.absolute||`/workspace/${s.path}`}))}async function Wt(e,t){let n=Q(t),r=pt(e),o=await D(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!o.ok)throw new b(await ut(o),{status:o.status,response:o});return o.json()}async function Yb(e,t,n){let r=Q(n),o=pt(e),s=await D(`${r}/file/raw?path=${encodeURIComponent(o)}`);if(!s.ok)throw new b(await ut(s),{status:s.status,response:s});if((s.headers.get("content-type")||"").includes("text/html"))throw new b("File could not be loaded (raw byte route unavailable)",{status:s.status,response:s,code:"INVALID_CONTENT_TYPE"});let i=await s.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}async function Ht(e,t){let n=Q(t);try{return await Yb(e,void 0,n)}catch{}let r=await Wt(e,n);if(r.encoding==="base64"&&r.content){let o=Uint8Array.from(atob(r.content),s=>s.charCodeAt(0));return new Blob([o],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}async function nr(e){return tr("/file/status",Q(e))}async function rr(e,t,n){let r=Q(n),o=new URLSearchParams({query:e});return t?.type&&o.set("type",t.type),t?.limit&&o.set("limit",String(t.limit)),tr(`/find/file?${o.toString()}`,r)}async function or(e,t){let n=Q(t);return(await tr(`/find?pattern=${encodeURIComponent(e)}`,n)).map(o=>({path:typeof o.path=="string"?o.path:o.path?.text??"",lines:typeof o.lines=="string"?o.lines:o.lines?.text??"",line_number:o.line_number,absolute_offset:o.absolute_offset,submatches:(o.submatches??[]).map(s=>({start:s.start,end:s.end}))}))}var Nt=[400,1200],Qb=e=>e===408||e===429||e===502||e===503||e===504,$g=e=>new Promise(t=>setTimeout(t,e));function Xb(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Vo=3e4,Jb=15*6e4,Zb=256;function Kt(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Vo;let t=Vo+e/Zb;return Math.min(Jb,Math.max(Vo,Math.round(t)))}async function e_(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 er(e,t){let n;for(let o=0;o<=Nt.length;o++){let s;try{s=await t(e())}catch(a){if(n=a,Xb(a)||o===Nt.length)break;await $g(Nt[o]);continue}if(s.ok)return s.json();let i=await e_(s);if(n=new b(`Upload failed (${s.status}): ${i}`,{status:s.status,response:s}),!Qb(s.status)||o===Nt.length)throw n;await $g(Nt[o])}if(n instanceof b)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new b(`Upload failed: ${r}`)}var zo=8*1024*1024;function t_(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new b(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Ug(e,t){try{e?.onProgress?.(t)}catch{}}function Lg(e,t,n){let r=new FormData,o=(t??"").trim();return o&&r.append("path",o.startsWith("/")?o:`/${o}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function n_(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function Vt(e,t,n,r,o){let s=typeof r=="string"?r:void 0,i=typeof r=="string"?o:r,a=Q(s),c=Kt(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=zo){let f=await er(()=>Lg(e,t,p),h=>D(`${a}/file/upload`,{method:"POST",body:h},{timeoutMs:c}));return t_(f[0],e.size),Ug(i,{loadedBytes:e.size,totalBytes:e.size}),f}let g=(await er(()=>Lg(new Blob([],{type:e.type}),t,p),f=>D(`${a}/file/upload`,{method:"POST",body:f},{timeoutMs:Kt(0)})))[0]?.path;if(!g)throw new b("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let m=n_(g);if(!m.name)throw new b(`Upload reservation returned an invalid file path: ${g}`,{code:"UPLOAD_INVALID_PATH"});try{for(let f=0;f<e.size;f+=zo){let h=Math.min(e.size,f+zo),w=e.slice(f,h,e.type),L=await er(()=>{let O=new FormData;return m.parent&&O.append("path",m.parent),O.append("filename",m.name),O.append("first",f===0?"true":"false"),O.append("offset",String(f)),O.append("file",w,m.name),O},O=>D(`${a}/file/append`,{method:"POST",body:O},{timeoutMs:Kt(w.size)}));if(L.path!==g||L.size!==h)throw new b(`Upload verification failed for ${g}: expected ${h} bytes, received ${L.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Ug(i,{loadedBytes:h,totalBytes:e.size})}}catch(f){throw await dt(g,a).catch(()=>{}),f}return[{path:g,size:e.size}]}function r_(e,t,n){let r=Q(n),o=Kt(t.size);return er(()=>{let s=new FormData;return s.append(e,t,e.split("/").pop()||"file"),s},s=>D(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:o}))}var qt=class extends b{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function sr(e,t){let n=Q(t),r=e.trim(),s=(r.startsWith("/")?r:`/${r}`).split("/"),i=s.pop()||"untitled",a=s.join("/")||"/workspace",c=Gt(`${a}/${i}`),p=[];try{p=await Bt(qg(c),n)}catch(g){if(!(g instanceof b&&g.status===404))throw g}if(p.some(g=>g.name===Gg(c)))throw new qt(c);let d=await Bg(c,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function ir(e,t,n){let r=Q(n);return r_(t,await Ht(e,r),r)}function o_(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function qg(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Gg(e){return e.slice(e.lastIndexOf("/")+1)}function s_(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function ar(e,t,n){let r=Q(n),o=Gt(o_(e.trim()));return Bg(o,t,r,{overwrite:!0})}async function Bg(e,t,n,r){let o=Gg(e);if(!o)throw new b(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let s=qg(e);await zt(s,n).catch(()=>{});let i=s_(),a=await Vt(t,s,`.${o}.kortix-write-${i}`,n),c=a[0]?.path;if(!c)throw new b(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=Gt(c);try{await Wg(p,e,n,r.overwrite)}catch(g){throw await dt(p,n).catch(()=>{}),!r.overwrite&&g instanceof b&&g.status===409?new qt(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function dt(e,t){let n=await D(`${Q(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Delete failed (${n.status}): ${await ut(n)}`,{status:n.status,response:n});return n.json()}async function zt(e,t){let n=await D(`${Q(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new b(`Mkdir failed (${n.status}): ${await ut(n)}`,{status:n.status,response:n});return n.json()}async function cr(e,t,n){return Wg(e,t,Q(n),!0)}async function Wg(e,t,n,r){let o=await D(`${n}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{from:e,to:t}:{from:e,to:t,overwrite:!1})});if(!o.ok)throw new b(`Rename failed (${o.status}): ${await ut(o)}`,{status:o.status,response:o});return o.json()}async function Hg(){return Fg(await Ke().project.current())}async function Qo(){return Fg(await Ke().global.health())}async function Vg(){try{return(await Qo()).healthy===!0}catch{return!1}}var i_={list:Bt,read:Wt,readBlob:Ht,status:nr,findFiles:rr,findText:or,upload:Vt,write:ar,create:sr,copy:ir,remove:dt,mkdir:zt,rename:cr,currentProject:Hg,health:Qo,isReachable:Vg,toDaemonPath:pt,toSandboxAbsolutePath:Gt,toWorkspaceRelative:Kg};function zg(e){return{list:async t=>Bt(t,(await e()).runtimeUrl),read:async t=>Wt(t,(await e()).runtimeUrl),readBlob:async t=>Ht(t,(await e()).runtimeUrl),status:async()=>nr((await e()).runtimeUrl),findFiles:async(t,n)=>rr(t,n,(await e()).runtimeUrl),findText:async t=>or(t,(await e()).runtimeUrl),upload:async(t,n,r,o)=>Vt(t,n,r,(await e()).runtimeUrl,o),write:async(t,n)=>ar(t,n,(await e()).runtimeUrl),create:async t=>sr(t,(await e()).runtimeUrl),copy:async(t,n)=>ir(t,n,(await e()).runtimeUrl),remove:async t=>dt(t,(await e()).runtimeUrl),mkdir:async t=>zt(t,(await e()).runtimeUrl),rename:async(t,n)=>cr(t,n,(await e()).runtimeUrl)}}function Yg(e){return{get:t=>Dn(e.projectId,e.sessionId,t),presence:t=>l.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1}),cost:()=>qn(e.sessionId,{projectId:e.projectId}),update:t=>Il(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),Tl(e.projectId,e.sessionId)),start:(...t)=>Ue(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Un(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Ln(e.projectId,e.sessionId)),configState:()=>Cl(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),El(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),Ml(e.projectId,e.sessionId,...t)),setSharing:t=>pl(e.projectId,e.sessionId,t),previews:()=>gl(e.projectId,e.sessionId),participants:()=>dl(e.projectId,e.sessionId),commit:t=>al(e.projectId,e.sessionId,t),publicShares:{list:()=>ml(e.projectId,e.sessionId),create:(...t)=>fl(e.projectId,e.sessionId,...t),revoke:(...t)=>yl(e.projectId,e.sessionId,...t)}}}function Qg(e){return{reminders:{list:()=>Yp(e.projectId,e.sessionId),create:t=>Qp(e.projectId,e.sessionId,t),update:(t,n)=>Xp(e.projectId,e.sessionId,t,n),remove:t=>Jp(e.projectId,e.sessionId,t)},audit:(t,n)=>_l(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Vd(e.projectId,e.sessionId,t,n),read:(t,n)=>zd(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Pl(e.projectId,e.sessionId,t),messageAuthors:()=>Ul(e.projectId,e.sessionId),modelUsage:()=>Ll(e.projectId,e.sessionId),transcriptSync:t=>xl(e.projectId,e.sessionId,t),turn:()=>Sl(e.projectId,e.sessionId),prompts:{create:t=>$n(e.projectId,e.sessionId,t),list:()=>wl(e.projectId,e.sessionId),remove:t=>vl(e.projectId,e.sessionId,t),retry:t=>kl(e.projectId,e.sessionId,t),edit:(t,n)=>Al(e.projectId,e.sessionId,t,n),hold:t=>Rl(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function c_(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var l_=["control_plane","provider_ingress","daemon","upstream_port"];function Xg(e){return typeof e=="string"&&l_.includes(e)?e:null}function Jg(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 Zg(e,t){let n=(e===void 0?Pe():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await D(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),o=await r.text().catch(()=>""),s=null;try{s=o?JSON.parse(o):null}catch{s=null}let i=s,a=Xg(r.headers.get("X-Kortix-Proxy-Hop"))??Xg(s?.hop),c=Number(r.headers.get("X-Kortix-Upstream-Status")),p=s?.upstream_status,d=Number.isFinite(c)&&c>0?c:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:o,hop:a,upstreamStatus:d}}var em=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,tm=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,nm=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,rm=new Set([22,4096,parseInt(Ie.KORTIX_MASTER,10)]);function u_(e){return tm.test(e)}function lr(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 p_(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var d_=new Set(["'",'"',"`","<","(","["]),g_=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function m_(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&&d_.has(e[t]);)t++;for(;n>t&&g_.has(e[n-1]);)n--;return e.slice(t,n)}function f_(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var y_=/^\/proxy\/(\d{1,5})(\/.*)?$/,h_=/^\/(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 b_(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:h_.test(t.pathname)}catch{return!1}}function ur(e){if(!e)return null;let t=m_(p_(e.trim())),n=cm(t);if(n){let r=lr(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let o=parseInt(r.port,10);if(!Number.isInteger(o)||o<1||o>65535)return null;let s=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(Ie.KORTIX_MASTER,10);if(o===i){let c=r.pathname.match(y_);if(c){let p=parseInt(c[1],10);if(p>=1&&p<=65535)return o=p,s=lr(`${c[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${o}${s}`,port:o,path:s}}}let a=lr(s);return{originalUrl:`${r.protocol}//${r.hostname}:${o}${a}`,port:o,path:a}}catch{let r=f_(e);return r&&r!==e?ur(r):null}}function __(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let o=/`[^`\n]+`/g;for(;(r=o.exec(e))!==null;){let s=r.index,i=s+r[0].length;t.some(([c,p])=>s>=c&&i<=p)||t.push([s,i])}return t}function P_(e,t){return t.some(([n,r])=>e>=n&&e<r)}function x_(e){let t=[],n=new Set,r=__(e);em.lastIndex=0;let o;for(;(o=em.exec(e))!==null;){let s=ur(o[0]);if(!s)continue;let{originalUrl:i,port:a,path:c}=s;a<1||a>65535||rm.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:c,startIndex:o.index,endIndex:o.index+i.length,inCodeBlock:P_(o.index,r)}))}return t}function dD(e){return x_(e).length>0}function S_(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function om(e){return e.trim().toLowerCase().split("_").join("-")}function sm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function w_(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let o=r.split("{port}").join(String(e)).split("{sandbox}").join(om(n.sandboxId));return`${sm(o)}${t}`}function v_(e){return e.sandboxId.trim().length>0}function qe(e,t,n){let r=lr(t);if(!v_(n))return I_(e,r);let o=w_(e,r,n);return o||(S_(n.apiBaseUrl)?`http://p${e}-${om(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${sm(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function gD(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(o=>encodeURIComponent(o)).join("/");return qe(3211,`/open?path=/workspace/${r}`,t)}function A_(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function mD(e){return`http://localhost:3211${A_(e)}`}function k_(){return"/health"}function fD(e){return qe(3211,k_(),e)}function yD(e,t){return qe(e,"/",t)}function R_(e){let t=ur(e);return!(!t||rm.has(t.port)||b_(e))}function im(e,t){if(!e)return e;let n=ur(e);return n?R_(n.originalUrl)?qe(n.port,n.path,t):n.originalUrl:e}function I_(e,t="/"){return`http://localhost:${e}${t}`}var am=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function cm(e){let t=e.match(tm);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(nm);if(n){let o=443;try{let s=new URL(e);o=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:o,path:n[4]||"/"}}let r=e.match(am);if(r)try{let o=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(o.port,10)||(o.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function hD(e){try{let t=cm(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function bD(e){return u_(e)||nm.test(e)||am.test(e)}function _D(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Yt="/web-proxy/";function PD(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),o=`${Yt}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,s=parseInt(Ie.KORTIX_MASTER,10);return`${qe(s,"/",t).replace(/\/$/,"")}${o}`}catch{return null}}function xD(e){try{let t=new URL(e),n=t.pathname.indexOf(Yt);if(n===-1)return null;let o=t.pathname.slice(n+Yt.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!o)return null;let s=o[1],i=o[2],a=o[3]||"/";return`${s}://${i}${a}${t.search}${t.hash}`}catch{return null}}function SD(e){try{return new URL(e).pathname.includes(Yt)}catch{return e.includes(Yt)}}function wD(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 vD(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 lm(e){return{health:t=>Zg(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>qe(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>im(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>tt(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Xo(e,t,n,r){let o,s,{persistedPromptDefaults:i,clearPersistedDefaults:a}=ag(e,t),{ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g}=dg(e,t,n),m={projectId:e,sessionId:t,ensureReady:c,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return o},set model(f){o=f},get agent(){return s},set agent(f){s=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...Yg(m),...Qg(m),...lm(m),...hg(m),...wg(m),...Dg(m),files:zg(c),...yg(m),get runtime(){return xe(d("runtime").runtimeUrl)}}}function um(e){return{apps:{list:()=>Ad(e),create:t=>kd(e,t),get:t=>Rd(e,t),update:(...t)=>Id(e,...t),access:{get:(...t)=>Cd(e,...t),update:(...t)=>Md(e,...t),session:(...t)=>Od(e,...t),agents:t=>Ed(e,t)},remove:t=>Td(e,t),artifacts:{register:t=>go(e,t),uploadArchive:(...t)=>jd(e,...t),finalize:(...t)=>mo(e,...t)},deployments:{create:(...t)=>Dd(e,...t),list:t=>$d(e,t),get:(...t)=>Ud(e,...t),logs:(...t)=>Ld(e,...t),remove:(...t)=>Kd(e,...t)},start:t=>Fd(e,t),stop:t=>Nd(e,t),rollback:(...t)=>qd(e,...t)}}}function pm(e){return{list:()=>oa(e),invite:(...t)=>aa(e,...t),update:(...t)=>sa(e,...t),revoke:t=>ia(e,t),pendingInvites:()=>ca(e),resendInvite:(...t)=>ua(e,...t),revokeInvite:(...t)=>la(e,...t),requests:()=>ta(e),approveRequest:(...t)=>na(e,...t),rejectRequest:(...t)=>ra(e,...t),groupGrants:()=>pa(e),attachGroupGrant:(...t)=>da(e,...t),updateGroupGrant:(...t)=>ga(e,...t),detachGroupGrant:t=>ma(e,t),resourceGrants:{list:()=>fa(e),create:t=>ya(e,t),remove:t=>ha(e,t)}}}function dm(e){return{tokens:{list:()=>sd(e),create:t=>id(e,t),revoke:t=>ad(e,t)},setupLinks:{requestSecret:t=>fd(e,t),requestConnector:t=>yd(e,t)},validateManifest:t=>Oi(e,t),gitToken:()=>ji(e),agentIdentities:()=>hp(e),secrets:{list:()=>xa(e),upsert:t=>Sa(e,t),setStrategy:(...t)=>wa(e,...t),broker:(...t)=>va(e,...t),remove:t=>Ia(e,t),setPersonal:(...t)=>Ta(e,...t),removePersonal:t=>Ca(e,t),setGitCredential:t=>Ra(e,t),listProviderOAuth:()=>Aa(e),startProviderOAuth:(...t)=>Hr(e,...t),pollProviderOAuth:(...t)=>Vr(e,...t),removeProviderOAuth:t=>ka(e,t)},access:pm(e)}}function gm(e){return{list:()=>Va(e),listAll:()=>za(e),reconcile:(...t)=>Ya(e,...t),reconcileMember:(...t)=>Qa(e,...t),updateCredential:(...t)=>Xa(e,...t),revoke:(...t)=>Ja(e,...t),activate:(...t)=>Za(e,...t),setDefault:(...t)=>ec(e,...t),rename:(...t)=>tc(e,...t),share:(...t)=>rc(e,...t),addComputer:(...t)=>nc(e,...t),pipedreamConnect:(...t)=>oc(e,...t),pipedreamFinalize:(...t)=>sc(e,...t)}}function pr(e){return{catalog:t=>In(e,t),tools:()=>Xr(e),search:(...t)=>qa(e,...t),describe:(...t)=>Ga(e,...t),call:(...t)=>Ba(e,...t),accounts:(...t)=>Wa(e,...t),uploadAttachment:(...t)=>Ha(e,...t)}}var T_=100,C_=0,E_=new Set(["attachment_size_mismatch","attachment_failed"]),mm=()=>new b("Attachment expired. Attach the file again.",{code:"attachment_expired"});function fm(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 ym(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,o=new Set,s=new Set,i=0,a=!1,c,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,P){y.removalDeleted||(y.removalDeleted=!0,kt(e,P).catch(()=>{}))}function m(){c&&clearTimeout(c);let y=d().map(({item:v})=>v);(y.length!==p.attachments.length||y.some((v,$)=>v!==p.attachments[$]))&&(p={attachments:y});let P=Math.min(...y.filter(v=>v.status==="ready").map(v=>Date.parse(v.attachment.expires_at)));Number.isFinite(P)&&!a&&(c=setTimeout(()=>{for(let v of d())v.item.status==="ready"&&Date.parse(v.item.attachment.expires_at)<=Date.now()&&(v.item={...v.item,status:"error",error:mm()});m()},Math.min(2147483647,Math.max(0,P-Date.now()))),typeof c=="object"&&"unref"in c&&c.unref());for(let v of o)v();for(let v of[...s])v()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(y){f();let P=d();if(P.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some($=>!Number.isSafeInteger($)||$<=0||$>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(P.reduce(($,x)=>$+x.item.size,0)+y.reduce(($,x)=>$+x,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function w(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let P=y.item.file;i++;let v=++y.generation,$=new AbortController;y.abort=$,y.item={...y.item,status:"uploading",error:void 0};let x=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===v,_,A=0,T,C=()=>{T=void 0,!(!x()||y.item.status!=="uploading"||_===void 0)&&(y.item={...y.item,receivedBytes:_},_=void 0,A=Date.now(),m())},E=N=>Math.floor(N*100/y.item.size);On(e,P,{resume:y.upload,signal:$.signal,onUpload:N=>{y.upload=N,y.removed&&($.abort(),g(y,N.attachment_id))},onProgress:N=>{if(!x()||E(N)===E(y.item.receivedBytes)||(_=N,T))return;let Z=A+T_-Date.now();if(Z<=0)return C();T=setTimeout(C,Z),typeof T=="object"&&"unref"in T&&T.unref()},onProcessing:()=>{T&&clearTimeout(T),T=void 0,_=void 0,x()&&(y.item={...y.item,status:"processing",receivedBytes:y.item.size},m())}}).then(N=>{x()&&(y.item={...y.item,status:"ready",attachment:fm(N),receivedBytes:N.size})}).catch(N=>{N instanceof b&&E_.has(N.code??"")&&(y.upload=void 0),x()&&(y.item={...y.item,status:N instanceof b&&N.code==="ABORTED"?"aborted":"error",error:N instanceof Error?N:new Error(String(N))})}).finally(()=>{i--,T&&clearTimeout(T),y.abort===$&&(y.abort=void 0),m(),w()})}m()}function L(y){h(y.map(v=>v.size));let P=y.map(v=>{let $=`attachment-${++C_}`;return r.set($,{generation:0,item:{id:$,file:v,filename:v.name,mime:v.type||"application/octet-stream",size:v.size,status:"pending",receivedBytes:0}}),$});return m(),w(),P}function O(y){let P=r.get(y);!P||P.item.status==="ready"||(P.generation++,P.abort?.abort(),P.item={...P.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function j(y,{signal:P}={}){let v=[...y];return new Promise(($,x)=>{let _=()=>{s.delete(C),P?.removeEventListener("abort",T)},A=E=>{_(),x(E)},T=()=>A(le()),C=()=>{let E=!1;for(let Z of v){let Y=r.get(Z);if(!Y)return A(new Error("Attachment was removed before it was sent"));if(a&&!Y.handedOff)return A(new Error("Attachment controller is disposed"));if(Y.item.status==="error"||Y.item.status==="aborted")return A(Y.item.error??new Error("Attachment upload failed"));Y.item.status!=="ready"&&(E=!0)}if(E)return;let N;try{N=v.map(Z=>{let Y=fm(r.get(Z).item.attachment);return{type:"file",attachment_id:Y.attachment_id,filename:Y.filename,mime:Y.mime}})}catch(Z){return A(Z instanceof Error?Z:new Error(String(Z)))}_(),$(N)};if(P?.aborted)return T();s.add(C),P?.addEventListener("abort",T,{once:!0}),C()})}return{add:y=>L([y])[0],addMany:L,retry(y){let P=r.get(y);if(P?.handedOff||f(),!(!P||P.item.status==="ready"||P.item.status==="uploading"||P.item.status==="processing"||P.item.status==="pending")){if(!P.item.file||P.upload&&Date.parse(P.upload.expires_at)<=Date.now())throw mm();P.item={...P.item,status:"pending",error:void 0},w()}},async remove(y){let P=r.get(y);if(!P)return;P.removed=!0,P.generation++,r.delete(y);let v=P.upload?.attachment_id??P.item.attachment?.attachment_id;v&&P.abort?.abort(),m(),w(),v&&g(P,v)},abort:O,submit(y){if(!a){for(let P of y){let v=r.get(P);v&&(v.handedOff=!0)}m()}},reclaim(y){if(!a){for(let P of y){let v=r.get(P);v&&(v.handedOff=!1)}m()}},whenReady:j,forget(y=d().map(P=>P.item.id)){for(let P of y){let v=r.get(P);v&&(v.generation++,v.abort?.abort(),r.delete(P))}m(),w()},dispose(){if(!a){a=!0,c&&clearTimeout(c);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let P=y.upload?.attachment_id??y.item.attachment?.attachment_id;P&&e&&kt(e,P).catch(()=>{})}o.clear(),m()}},getSnapshot:()=>p,subscribe(y){return o.add(y),()=>{o.delete(y)}}}}function hm(e){return{attachments:{upload:(...t)=>On(e,...t),delete:(...t)=>kt(e,...t),createController:t=>ym(e,t)},get:t=>xn(e,t),detail:()=>Sn(e),audit:t=>ld(e,t),update:t=>An(e,t),archive:()=>kn(e),llmCatalog:()=>wn(e),modelPicker:()=>vn(e),modelAccess:()=>Bn(e),setModelAccess:t=>Wn(e,t),sandboxHealth:()=>Tn(e),onboardingComplete:(...t)=>Ki(e,...t)}}function bm(e){return{sessions:{list:t=>Ze(e,t),listPage:t=>ul(e,t),create:t=>et(e,t),ensureWarm:()=>hl(e),claimWarm:t=>bl(e,t)},review:{list:t=>Up(e,t),get:t=>Lp(e,t),submit:t=>Fp(e,t),act:(...t)=>Np(e,...t),bulkAct:t=>Kp(e,t)},approvals:{list:t=>ba(e,t),resolve:(...t)=>Pa(e,...t),sessionsNeedingInput:t=>_a(e,t)}}}function _m(e){return{files:{list:t=>$c(e,t),read:(t,n)=>Lc(e,t,n),search:(...t)=>Uc(e,...t),archive:(...t)=>Fc(e,...t),history:(...t)=>Qc(e,...t)},git:{commits:()=>Vc(e),commit:t=>zc(e,t),commitDiff:t=>Yc(e,t),branches:()=>Hc(e),versionDiff:(...t)=>Xc(e,...t),inviteCollaborator:(...t)=>Mi(e,...t)},changeRequests:{list:()=>Jc(e),get:t=>Zc(e,t),diff:t=>el(e,t),mergePreview:t=>tl(e,t),open:(...t)=>nl(e,...t),merge:(...t)=>rl(e,...t),close:(...t)=>ol(e,...t),reopen:(...t)=>sl(e,...t),requestChanges:(...t)=>il(e,...t)},...bm(e)}}function Pm(e){return{policies:{list:()=>Ac(e),set:(...t)=>kc(e,...t)},reminders:{list:()=>Zp(e)},triggers:{list:()=>Fl(e),create:(...t)=>Nl(e,...t),update:(...t)=>Kl(e,...t),remove:(...t)=>ql(e,...t),fire:(...t)=>Bl(e,...t),setActivation:(...t)=>Gl(e,...t)},..._m(e)}}function xm(e,t){return{connectors:{...pr(e),list:()=>ic(e),config:(...n)=>gc(e,...n),create:(...n)=>yc(e,...n),remove:(...n)=>bc(e,...n),sync:()=>ac(e),auth:{discover:(...n)=>hc(e,...n)},setName:(...n)=>mc(e,...n),setCredentialMode:(...n)=>cc(e,...n),setAuthorizationStrategy:(...n)=>lc(e,...n),setCredential:(...n)=>wc(e,...n),setSensitive:(...n)=>uc(e,...n),connections:t,policies:{get:(...n)=>pc(e,...n),set:(...n)=>dc(e,...n)},pipedream:{listApps:(...n)=>_c(e,...n),listSections:(...n)=>Pc(e,...n),connect:(...n)=>fc(e,...n),finalize:(...n)=>vc(e,...n)},discover:{list:(...n)=>Jr(e,...n),sections:(...n)=>xc(e,...n),detail:(...n)=>Zr(e,...n)}},...Pm(e)}}function Sm(e){return{gateway:{logs:t=>Vu(e,t),log:t=>zu(e,t),overview:t=>Yu(e,t),series:t=>Qu(e,t),breakdown:t=>Xu(e,t),sessions:t=>Ju(e,t),errors:t=>Zu(e,t),budgets:()=>ep(e),setBudget:t=>tp(e,t),deleteBudget:t=>np(e,t),keys:()=>rp(e),createKey:t=>op(e,t),revokeKey:t=>sp(e,t),routing:{get:()=>Gu(e),set:t=>Bu(e,t),reset:()=>Wu(e),preview:t=>Hu(e,t)},playground:(t,n,r)=>ip(e,t,n,r)}}}function wm(e){return{modelDefaults:{get:()=>Ql(e),set:t=>Xl(e,t),clear:t=>Jl(e,t)},setDefaultAgent:t=>tu(e,t),sandbox:{list:()=>Dc(e),snapshots:()=>Ic(e),rebuildSnapshot:t=>Tc(e,t),fixWithAgent:()=>Cc(e),createTemplate:t=>Ec(e,t),updateTemplate:(...t)=>Mc(e,...t),removeTemplate:t=>Oc(e,t),buildTemplate:t=>jc(e,t),setProvider:t=>Ni(e,t)},setAgentScope:(...t)=>eu(e,...t)}}function vm(e){return{channels:{slack:{installation:()=>Iu(e),connect:t=>Tu(e,t),mode:()=>Cu(e),completeInstall:t=>Mu(e,t),manifest:()=>ju(e),disconnect:()=>Du(e),getFile:t=>$u(e,t),uploadFile:t=>Uu(e,t)},teams:{completeInstall:t=>Ou(e,t)},email:{installation:t=>Lu(e,t),mode:()=>Fu(e),connect:t=>Nu(e,t),disconnect:t=>Ku(e,t),updatePolicy:(...t)=>qu(e,...t)}},updateFeatureFlag:(...t)=>Li(e,...t),updateExperimentalFeature:(...t)=>Fi(e,...t),...wm(e)}}function M_(){return Ke()}function O_(e,t){Dr(e,t);let n=ig(e),{auth:r,accounts:o,iam:s,accountInvites:i}=tg(),{billing:a,sandboxShares:c}=Jd(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=Xd();function h(w){let L=gm(w);return{...hm(w),...um(w),...dm(w),...xm(w,L),...Sm(w),...vm(w),session:O=>Xo(w,O,e,n)}}return{config:e,auth:r,accounts:o,iam:s,accountInvites:i,projects:p,connectors:pr(),project:h,session:(w,L)=>Xo(w,L,e,n),github:d,gitBackend:g,billing:a,sandboxShares:c,connectStatus:m,marketplace:f,validateToken:Ti,runtime:M_}}function j_(){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 D_(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function gt(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function $_(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function U_(e){if(gt(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 L_(e){let t=gt(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function F_(e,t){let n=gt(e);if(n.length===0)return e;let r=e.pending.filter(o=>n.includes(o.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(o=>!n.includes(o.id)),failed:[...e.failed,...r.map(o=>({...o,lastError:t}))],inFlightId:null,inFlightIds:[]}}function N_(e,t){let n=e.failed.find(s=>s.id===t);if(!n)return e;let{lastError:r,...o}=n;return{...e,pending:[...e.pending,o],failed:e.failed.filter(s=>s.id!==t)}}function K_(e,t){return gt(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 q_(e,t,n){return gt(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 G_(e,t,n){let r=gt(e);if(r.includes(t))return e;let o=e.pending.findIndex(p=>p.id===t);if(o===-1)return e;let s=r.length,i=Math.min(Math.max(n,s),e.pending.length-1);if(i===o)return e;let a=[...e.pending],[c]=a.splice(o,1);return a.splice(i,0,c),{...e,pending:a}}var Am={thinking:!1,toolDetails:!0,assistantMetadata:!0};function B_(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function W_(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 H_(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
22
22
 
23
23
  `;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
24
24
  >
@@ -51,15 +51,15 @@ ${o}
51
51
  ${e.state.error}
52
52
  \`\`\`
53
53
  `),n+=`
54
- `,n}return""}function H_(e,t){if(!t)return`## Assistant
54
+ `,n}return""}function V_(e,t){if(!t)return`## Assistant
55
55
 
56
- `;let n=e.agent?G_(e.agent):"Assistant",r=e.modelID||"",o="";e.time?.completed&&e.time?.created&&(o=B_(e.time.completed-e.time.created));let s=[r,o].filter(Boolean).join(" \xB7 ");return s?`## ${n} (${s})
56
+ `;let n=e.agent?B_(e.agent):"Assistant",r=e.modelID||"",o="";e.time?.completed&&e.time?.created&&(o=W_(e.time.completed-e.time.created));let s=[r,o].filter(Boolean).join(" \xB7 ");return s?`## ${n} (${s})
57
57
 
58
58
  `:`## ${n}
59
59
 
60
- `}function V_(e,t,n){let r="";e.role==="user"?r+=`## User
60
+ `}function z_(e,t,n){let r="";e.role==="user"?r+=`## User
61
61
 
62
- `:r+=H_(e,n.assistantMetadata);for(let o of t)r+=W_(o,n);return r}function z_(e,t,n=vm){let r=`# ${e.title||"Untitled Session"}
62
+ `:r+=V_(e,n.assistantMetadata);for(let o of t)r+=H_(o,n);return r}function Y_(e,t,n=Am){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 o of t)r+=V_(o.info,o.parts,n),r+=`---
70
+ `;for(let o of t)r+=z_(o.info,o.parts,n),r+=`---
71
71
 
72
- `;return r}function Y_(e,t){return`session-${e}.md`}var Jo="An error occurred";var Q_=["message","error","detail","error_description","msg","errors","data"];function Zo(e){let t=e.trim();for(let n=0;n<4;n++){let r=t.replace(/^(?:\d{3}\s+)?(?:[A-Za-z_$][\w$]*)?Error:\s*/,"").trim();if(r===t)break;t=r}return t}function mt(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function X_(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=mt(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function J_(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=Z_(e,t);if(n)return n;let r=tP(e,t);return r?r.slice(0,200):void 0}function Im(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function Am(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function Z_(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let o=r+6;if(!Im(t.charCodeAt(o))){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return;let i=e.indexOf("<",s+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(s+1,i).trim();if(a)return a}n=s+1}}var eP=["script","style"];function tP(e,t){let n=[],r=0;for(;r<e.length;){let o=e.indexOf("<",r);if(o===-1){n.push(e.slice(r));break}n.push(e.slice(r,o));let s=eP.find(i=>t.startsWith(`<${i}`,o)&&Im(t.charCodeAt(o+i.length+1)));if(s){let i=t.indexOf(`</${s}`,o);r=i===-1?e.length:Am(e,i);continue}r=Am(e,o)}return n.join(" ").replace(/\s+/g," ").trim()}function nP(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 rP(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function km(e,t,n){if(typeof e=="string")return dr(e,t,n);if(e&&typeof e=="object")return gr(e,t,n)}function dr(e,t,n=new WeakSet){let r=Zo(e);if(!r)return;if(t>=4)return r;let o=nP(r);if(o)return o;let s=mt(r);if(s!==void 0)return typeof s=="string"?dr(s,t+1,n):s&&typeof s=="object"?gr(s,t+1,n):String(s);let i=Cm(r);if(i){let a=mt(i);if(a&&typeof a=="object"){let c=gr(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=X_(r);if(a)return dr(a,t+1,n)??a}return J_(r)??r}function gr(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=km(i,t,n);if(a)return a}return}let r=e;for(let i of Q_){let a=km(r[i],t,n);if(a)return a}let o=r.type??r.code;if(typeof o=="string"&&o.trim())return rP(o);let s=r.status??r.statusCode??r.upstream_status;if(typeof s=="number"&&Number.isFinite(s))return`Request failed with status ${s}`}function ce(e){return e?typeof e=="string"?dr(e,0)??Jo:typeof e=="object"?gr(e,0)??Jo:String(e):Jo}function Tm(e){let t=oP(e)?.trim();if(!t)return;let n=ce(e);if(!(t===n||Zo(t)===n))return t}function oP(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:o}=n,s=[r,o].filter((i,a,c)=>typeof i=="string"&&i.trim()!==""&&c.indexOf(i)===a);if(s.length>0)return s.join(`
72
+ `;return r}function Q_(e,t){return`session-${e}.md`}var Jo="An error occurred";var X_=["message","error","detail","error_description","msg","errors","data"];function Zo(e){let t=e.trim();for(let n=0;n<4;n++){let r=t.replace(/^(?:\d{3}\s+)?(?:[A-Za-z_$][\w$]*)?Error:\s*/,"").trim();if(r===t)break;t=r}return t}function mt(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function J_(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=mt(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function Z_(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=eP(e,t);if(n)return n;let r=nP(e,t);return r?r.slice(0,200):void 0}function Tm(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function km(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function eP(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let o=r+6;if(!Tm(t.charCodeAt(o))){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return;let i=e.indexOf("<",s+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(s+1,i).trim();if(a)return a}n=s+1}}var tP=["script","style"];function nP(e,t){let n=[],r=0;for(;r<e.length;){let o=e.indexOf("<",r);if(o===-1){n.push(e.slice(r));break}n.push(e.slice(r,o));let s=tP.find(i=>t.startsWith(`<${i}`,o)&&Tm(t.charCodeAt(o+i.length+1)));if(s){let i=t.indexOf(`</${s}`,o);r=i===-1?e.length:km(e,i);continue}r=km(e,o)}return n.join(" ").replace(/\s+/g," ").trim()}function rP(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 oP(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function Rm(e,t,n){if(typeof e=="string")return dr(e,t,n);if(e&&typeof e=="object")return gr(e,t,n)}function dr(e,t,n=new WeakSet){let r=Zo(e);if(!r)return;if(t>=4)return r;let o=rP(r);if(o)return o;let s=mt(r);if(s!==void 0)return typeof s=="string"?dr(s,t+1,n):s&&typeof s=="object"?gr(s,t+1,n):String(s);let i=Em(r);if(i){let a=mt(i);if(a&&typeof a=="object"){let c=gr(a,t+1,n);if(c)return c}}if(r.includes("{")){let a=J_(r);if(a)return dr(a,t+1,n)??a}return Z_(r)??r}function gr(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=Rm(i,t,n);if(a)return a}return}let r=e;for(let i of X_){let a=Rm(r[i],t,n);if(a)return a}let o=r.type??r.code;if(typeof o=="string"&&o.trim())return oP(o);let s=r.status??r.statusCode??r.upstream_status;if(typeof s=="number"&&Number.isFinite(s))return`Request failed with status ${s}`}function ce(e){return e?typeof e=="string"?dr(e,0)??Jo:typeof e=="object"?gr(e,0)??Jo:String(e):Jo}function Cm(e){let t=sP(e)?.trim();if(!t)return;let n=ce(e);if(!(t===n||Zo(t)===n))return t}function sP(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:o}=n,s=[r,o].filter((i,a,c)=>typeof i=="string"&&i.trim()!==""&&c.indexOf(i)===a);if(s.length>0)return s.join(`
73
73
 
74
- `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function Cm(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function sP(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 iP(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 Rm(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,o=typeof e.upstream_status=="number"?e.upstream_status:void 0,s=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=iP(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,c=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&o===void 0&&!s&&!i?void 0:{message:typeof e.message=="string"&&e.message||sP(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:o,requestId:s,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function ge(e){if(e==null)return;if(typeof e=="string"){let i=Zo(e),a=mt(i)??mt(Cm(i));return a!==void 0?ge(a):void 0}if(typeof e!="object")return;let t=e,n=Rm(t);if(n)return n;let r=t.error;if(r&&typeof r=="object"&&!Array.isArray(r)){let i=Rm(r);if(i)return i}let o=t.data;if(o&&typeof o.responseBody=="string"){let i=mt(o.responseBody);if(i!==void 0){let a=ge(i);if(a)return a}}if(o&&typeof o.message=="string"){let i=ge(o.message);if(i)return i}let s=t.cause;if(s&&typeof s=="object"){let i=s.body;if(i!==void 0){let a=ge(i);if(a)return a}}}var Em={};function B(e,t){for(let n of t)Em[n]=e}B("read",["read"]);B("list",["list","ls"]);B("glob",["glob"]);B("grep",["grep"]);B("write",["write"]);B("edit",["edit","multiedit","morph_edit"]);B("apply_patch",["apply_patch","patch"]);B("bash",["bash"]);B("web_search",["web_search","websearch","image_search"]);B("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);B("media",["image_gen","video_gen"]);B("show",["show","show_user","presentation_gen"]);B("task",["task"]);B("delegate",["agent_spawn","agent_task","agent_task_create","agent_task_start","task_create","task_start","session_spawn","session_start_background","agent_message","agent_task_message","task_message","agent_task_update","task_update","session_message","agent_status","agent_task_list","agent_task_get","task_list","task_get","agent_stop","agent_task_cancel","task_cancel","agent_task_approve","task_approve","task_done","task_delete"]);B("todowrite",["todowrite","todo_write","todoread"]);B("question",["question","ask"]);B("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);B("connectors",["connector_get","connector_list","connector_setup","kortix_connector_call","kortix_connectors","kortix_connectors_connectors","kortix_connectors_discover","kortix_connectors_describe","kortix_connectors_call","kortix_connector_describe","kortix_connector_discover"]);B("automations",["triggers"]);B("skill",["skill"]);B("context",["prune","distill","compress","context_info"]);B("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var aP=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function re(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=Em[t];if(n)return n;for(let[r,o]of aP)if(t.startsWith(r))return o;return"other"}function Oe(e){for(let t of[e?.filePath,e?.file_path,e?.path])if(typeof t=="string"&&t)return t}var cP=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function lP(){return new RegExp(`(^|\\s)([-+]?)(${cP.join("|")}):("[^"]*"|\\S+)`,"gi")}function uP(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function pP(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function dP(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function gP(e){return dP(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function Mm(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function mr(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(lP(),(o,s,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=gP(c);p&&!n.includes(p)&&n.push(p)}return s});return r=r.replace(uP(),"$1").replace(pP(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${Mm(n)}`:r:n.length>0?Mm(n):t}var mP=/\s/,fP=/\w/;function oe(e){return e!==void 0&&mP.test(e)}function Qt(e){return e===`
75
- `||e==="\r"||e==="\u2028"||e==="\u2029"}function es(e){return e!==void 0&&fP.test(e)}function Ge(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(yP(n.charCodeAt(0))):n;return t}function yP(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 Se(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function Om(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Se(e.slice(t))}function Xt(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let o=e.indexOf(n,r+t.length);return o===-1?null:e.slice(r+t.length,o)}function ts(e,t){let n=Xt(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
74
+ `)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function Em(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function iP(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 aP(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 Im(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,o=typeof e.upstream_status=="number"?e.upstream_status:void 0,s=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=aP(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,c=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&o===void 0&&!s&&!i?void 0:{message:typeof e.message=="string"&&e.message||iP(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:o,requestId:s,attemptFailures:i,...a?{requestedModel:a}:{},...c?{resolvedModel:c}:{}}}function ge(e){if(e==null)return;if(typeof e=="string"){let a=Zo(e),c=mt(a)??mt(Em(a));return c!==void 0?ge(c):void 0}if(typeof e!="object")return;let t=e,n=Im(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let o=t.error;if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Im(o);if(a)return a}let s=t.data;if(s&&typeof s.responseBody=="string"){let a=mt(s.responseBody);if(a!==void 0){let c=ge(a);if(c)return c}}if(s&&typeof s.message=="string"){let a=ge(s.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let c=ge(a);if(c)return c}}return n}var Mm={};function B(e,t){for(let n of t)Mm[n]=e}B("read",["read"]);B("list",["list","ls"]);B("glob",["glob"]);B("grep",["grep"]);B("write",["write"]);B("edit",["edit","multiedit","morph_edit"]);B("apply_patch",["apply_patch","patch"]);B("bash",["bash"]);B("web_search",["web_search","websearch","image_search"]);B("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);B("media",["image_gen","video_gen"]);B("show",["show","show_user","presentation_gen"]);B("task",["task"]);B("delegate",["agent_spawn","agent_task","agent_task_create","agent_task_start","task_create","task_start","session_spawn","session_start_background","agent_message","agent_task_message","task_message","agent_task_update","task_update","session_message","agent_status","agent_task_list","agent_task_get","task_list","task_get","agent_stop","agent_task_cancel","task_cancel","agent_task_approve","task_approve","task_done","task_delete"]);B("todowrite",["todowrite","todo_write","todoread"]);B("question",["question","ask"]);B("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);B("connectors",["connector_get","connector_list","connector_setup","kortix_connector_call","kortix_connectors","kortix_connectors_connectors","kortix_connectors_discover","kortix_connectors_describe","kortix_connectors_call","kortix_connector_describe","kortix_connector_discover"]);B("automations",["triggers"]);B("skill",["skill"]);B("context",["prune","distill","compress","context_info"]);B("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var cP=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function re(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=Mm[t];if(n)return n;for(let[r,o]of cP)if(t.startsWith(r))return o;return"other"}function Oe(e){for(let t of[e?.filePath,e?.file_path,e?.path])if(typeof t=="string"&&t)return t}var lP=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function uP(){return new RegExp(`(^|\\s)([-+]?)(${lP.join("|")}):("[^"]*"|\\S+)`,"gi")}function pP(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function dP(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function gP(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function mP(e){return gP(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function Om(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function mr(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(uP(),(o,s,i,a,c)=>{if(!i&&a.toLowerCase()==="site"){let p=mP(c);p&&!n.includes(p)&&n.push(p)}return s});return r=r.replace(pP(),"$1").replace(dP(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${Om(n)}`:r:n.length>0?Om(n):t}var fP=/\s/,yP=/\w/;function oe(e){return e!==void 0&&fP.test(e)}function Qt(e){return e===`
75
+ `||e==="\r"||e==="\u2028"||e==="\u2029"}function es(e){return e!==void 0&&yP.test(e)}function Ge(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(hP(n.charCodeAt(0))):n;return t}function hP(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 Se(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function jm(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Se(e.slice(t))}function Xt(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let o=e.indexOf(n,r+t.length);return o===-1?null:e.slice(r+t.length,o)}function ts(e,t){let n=Xt(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 ns(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let o=e.indexOf(">",r+1+t.length);return o===-1?null:{open:r,end:o}}function jm(e,t){let n=ns(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function Dm(e,t){let n=ns(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 $m(e,t){let n=`</${t}>`,r="",o=0;for(;;){let s=ns(e,t,o);if(!s)break;let i=e.indexOf(n,s.end+1);if(i===-1)break;r+=e.slice(o,s.open),o=i+n.length}return r+e.slice(o)}function Um(e,t,n){let r=[];for(let o of e.split(/[\n\r\u2028\u2029]/)){let s=0;for(;;){let i=o.indexOf(t,s);if(i===-1)break;let a=o.indexOf(n,i+t.length);if(a===-1)break;r.push(o.slice(i+t.length,a)),s=a+n.length}}return r}function Jt(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&oe(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function Lm(e,t,n){let r=Ge(t),o=Ge(n);for(let s of Ge(e).split(/[\n\r\u2028\u2029]/)){let i=s.indexOf(r);if(i!==-1&&s.lastIndexOf(o)>=i+r.length)return!0}return!1}function Fm(e,t){let n=Ge(e),r=t.map(Ge),o=e.length,s=c=>{let p=c;for(;p<o&&oe(e[p]);)p++;return p},i=c=>{for(let p=c;p<o;p++)if(Qt(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=o;){let c=s(a);if(c>=o)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=s(c+p.length);if(e[d]===":"){let g=s(d+1);if(g<o){let m=g;for(;m<o&&!Qt(e[m]);)m++;for(;m>g+1&&oe(e[m-1]);)m--;return e.slice(g,m)}for(let m=o-1;m>d;m--)if(!Qt(e[m]))return e[m];return null}}a=i(c)}return null}function Nm(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=oe(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!oe(e[a-1]))continue;let c=a+1;if(oe(e[c])){for(;c<t&&oe(e[c]);)c++;es(e[c])&&(r[a]=a)}}let o=new Array(t+1);o[0]=0;for(let a=0;a<t;a++)o[a+1]=o[a]+(Qt(e[a])?1:0);let s=(a,c)=>o[c]===o[a],i=a=>{let c=a+1;for(;oe(e[c]);)c++;let p=c;for(;p<t&&es(e[p]);)p++;return e.slice(c,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let c=a+7;for(;c<t&&/[a-z0-9]/.test(e[c]);)c++;if(c===a+7||e[c]!=="*"||e[c+1]!=="*")continue;let p=c+2,d=p;for(;d<t&&oe(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(s(d,m))return{id:e.slice(a+2,c),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Qt(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function Km(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&oe(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&oe(e[i]);)i++;n=i}let r=e.slice(n),o="",s=0;for(;s<r.length;){if(t(r,s)&&(s===0||!es(r[s-1]))){let i=s,a=0;for(;t(r,i);){for(i+=6;i<r.length&&oe(r[i]);)i++;a++}if(a>=2){s=i;continue}}o+=r[s],s++}return o}function qm(e,t){let n=t?"![":"[",r="",o=0,s=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(s<c&&(s=e.indexOf("]",c)),s===-1)break;let p=s;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(o,a)+(t?" ":e.slice(c,p)),o=i+1,a=e.indexOf(n,o)}return r+e.slice(o)}function Gm(e){return qm(e,!0)}function Bm(e){return qm(e,!1)}function hP(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Wm(e,t){let n=Ge(e),r=Ge(t),o=e.length,s=i=>{let a=i;for(;a<o&&oe(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=s(i+r.length);if(e[a]!==":")continue;let c=s(a+1);for(let p=c;p<o;){if(!oe(e[p])){p++;continue}let d=s(p);if(hP(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var bP=new Set(["read","glob","grep","list"]);function H(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function $$(e){return bP.has(re(e))}function U$(e){let t=0,n=0,r=0;for(let o of e){let s=re(o.tool);s==="read"?t++:s==="glob"||s==="grep"?n++:s==="list"&&r++}return{read:t,search:n,list:r}}function rs(e){if(!e)return"";let t=Se(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function fr(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function os(e){let n=(e.state??{}).input??{};switch(H(e.tool)){case"read":case"edit":case"write":case"morph_edit":{let s=n.filePath??n.file_path??n.path;return s?rs(String(s)):""}case"glob":return n.pattern?String(n.pattern):"";case"grep":{let s=n.pattern??n.query,i=n.path??n.include;return s&&i?`"${fr(String(s),40)}" in ${rs(String(i))}`:s?`"${fr(String(s),60)}"`:""}case"list":return n.path?rs(String(n.path)):"";case"bash":return fr(String(n.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let s of o){let i=n[s];if(typeof i=="string"&&i.length>0)return fr(s==="query"&&mr(i)||i,60)}return""}var _P={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 L$(e,t={}){let n={..._P,...t},r=H(e.tool),o=os(e);switch(r){case"read":return{title:n.read,subtitle:o};case"glob":case"grep":return{title:n.search,subtitle:o};case"list":return{title:n.list,subtitle:o};case"bash":return{title:n.shell,subtitle:o};case"edit":case"morph_edit":return{title:n.edit,subtitle:o};case"write":return{title:n.write,subtitle:o};case"webfetch":case"web_fetch":return{title:n.fetch,subtitle:o};case"websearch":case"web_search":return{title:n.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:n.scrape,subtitle:o};case"apply_patch":return{title:n.applyPatch,subtitle:o};case"task":return{title:n.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:n.worker,subtitle:o};case"project_select":case"project_list":return{title:n.workspace,subtitle:o};default:return{title:r.replace(/_/g," ").replace(/\b\w/g,i=>i.toUpperCase()),subtitle:o}}}function we(e){return e.type==="text"}function ve(e){return e.type==="reasoning"}function X(e){return e.type==="tool"}function Vm(e){return e.type==="file"}function G$(e){return e.type==="agent"}function B$(e){return e.type==="compaction"}function W$(e){return e.type==="snapshot"}function H$(e){return e.type==="patch"}function V$(e){return e.type==="step-start"||e.type==="step-finish"}function z$(e){if(we(e)||ve(e))return e.text}function Y$(e){if(!Vm(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function Q$(e){let t=[],n=[];for(let r of e)Vm(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function X$(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function J$(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var PP=new Set(["todoread","context_info"]);function xP(e){return!PP.has(e.tool)}var SP=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 zm(e){let t=e.tool||"";if(t.startsWith("oc-"))return;let n=re(t);if(n==="task"||n==="delegate"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r}return wP(t,e.state)}function wP(e,t){let n=H(e);if(SP.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 Z$(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return ce(n.error)}}function e0(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)X(r)&&xP(r)&&t.push(r);return t}function t0(e,t={}){switch(H(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:RP(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"KortixWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"apply_patch":return{icon:"file-pen",title:"Patch",subtitle:t.files?.length?`${t.files.length} file${t.files.length>1?"s":""}`:void 0};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"prune":return{icon:"scissors",title:"DCP Prune",subtitle:t.reason};case"distill":return{icon:"scissors",title:"DCP Distill"};case"compress":return{icon:"scissors",title:"DCP Compress",subtitle:t.topic};case"context_info":return{icon:"scissors",title:"Context Info"};case"session_read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session_list_spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":return{icon:"folder",title:"Projects"};case"project_get":case"project_update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":return{icon:"clock",title:"List Triggers"};case"trigger_get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":return{icon:"layers",title:"Agent Status"};case"agent_task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":return{icon:"trash-2",title:"Delete Task",subtitle:t.id};case"pty_spawn":return{icon:"terminal",title:"Spawn",subtitle:t.title||t.command};case"pty_read":return{icon:"terminal",title:"Terminal Output",subtitle:t.id};case"pty_write":case"pty_input":return{icon:"terminal",title:"Terminal Input",subtitle:t.id};case"pty_kill":return{icon:"terminal",title:"Kill Process",subtitle:t.id};default:return vP(e,t)}}function vP(e,t){switch(re(e)){case"read":return{icon:"glasses",title:"Read",subtitle:AP(Oe(t))};case"list":return{icon:"list",title:"List",subtitle:kP(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":return{icon:"file-pen",title:"Edit",subtitle:Hm(Oe(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Hm(Oe(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function AP(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Hm(e){if(!e)return;let t=e.split("/"),n=t[t.length-1]||e;if(t.length<=1)return n;let r=t[t.length-2];return r?`${n} /${r}`:n}function kP(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function n0(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 Zt(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 RP(e){let t=Zt(e.description);if(t)return t;let n=Zt(e.title,80);if(n)return n;let r=Zt(e.message);if(r)return r;let o=Zt(e.prompt);if(o)return o;let s=Zt(e.agent_id,40);return s?`Agent ${s}`:"Worker task"}function r0(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function o0(e,t){return e.find(n=>n.tool?.callID===t)}function s0(e,t){return e.find(n=>n.tool?.callID===t)}var IP=/\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 i0(e){return e?e.replace(IP,""):""}var TP={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"},CP={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function EP(e){return e.replace(/^oc[-_]/,"")}function Ym(e){return EP(e).replace(/-/g,"_")}function Qm(e){return Ym(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function ss(e){return{label:TP[Ym(e)]??Qm(e),category:CP[re(e)]}}var MP=256*1024;function OP(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function jP(e){if(e===void 0)return{};if(e.length>MP)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function DP(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,o=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!o))return o?ce(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var J=e=>typeof e=="string"?e:void 0,yr=e=>typeof e=="number"?e:void 0,hr=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function is(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var $P=new Set(["add","update","delete","move"]);function UP(e,t,n){if(e==="apply_patch"){let c=(Array.isArray(n.files)?n.files:[]).flatMap(p=>{let d=hr(p),g=d&&(J(d.relativePath)||J(d.filePath));if(!d||!g)return[];let m=J(d.type);return[is({path:g,type:m&&$P.has(m)?m:void 0,before:J(d.before),after:J(d.after),patch:J(d.patch)??J(d.diff),additions:yr(d.additions),deletions:yr(d.deletions),movePath:J(d.movePath)})]});return c.length?c:void 0}let r=Oe(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[is({path:r,after:J(t.content)})];if(e!=="edit")return;let o=hr(n.filediff),s=o?void 0:J(n.patch),i=s?LP(s):void 0;return[is({path:r,before:J(o?.before)??J(t.oldString),after:J(o?.after)??J(t.newString),patch:s,additions:yr(o?.additions)??i?.additions,deletions:yr(o?.deletions)??i?.deletions})]}function LP(e){let t=0,n=0;for(let r of e.split(`
79
- `))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function FP(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function Xm(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:o,outputText:s}=jP(r),i=OP(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=DP(o);m&&(i="error",a=m)}let c=re(e),p=t.input??{},d="metadata"in t&&hr(t.metadata)||{},g=hr(d.diagnostics);return{name:e,kind:c,title:n||ss(e).label,status:i,input:t.input,output:r,outputParsed:o,outputText:s,error:a,files:UP(c,p,d),diff:J(d.patch)??J(d.diff),diagnostics:g,answers:c==="question"?FP(d):void 0,childSessionId:zm({tool:e,state:t})}}function m0(e){return Xm(e.tool,e.state)}function NP(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function KP(e){return{kind:"reasoning",id:e.id,text:e.text}}function qP(e){return{kind:"tool",id:e.id,tool:Xm(e.tool,e.state)}}function GP(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 BP(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function WP(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function HP(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function VP(e){return{kind:"agent",id:e.id,name:e.name}}function zP(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:ce(e.error),createdAt:e.time.created}}function YP(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function QP(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function XP(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Jm(e){switch(e.type){case"text":return NP(e);case"reasoning":return KP(e);case"tool":return qP(e);case"file":return GP(e);case"subtask":return BP(e);case"patch":return WP(e);case"snapshot":return HP(e);case"agent":return VP(e);case"retry":return zP(e);case"compaction":return YP(e);case"step-start":return QP(e);case"step-finish":return XP(e);default:return{kind:"unknown",raw:e}}}function JP(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=ge(e);return{name:t,message:n?.message||ce(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function ZP(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function ex(e){let t=e.parts.map(Jm),n=e.info.role==="assistant"?e.info.error:void 0,r=JP(n),o=!r&&!t.some(ZP);return{parts:t,error:r,isEmpty:o}}var as=Ce+BigInt(1),Zm=as/BigInt(2);function br(e){return BigInt(Math.trunc(e))*$t}function cs(e,t){let r=t-(t&Ce)+e;return r-t>Zm?r-=as:t-r>Zm&&(r+=as),r}function ef(e,t){let n=at(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return cs(n,t);let o=br(r),s=cs(n,o);return(s>o?s-o:o-s)<=Ne?s:o}function tf(e){return at(e)===null?1:0}function nf(e,t){return e<t?-1:e>t?1:0}function x0(e,t){return rf(e,t,br(Date.now()))}function tx(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 br(t??Date.now())}function rf(e,t,n){let r=tf(e.info.id),o=tf(t.info.id);if(r!==o)return r-o;if(r===0){let a=ef(e,n),c=ef(t,n);return a!==c?a<c?-1:1:nf(e.info.id,t.info.id)}let s=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return s===null&&i===null?0:s===null?1:i===null?-1:s!==i?s<i?-1:1:nf(e.info.id,t.info.id)}function S0(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=tx(e),o=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:rf(d,g,r)}),s=[],i=new Map;for(let d of o)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};s.push(g),i.set(d.info.id,g)}let a=null,c=[],p=[];for(let d of o){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=c[c.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):c.push({userMessage:rx(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=s[0]??c[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;s.push({userMessage:g,assistantMessages:m})}}return c.length>0?[...c,...s]:s}var en=new Map,nx=256;function rx(e,t){let n=t.info,r=n.time?.created,o=`${n.sessionID??""}|${e}|${r??""}`,s=en.get(o);if(s)return s;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(en.size>=nx){let a=en.keys().next().value;a!==void 0&&en.delete(a)}return en.set(o,i),i}function w0(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function v0(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(we(n)&&n.text?.trim())return n}}function A0(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function k0(e,t,n){if(n)return[];let r=[];for(let o of e.assistantMessages)for(let s of o.parts){if(!X(s))continue;let i=s,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:s,message:o})}return r}function R0(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 I0(e){let t=e-6e4;return(n,r)=>{let o=n.time.updated??n.time.created,s=r.time.updated??r.time.created,i=o>t,a=s>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:s-o}}function ox(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let o of n)r.push(o),r.push(...ox(e,o));return r}function sx(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function C0(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&&sx(n.error)}return!1}function _r(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function sf(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 O0(e){return!!e&&(sf(e)||ux(e)!==null)}function af(e){let t=of.get(e);if(t&&t.state===e.state)return t.outcome;let n=ix(e);return of.set(e,{state:e.state,outcome:n}),n}var of=new WeakMap;function ix(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(sf(n))return"failed";let r=ax(n);return r===void 0?"ok":cx(r)?"failed":lx(r)}function ax(e){try{return JSON.parse(e)}catch{return}}function cx(e){return _r(e)&&e.success===!1&&typeof e.error=="string"}function lx(e){let t=_r(e)?e.results:void 0;if(!Array.isArray(t)||t.length===0)return"ok";let n=t.filter(r=>r!==null&&typeof r=="object"&&r.success===!1).length;return n===0?"ok":n===t.length?"failed":"partial"}function ux(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!_r(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},o=Jt(r.errorSummary);if(o===null)return r;try{let s=JSON.parse(o);typeof s.message=="string"&&s.message.trim()&&(r.nestedMessage=s.message.trim()),typeof s.status=="number"&&(r.status=s.status),typeof s.error=="boolean"&&(r.nestedError=s.error)}catch{}return r}function j0(e){return Km(e).replace(/\s+/g," ").trim()||e.trim()}function D0(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!_r(n))return null;let r=n.success,o=n.error,s=n.hint;if(r!==!1||typeof o!="string")return null;let i=[];i.push(o.trim());let a=Jt(o);if(a!==null)try{let p=JSON.parse(a).message;typeof p=="string"&&p.trim()&&i.push(`Details: ${p.trim()}`)}catch{}return typeof s=="string"&&s.trim()&&i.push(`Hint: ${s.trim()}`),i.join(`
80
-
81
- `)}var px=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),dx={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 gx(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&mr(t)||t}function mx(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim())return gx(r,o.trim())}}function cf(e){if(ve(e))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!X(e))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let t=ae(e.tool),n=dx[t],r=e.state?.input;return n?{verb:n.verb,running:n.running,object:mx(r,n.objectKeys),tier:px.has(t)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:t,tier:"primary"}}function B0(e){let t=0,n=0,r=!1,o=!1;for(let s of e){if(cf(s).tier==="plumbing"){r=!0;continue}if(ve(s)){if(!s.text?.trim())continue;o||(o=!0,t+=1);continue}o=!1,t+=1,X(s)&&af(s)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function ls(e){return`${e} ${e===1?"step":"steps"}`}function W0(e,t){let{total:n,failed:r,completed:o,hasPlumbing:s}=e;return t?n===0?"Working":`Working \xB7 ${ls(n)}`:n===0?s?"Housekeeping":"Worked":r===0?`Completed ${ls(n)}`:o===0?`${ls(n)} failed`:`Completed ${o} of ${n} steps \xB7 ${r} failed`}function V0(e){let t=!1,n=!1,r=!1,o=null,s=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),o==null&&d.error!=null&&(o=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(t=!0),e.userMessage&&s(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)s(p.info),i(p.parts);return c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:o}}function Q0(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function X0(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 J0(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=Gm(n),n=Bm(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 Z0(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let o=r.error.trim(),s;for(let i=0;i<3;i++){let a=Jt(o);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(s=c.status),typeof c.message=="string"&&c.message.trim())o=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())o=c.error.trim();else break}return{message:o,status:s}}function tn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function us(e,t=30){if(!e)return[];let n=[],r=new Set,o=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},s=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=s.exec(e))!==null;)if(o(tn(i[1]),tn(i[2]),i[3]?tn(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(o(tn(i[2]),tn(i[1])),n.length>=t)return n}return n}function lf(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{return JSON.parse(n)}catch{}return null}}function Pr(e){return e.filter(t=>t.title&&t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function uf(e){if(!e)return[];let t=lf(e,!0);if(t?.success===!1)return[];if(Array.isArray(t?.results)&&t.results.length>0){let n=t.results[0];if(n&&typeof n.query=="string"){let r=[];for(let o of t.results)typeof o.query=="string"&&r.push({query:o.query,answer:o.answer||void 0,sources:Array.isArray(o.results)?Pr(o.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=Pr(t.results);if(r.length>0)return[{query:t.query||"",answer:t.answer||void 0,sources:r}]}}if(t?.query&&typeof t.query=="string")return[{query:t.query,answer:t.answer||void 0,sources:Array.isArray(t.results)?Pr(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=Pr(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let o of n){let s=o.match(/^Title:\s*(.+)/m),i=o.match(/^URL:\s*(.+)/m),a=o.match(/^Author:\s*(.+)/m),c=o.match(/^Published Date:\s*(.+)/m),p=o.match(/^Text:\s*([\s\S]*?)$/m);s&&i&&r.push({title:s[1].trim(),url:i[1].trim(),snippet:p?.[1]?.trim()||void 0,author:a?.[1]?.trim()||void 0,publishedDate:c?.[1]?.trim()||void 0})}if(r.length>0)return[{query:"",sources:r}]}if(typeof e=="string"){let n=us(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function ps(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function rU(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return ps(e)}}function oU(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function sU(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 fx(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let o=r.trim();/^https?:\/\//i.test(o)&&n.push(o)}return n}return[]}function yx(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let o=Wm(n,r)?.trim()||n;return{url:r,success:!1,error:o}})}function iU(e,t){let n=hx(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?yx(r,fx(t)):[]}function hx(e){if(!e)return null;let t=lf(e);if(!t)return null;if(t.results&&Array.isArray(t.results))return{total:t.total||t.results.length,successful:t.successful??t.results.filter(n=>n.success!==!1).length,failed:t.failed??t.results.filter(n=>n.success===!1).length,results:t.results.map(n=>({url:n.url||"",success:n.success!==!1,title:n.title||void 0,content:n.content||n.text||n.snippet||void 0,error:n.error||void 0}))};if(typeof e=="string"){let n=us(e);if(n.length>0)return{total:n.length,successful:n.length,failed:0,results:n.map(r=>({url:r.url,success:!0,title:r.title||void 0,content:r.snippet||void 0}))}}return null}function bx(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 _x={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function ds(e){return _x[re(e)]}function xr(e){let t=H(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var Px={run:"Terminal",memory:"Memory"};function dU(e){let t=ds(e);return(t==="hidden"?void 0:Px[t])??xr(e)}function nn(e,t,n){return e===1?t:n}function gs(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 gf(e){return e.length?os(e[0]):""}function me(e){return(e.state??{}).input??{}}var xx={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 Sx(e){let t=H(e.tool);if(t==="agent_task_update"||t==="task_update")switch(me(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return xx[t]??"message"}function pf(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 wx(e){let t=H(e.tool);if(t==="triggers"){let r=me(e).action||"list";return pf(r)}let n=t.match(/^trigger_(.+)$/);return pf(n?n[1]:"list")}var vx={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 Ax(e){return vx[H(e.tool)]??"read"}var kx={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function Rx(e){return kx[H(e.tool)]??"open"}function ft(e){return e.every(t=>t===e[0])}var Ix={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function Tx(e){if(H(e.tool)!=="memory")return"read";let n=me(e).command;return n&&Ix[n]||"unknown"}var Cx={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},Ex={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 Mx(e){let t=Se(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Ox(e){let t=me(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 jx(r,60);let o=typeof t.path=="string"?t.path:"";if(o)return Mx(o);let s=typeof t.url=="string"?t.url:"";if(s){let i=bx(s);return i?ps(i):"a link"}return""}function jx(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function Dx(e){let t=me(e).action;return t&&Cx[t]||"Worked on an image"}function $x(e){let t=me(e).action;return t&&Ex[t]||"Worked on a presentation"}function Ux(e){return e.slice(0,e.indexOf(":"))}var Lx={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},Fx={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 Nx(e){let t=H(e.tool);if(t==="image_gen"){let n=me(e).action;return n&&Lx[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=me(e).action;return n&&Fx[n]||"presentation:unknown"}return"shown:result"}var Kx=new Set(["create_slide","export_pdf","export_pptx"]);function gU(e){let t=H(e.tool);if(t==="image_gen")return"image";if(t==="video_gen")return"video";if(t==="presentation_gen"){let n=me(e).action;return n?Kx.has(n)?"presentation":null:"presentation"}return null}var qx={"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`},df={image:"image",video:"video",presentation:"presentation",shown:"result"};function Gx(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[Ux(r)]++;let n=[];return Object.keys(t).forEach(r=>{let o=t[r];o&&n.push(`${o} ${nn(o,df[r],`${df[r]}s`)}`)}),`Worked on ${gs(n)}`}function mf(e,t){let n=t.length,r=gf(t);switch(e){case"explore":{let o=t.filter(s=>H(s.tool)==="read").length;return o===n?`Read ${n} ${nn(n,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(t.map(i=>Oe(me(i))).filter(Boolean)).size||n,s=t.every(i=>H(i.tool)==="write")?"Wrote":"Updated";return o===1?r?`${s} ${r}`:`${s} a file`:`${s} ${o} files`}case"run":return n===1?"Ran a command":`Ran ${n} commands`;case"web":{let o=c=>{let p=H(c.tool);return p==="web_search"||p==="websearch"||p==="image_search"},s=t.filter(o).length;if(s===n)return`Searched the web \xB7 ${n} ${nn(n,"query","queries")}`;if(s===0)return`Read ${n} ${nn(n,"page","pages")}`;let i=new Set;for(let c of t)if(o(c)){let p=c.state?.output;for(let d of uf(p).flatMap(g=>g.sources))d.url&&i.add(d.url)}else{let p=c.state?.input?.url;typeof p=="string"&&p&&i.add(p)}let a=i.size||n;return`Searched and read ${a} ${nn(a,"source","sources")}`}case"create":{if(n===1){let s=t[0],i=H(s.tool);if(i==="image_gen")return Dx(s);if(i==="video_gen")return"Made a video";if(i==="presentation_gen")return $x(s);let a=Ox(s);return a?`Showed you ${a}`:"Showed you the result"}let o=t.map(Nx);return ft(o)?qx[o[0]](n):Gx(o)}case"plan":return n===1?"Planned the work":`Planned the work \xB7 ${n} steps`;case"delegate":{let o=t.map(Sx);if(ft(o))switch(o[0]){case"spawn":return n===1?"Asked a helper agent":`Worked with ${n} helper agents`;case"message":return n===1?"Sent instructions to a helper agent":`Sent instructions to ${n} helper agents`;case"status":return"Checked on a helper agent";case"stop":return n===1?"Stopped a helper agent":`Stopped ${n} helper agents`;case"done":return n===1?"A helper agent finished a task":`Helper agents finished ${n} tasks`;case"delete":return n===1?"Removed a task":`Removed ${n} tasks`}return n===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${n} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=t.map(Tx);if(ft(o))switch(o[0]){case"write":return n===1?"Wrote to its memory":`Wrote to its memory \xB7 ${n} updates`;case"delete":return n===1?"Deleted from its memory":`Deleted ${n} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=t.map(Ax);if(ft(o))switch(o[0]){case"connect":return n===1?r?`Connected to ${r}`:"Connected a connector":`Connected ${n} connectors`;case"call":return n===1?"Used a connector":`Made ${n} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=t.map(wx);if(ft(o))switch(o[0]){case"create":return n===1?"Set up an automation":`Set up ${n} automations`;case"update":return n===1?"Updated an automation":`Updated ${n} automations`;case"delete":return n===1?"Deleted an automation":`Deleted ${n} automations`;case"control":return n===1?"Adjusted an automation":`Adjusted ${n} automations`;case"test":return n===1?"Tested an automation":`Tested ${n} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=t.map(Rx);if(ft(o))switch(o[0]){case"delete":return n===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${n} projects \u2014 deletion isn't allowed`;case"create":return n===1?r?`Created ${r}`:"Created a project":`Created ${n} projects`;case"update":return n===1?r?`Updated ${r}`:"Updated your project":`Updated ${n} projects`;case"open":return n===1?r?`Opened ${r}`:"Opened your project":`Opened ${n} projects`}return r?`Worked in ${r}`:"Worked in your project"}case"skills":return n===1?r?`Used the ${r} skill`:"Used a skill":`Used ${n} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(n===1)return`Used ${xr(t[0].tool)}`;let o=Array.from(new Set(t.map(s=>xr(s.tool))));return o.length===1?`Used ${o[0]} \xB7 ${n} times`:`Used ${gs(o)}`}}}function ff(e,t){let n=gf(t);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(t.length===1){let r=H(t[0].tool)==="write"?"write":"update";return n?`Couldn't ${r} ${n}`:`Couldn't ${r} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let r=t.filter(i=>i.state?.status==="error"),o=r.length?r:t,s=Array.from(new Set(o.map(i=>xr(i.tool))));return`Couldn't finish using ${gs(s)}`}}}function Bx(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function Wx(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let o=r.state.time;typeof o?.start=="number"&&(t=Math.min(t,o.start)),typeof o?.end=="number"&&(n=Math.max(n,o.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function yf(e,t){let n=Bx(t);return{id:t[0].callID,family:e,label:n==="error"?ff(e,t):mf(e,t),parts:t,status:n,durationMs:n==="running"?void 0:Wx(t)}}function hf(e){let t=[],n=null,r=[],o=()=>{n&&r.length&&t.push(yf(n,r)),n=null,r=[]};for(let s of e){let i=ds(s.tool);if(i!=="hidden"&&!yo(s)){if(Gd(s.tool)){o(),t.push(yf(i,[s]));continue}i!==n&&(o(),n=i),r.push(s)}}return o(),t}function Hx(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function PU(e,t){let n=[],r=null,o=[],s=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(o.length!==0){for(let a of hf(o))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});o=[]}};for(let a of e)if(t(a)!=="plumbing"){if(ve(a)){let c=a.text?.trim();if(!c)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(c);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=Hx(a);continue}if(s(),X(a)){o.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}s(),i();for(let a=0;a<n.length-1;a++){let c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var Vx=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function zx(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 xU(e){let t=e.flatMap(o=>{let s=zx(o);return s?[s]:[]}).join(" ").trim();return t?Vx.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function Yx(e){return e?.info?.time??{}}function wU(e){let t=Yx(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Sr=6e4,Qx=10080*Sr,bf=1440;function _f(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 Xx(e,t){let n=t.getTime()-e.getTime(),r=n/Sr,o=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return o(Math.round(r),"minute");if(r<bf)return o(Math.round(r/60),"hour");let s=(n-(_f(t)-_f(e)))/Sr;return o(Math.round(s/bf),"day")}function Sf(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 Pf=new Map;function Jx(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,o=Pf.get(r);return o||(o=new Intl.DateTimeFormat(t.locale,n),Pf.set(r,o)),o}function wr(e,t,n){return Jx(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?Zx(r.value,n):r.value).join("")}function Zx(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function xf(e,t){return wr(e,{year:"numeric"},t)}function vU(e,t,n={}){let r=Sf(e);if(!r)return"";let o=i=>wr(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return o(!0);let s=Math.max(0,t-r.getTime());return s<Sr?"just now":s<Qx?Xx(r,new Date(t)):o(xf(r,n)!==xf(new Date(t),n))}function AU(e,t={}){let n=Sf(e);if(!n)return"";let r=wr(n,{month:"long",day:"numeric",year:"numeric"},t),o=wr(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${o}`}function TU(e,t={}){let n=[],r=[],o=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let s of e)if(!Bd(s)){if(we(s)){o(),n.push({kind:"text",part:s});continue}if(X(s)&&(Wd(s.tool)||!!t.standaloneCallIds?.has(s.callID))){o(),n.push({kind:"standalone",part:s});continue}r.push(s)}return o(),n}function eS(e){let t=ae(e);return t==="show"||t==="show_user"}function OU(e,t={}){let n=[],r=[],o=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(s=>s.part)}),r=[]};for(let s of e){if(s.kind==="standalone"&&eS(s.part.tool)&&!t.standaloneCallIds?.has(s.part.callID)){r.push(s);continue}o(),n.push(s)}return o(),n}var tS=["title","description","path","url","content","language","aspect_ratio","attachment"];function wf(e,t){if(!t||typeof t!="object")return null;let n=t;if(Hn(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let o of tS){let s=n[o];typeof s=="string"&&s&&(r[o]=s)}return r}function nS(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 jU(e){let t=[];for(let n of e){let r=n.state,o=r.input??{};if(r.status==="error"){let a=typeof o.title=="string"&&o.title?o.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let s=nS(o.items),i=s?s.map(a=>wf(n.callID,a)).filter(a=>!!a):[wf(n.callID,o)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function vf(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var rS=e=>e.time?.completed;function LU(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function oS(e,t){let n=e.userMessage.info.id;return t.pendingTurnIds.has(n)||e.assistantMessages.length===0&&t.pendingPromptIds.has(n)}function FU(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(r.userMessage.info.id));if(t)return t.userMessage.info.id;let n=e.turns.findIndex(r=>oS(r,e));return n<=0?null:e.turns[n-1].userMessage.info.id}function NU(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function KU(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:vf({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function qU(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].userMessage.info.id;if(t(r))return e[n].assistantMessages.length===0?r:null}return null}function GU(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),o=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(c=>c.userMessage.info.id)}),s=e.hintMessageId??null;if(s){if(n>=0&&t[n].userMessage.info.id===s)return o(n);let a=r.indexOf(s);if(a>=0)return o(n+1+a)}if(n>=0){let a=t[n],c=a.assistantMessages[a.assistantMessages.length-1];if(!rS(c.info)&&!c.info.error)return o(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return o(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:o(n)}function sS(e){let t=e.userMessage.parts;if(t.length===0||!t.every(s=>we(s)&&s.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let o=r[0];return X(o)&&o.tool==="bash"}function HU(e){if(sS(e))return e.assistantMessages[0].parts[0]}function QU(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 XU(e,t){return!t||!e?!1:e.type!=="idle"}function JU(e,t){return!e&&!!t}function ZU(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ge(n.error)?.message||ce(n.error)}}function eL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Tm(n.error)}}function tL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ge(n.error)}}function Af(e){if(e){if(X(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(ve(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(we(e))return"Gathering thoughts..."}}function nL(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,o=X(r)?r:void 0;if(o&&(o.tool==="task"||o.tool==="agent_task"||o.tool==="agent-task"||o.tool==="task_create"||o.tool==="task-create"||o.tool==="task_start"||o.tool==="task-start")&&o.state.status==="running"&&t&&t.length>0){for(let i=t.length-1;i>=0;i--){let a=t[i];if(a.info.role==="assistant")for(let c=a.parts.length-1;c>=0;c--){let p=Af(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let s=Af(r);if(s)return s}return"Figuring out what\u2019s next..."}function rL(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 kf=1.2;function Rf(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),o=e.cache?.read??0,s=e.cache?.write??0,i=Math.max(0,n-o-s),c=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*c.inputPer1M;return p+=r/1e6*c.outputPer1M,o>0&&(p+=o/1e6*(c.cacheReadPer1M??c.inputPer1M)),s>0&&(p+=s/1e6*(c.cacheWritePer1M??c.inputPer1M)),p}function ms(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function If(e,t,n,r){if(ms(t,n))return 0;let o=e.cost||0;if(o>0)return o;if(!r||!t||!n)return 0;let s=r(t,n);return s?Rf(e.tokens,s):0}function Tf(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function oL(e,t){let n=0,r=0,o=0,s=0,i=0,a=0,c=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){c=!0;let g=p,{providerID:m,modelID:f}=Tf(d.info);n+=If(g,m,f,t),r+=g.tokens?.input||0,o+=g.tokens?.output||0,s+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!c){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=Cf(g,t),f=g.tokens&&ms(g.providerID,g.modelID);if(m<=0&&!f)continue;c=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,o+=h.output??0,s+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(c)return{cost:n*kf,tokens:{input:r,output:o,reasoning:s,cacheRead:i,cacheWrite:a}}}function Cf(e,t){if(ms(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?Rf({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function sL(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let o=r.info,{providerID:s,modelID:i}=Tf(o),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=If(p,s,i,t));c||(a+=Cf(o,t)),n+=a}return n*kf}function iL(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function aL(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function cL(e){if(!e||e.type!=="retry")return;let t=e,n=ce(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:ge(t.message)}}function lL(e){if(!(!e||e.type!=="retry"))return ce(e.message)}function uL(e){return(e.info.summary?.diffs?.length??0)>0}function gL(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=$m(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 mL(e){return e?e.split(`
82
- `).filter(n=>n.trim()).length<=3:!1}function fL(e){if(!e)return null;let n=e.split(`
83
- `).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function yL(e){if(!e)return[];let t=[],n=e.split(`
84
- `).filter(r=>r.trim());for(let r of n){let o=Nm(r);if(o){let s=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...o,sessionId:s?.[0]})}}return t}var Be={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 bL(e,t){let n=Be[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function _L(e,t){return t?"failed":e?"running":"done"}var SL={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function wL(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function vL(e,t){if(!e)return null;let n=e.indexOf(`
85
- `),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1);if(Lm(r,"content of "," with line numbers"))return{type:"file",content:o.split(`
77
+ `)&&(n=n.slice(0,-1)),n)}function ns(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let o=e.indexOf(">",r+1+t.length);return o===-1?null:{open:r,end:o}}function Dm(e,t){let n=ns(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function $m(e,t){let n=ns(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 Um(e,t){let n=`</${t}>`,r="",o=0;for(;;){let s=ns(e,t,o);if(!s)break;let i=e.indexOf(n,s.end+1);if(i===-1)break;r+=e.slice(o,s.open),o=i+n.length}return r+e.slice(o)}function Lm(e,t,n){let r=[];for(let o of e.split(/[\n\r\u2028\u2029]/)){let s=0;for(;;){let i=o.indexOf(t,s);if(i===-1)break;let a=o.indexOf(n,i+t.length);if(a===-1)break;r.push(o.slice(i+t.length,a)),s=a+n.length}}return r}function Jt(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&oe(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function Fm(e,t,n){let r=Ge(t),o=Ge(n);for(let s of Ge(e).split(/[\n\r\u2028\u2029]/)){let i=s.indexOf(r);if(i!==-1&&s.lastIndexOf(o)>=i+r.length)return!0}return!1}function Nm(e,t){let n=Ge(e),r=t.map(Ge),o=e.length,s=c=>{let p=c;for(;p<o&&oe(e[p]);)p++;return p},i=c=>{for(let p=c;p<o;p++)if(Qt(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=o;){let c=s(a);if(c>=o)return null;let p=r.find(d=>n.startsWith(d,c));if(p!==void 0){let d=s(c+p.length);if(e[d]===":"){let g=s(d+1);if(g<o){let m=g;for(;m<o&&!Qt(e[m]);)m++;for(;m>g+1&&oe(e[m-1]);)m--;return e.slice(g,m)}for(let m=o-1;m>d;m--)if(!Qt(e[m]))return e[m];return null}}a=i(c)}return null}function Km(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=oe(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!oe(e[a-1]))continue;let c=a+1;if(oe(e[c])){for(;c<t&&oe(e[c]);)c++;es(e[c])&&(r[a]=a)}}let o=new Array(t+1);o[0]=0;for(let a=0;a<t;a++)o[a+1]=o[a]+(Qt(e[a])?1:0);let s=(a,c)=>o[c]===o[a],i=a=>{let c=a+1;for(;oe(e[c]);)c++;let p=c;for(;p<t&&es(e[p]);)p++;return e.slice(c,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let c=a+7;for(;c<t&&/[a-z0-9]/.test(e[c]);)c++;if(c===a+7||e[c]!=="*"||e[c+1]!=="*")continue;let p=c+2,d=p;for(;d<t&&oe(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(s(d,m))return{id:e.slice(a+2,c),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Qt(e[g]))return{id:e.slice(a+2,c),title:e[g],status:i(d)}}}}return null}function qm(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&oe(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&oe(e[i]);)i++;n=i}let r=e.slice(n),o="",s=0;for(;s<r.length;){if(t(r,s)&&(s===0||!es(r[s-1]))){let i=s,a=0;for(;t(r,i);){for(i+=6;i<r.length&&oe(r[i]);)i++;a++}if(a>=2){s=i;continue}}o+=r[s],s++}return o}function Gm(e,t){let n=t?"![":"[",r="",o=0,s=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let c=a+n.length;if(s<c&&(s=e.indexOf("]",c)),s===-1)break;let p=s;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(o,a)+(t?" ":e.slice(c,p)),o=i+1,a=e.indexOf(n,o)}return r+e.slice(o)}function Bm(e){return Gm(e,!0)}function Wm(e){return Gm(e,!1)}function bP(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Hm(e,t){let n=Ge(e),r=Ge(t),o=e.length,s=i=>{let a=i;for(;a<o&&oe(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=s(i+r.length);if(e[a]!==":")continue;let c=s(a+1);for(let p=c;p<o;){if(!oe(e[p])){p++;continue}let d=s(p);if(bP(e,d))return e.slice(c,p);p=d}return e.slice(c)}return null}var _P=new Set(["read","glob","grep","list"]);function H(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function F$(e){return _P.has(re(e))}function N$(e){let t=0,n=0,r=0;for(let o of e){let s=re(o.tool);s==="read"?t++:s==="glob"||s==="grep"?n++:s==="list"&&r++}return{read:t,search:n,list:r}}function rs(e){if(!e)return"";let t=Se(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function fr(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function os(e){let n=(e.state??{}).input??{};switch(H(e.tool)){case"read":case"edit":case"write":case"morph_edit":{let s=n.filePath??n.file_path??n.path;return s?rs(String(s)):""}case"glob":return n.pattern?String(n.pattern):"";case"grep":{let s=n.pattern??n.query,i=n.path??n.include;return s&&i?`"${fr(String(s),40)}" in ${rs(String(i))}`:s?`"${fr(String(s),60)}"`:""}case"list":return n.path?rs(String(n.path)):"";case"bash":return fr(String(n.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let s of o){let i=n[s];if(typeof i=="string"&&i.length>0)return fr(s==="query"&&mr(i)||i,60)}return""}var PP={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 K$(e,t={}){let n={...PP,...t},r=H(e.tool),o=os(e);switch(r){case"read":return{title:n.read,subtitle:o};case"glob":case"grep":return{title:n.search,subtitle:o};case"list":return{title:n.list,subtitle:o};case"bash":return{title:n.shell,subtitle:o};case"edit":case"morph_edit":return{title:n.edit,subtitle:o};case"write":return{title:n.write,subtitle:o};case"webfetch":case"web_fetch":return{title:n.fetch,subtitle:o};case"websearch":case"web_search":return{title:n.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:n.scrape,subtitle:o};case"apply_patch":return{title:n.applyPatch,subtitle:o};case"task":return{title:n.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:n.worker,subtitle:o};case"project_select":case"project_list":return{title:n.workspace,subtitle:o};default:return{title:r.replace(/_/g," ").replace(/\b\w/g,i=>i.toUpperCase()),subtitle:o}}}function we(e){return e.type==="text"}function ve(e){return e.type==="reasoning"}function X(e){return e.type==="tool"}function zm(e){return e.type==="file"}function H$(e){return e.type==="agent"}function V$(e){return e.type==="compaction"}function z$(e){return e.type==="snapshot"}function Y$(e){return e.type==="patch"}function Q$(e){return e.type==="step-start"||e.type==="step-finish"}function X$(e){if(we(e)||ve(e))return e.text}function J$(e){if(!zm(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function Z$(e){let t=[],n=[];for(let r of e)zm(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function e0(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function t0(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var xP=new Set(["todoread","context_info"]);function SP(e){return!xP.has(e.tool)}var wP=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 Ym(e){let t=e.tool||"";if(t.startsWith("oc-"))return;let n=re(t);if(n==="task"||n==="delegate"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r}return vP(t,e.state)}function vP(e,t){let n=H(e);if(wP.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 n0(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return ce(n.error)}}function r0(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)X(r)&&SP(r)&&t.push(r);return t}function o0(e,t={}){switch(H(e)){case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web_search":return{icon:"search",title:"Web Search",subtitle:t.query};case"scrape_webpage":return{icon:"globe",title:"Scrape",subtitle:t.urls?.split?.(",")[0]};case"image_search":return{icon:"image",title:"Image Search",subtitle:t.query};case"image_gen":return{icon:"image",title:"Image Gen",subtitle:t.prompt?.slice?.(0,40)};case"video_gen":return{icon:"cpu",title:"Video Gen",subtitle:t.prompt?.slice?.(0,40)};case"presentation_gen":{let n=t.action||"";return{icon:"presentation",title:{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[n]||"Presentation",subtitle:t.slide_title||t.presentation_name}}case"show":case"show_user":return{icon:"globe",title:"Output",subtitle:t.title||t.description};case"task":return{icon:"square-kanban",title:`Agent (${t.subagent_type||"task"})`,subtitle:IP(t)};case"session_spawn":case"session_start_background":return{icon:"square-kanban",title:`Worker (${t.agent||"KortixWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"apply_patch":return{icon:"file-pen",title:"Patch",subtitle:t.files?.length?`${t.files.length} file${t.files.length>1?"s":""}`:void 0};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"prune":return{icon:"scissors",title:"DCP Prune",subtitle:t.reason};case"distill":return{icon:"scissors",title:"DCP Distill"};case"compress":return{icon:"scissors",title:"DCP Compress",subtitle:t.topic};case"context_info":return{icon:"scissors",title:"Context Info"};case"session_read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session_list_spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":return{icon:"folder",title:"Projects"};case"project_get":case"project_update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":return{icon:"clock",title:"List Triggers"};case"trigger_get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":return{icon:"layers",title:"Agent Status"};case"agent_task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":return{icon:"trash-2",title:"Delete Task",subtitle:t.id};case"pty_spawn":return{icon:"terminal",title:"Spawn",subtitle:t.title||t.command};case"pty_read":return{icon:"terminal",title:"Terminal Output",subtitle:t.id};case"pty_write":case"pty_input":return{icon:"terminal",title:"Terminal Input",subtitle:t.id};case"pty_kill":return{icon:"terminal",title:"Kill Process",subtitle:t.id};default:return AP(e,t)}}function AP(e,t){switch(re(e)){case"read":return{icon:"glasses",title:"Read",subtitle:kP(Oe(t))};case"list":return{icon:"list",title:"List",subtitle:RP(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:Vm(Oe(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Vm(Oe(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function kP(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Vm(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 RP(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function s0(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 Zt(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 IP(e){let t=Zt(e.description);if(t)return t;let n=Zt(e.title,80);if(n)return n;let r=Zt(e.message);if(r)return r;let o=Zt(e.prompt);if(o)return o;let s=Zt(e.agent_id,40);return s?`Agent ${s}`:"Worker task"}function i0(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function a0(e,t){return e.find(n=>n.tool?.callID===t)}function c0(e,t){return e.find(n=>n.tool?.callID===t)}var TP=/\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 l0(e){return e?e.replace(TP,""):""}var CP={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"},EP={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function MP(e){return e.replace(/^oc[-_]/,"")}function Qm(e){return MP(e).replace(/-/g,"_")}function Xm(e){return Qm(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function ss(e){return{label:CP[Qm(e)]??Xm(e),category:EP[re(e)]}}var OP=256*1024;function jP(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function DP(e){if(e===void 0)return{};if(e.length>OP)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function $P(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,o=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!o))return o?ce(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var J=e=>typeof e=="string"?e:void 0,yr=e=>typeof e=="number"?e:void 0,hr=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function is(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var UP=new Set(["add","update","delete","move"]);function LP(e,t,n){if(e==="apply_patch"){let c=(Array.isArray(n.files)?n.files:[]).flatMap(p=>{let d=hr(p),g=d&&(J(d.relativePath)||J(d.filePath));if(!d||!g)return[];let m=J(d.type);return[is({path:g,type:m&&UP.has(m)?m:void 0,before:J(d.before),after:J(d.after),patch:J(d.patch)??J(d.diff),additions:yr(d.additions),deletions:yr(d.deletions),movePath:J(d.movePath)})]});return c.length?c:void 0}let r=Oe(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[is({path:r,after:J(t.content)})];if(e!=="edit")return;let o=hr(n.filediff),s=o?void 0:J(n.patch),i=s?FP(s):void 0;return[is({path:r,before:J(o?.before)??J(t.oldString),after:J(o?.after)??J(t.newString),patch:s,additions:yr(o?.additions)??i?.additions,deletions:yr(o?.deletions)??i?.deletions})]}function FP(e){let t=0,n=0;for(let r of e.split(`
79
+ `))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function NP(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function Jm(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:o,outputText:s}=DP(r),i=jP(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=$P(o);m&&(i="error",a=m)}let c=re(e),p=t.input??{},d="metadata"in t&&hr(t.metadata)||{},g=hr(d.diagnostics);return{name:e,kind:c,title:n||ss(e).label,status:i,input:t.input,output:r,outputParsed:o,outputText:s,error:a,files:LP(c,p,d),diff:J(d.patch)??J(d.diff),diagnostics:g,answers:c==="question"?NP(d):void 0,childSessionId:Ym({tool:e,state:t})}}function h0(e){return Jm(e.tool,e.state)}function KP(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function qP(e){return{kind:"reasoning",id:e.id,text:e.text}}function GP(e){return{kind:"tool",id:e.id,tool:Jm(e.tool,e.state)}}function BP(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 WP(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function HP(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function VP(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function zP(e){return{kind:"agent",id:e.id,name:e.name}}function YP(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:ce(e.error),createdAt:e.time.created}}function QP(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function XP(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function JP(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Zm(e){switch(e.type){case"text":return KP(e);case"reasoning":return qP(e);case"tool":return GP(e);case"file":return BP(e);case"subtask":return WP(e);case"patch":return HP(e);case"snapshot":return VP(e);case"agent":return zP(e);case"retry":return YP(e);case"compaction":return QP(e);case"step-start":return XP(e);case"step-finish":return JP(e);default:return{kind:"unknown",raw:e}}}function ZP(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=ge(e);return{name:t,message:n?.message||ce(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function ex(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function tx(e){let t=e.parts.map(Zm),n=e.info.role==="assistant"?e.info.error:void 0,r=ZP(n),o=!r&&!t.some(ex);return{parts:t,error:r,isEmpty:o}}var as=Ce+BigInt(1),ef=as/BigInt(2);function br(e){return BigInt(Math.trunc(e))*$t}function cs(e,t){let r=t-(t&Ce)+e;return r-t>ef?r-=as:t-r>ef&&(r+=as),r}function tf(e,t){let n=at(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return cs(n,t);let o=br(r),s=cs(n,o);return(s>o?s-o:o-s)<=Ne?s:o}function nf(e){return at(e)===null?1:0}function rf(e,t){return e<t?-1:e>t?1:0}function v0(e,t){return of(e,t,br(Date.now()))}function nx(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 br(t??Date.now())}function of(e,t,n){let r=nf(e.info.id),o=nf(t.info.id);if(r!==o)return r-o;if(r===0){let a=tf(e,n),c=tf(t,n);return a!==c?a<c?-1:1:rf(e.info.id,t.info.id)}let s=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return s===null&&i===null?0:s===null?1:i===null?-1:s!==i?s<i?-1:1:rf(e.info.id,t.info.id)}function A0(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=nx(e),o=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:of(d,g,r)}),s=[],i=new Map;for(let d of o)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};s.push(g),i.set(d.info.id,g)}let a=null,c=[],p=[];for(let d of o){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=c[c.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):c.push({userMessage:ox(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=s[0]??c[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;s.push({userMessage:g,assistantMessages:m})}}return c.length>0?[...c,...s]:s}var en=new Map,rx=256;function ox(e,t){let n=t.info,r=n.time?.created,o=`${n.sessionID??""}|${e}|${r??""}`,s=en.get(o);if(s)return s;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(en.size>=rx){let a=en.keys().next().value;a!==void 0&&en.delete(a)}return en.set(o,i),i}function k0(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function R0(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(we(n)&&n.text?.trim())return n}}function I0(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function T0(e,t,n){if(n)return[];let r=[];for(let o of e.assistantMessages)for(let s of o.parts){if(!X(s))continue;let i=s,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:s,message:o})}return r}function C0(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 E0(e){let t=e-6e4;return(n,r)=>{let o=n.time.updated??n.time.created,s=r.time.updated??r.time.created,i=o>t,a=s>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:s-o}}function sx(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let o of n)r.push(o),r.push(...sx(e,o));return r}function ix(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function O0(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&&ix(n.error)}return!1}function _r(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function af(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 $0(e){return!!e&&(af(e)||px(e)!==null)}function cf(e){let t=sf.get(e);if(t&&t.state===e.state)return t.outcome;let n=ax(e);return sf.set(e,{state:e.state,outcome:n}),n}var sf=new WeakMap;function ax(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(af(n))return"failed";let r=cx(n);return r===void 0?"ok":lx(r)?"failed":ux(r)}function cx(e){try{return JSON.parse(e)}catch{return}}function lx(e){return _r(e)&&e.success===!1&&typeof e.error=="string"}function ux(e){let t=_r(e)?e.results:void 0;if(!Array.isArray(t)||t.length===0)return"ok";let n=t.filter(r=>r!==null&&typeof r=="object"&&r.success===!1).length;return n===0?"ok":n===t.length?"failed":"partial"}function px(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!_r(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},o=Jt(r.errorSummary);if(o===null)return r;try{let s=JSON.parse(o);typeof s.message=="string"&&s.message.trim()&&(r.nestedMessage=s.message.trim()),typeof s.status=="number"&&(r.status=s.status),typeof s.error=="boolean"&&(r.nestedError=s.error)}catch{}return r}function U0(e){return qm(e).replace(/\s+/g," ").trim()||e.trim()}function L0(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!_r(n))return null;let r=n.success,o=n.error,s=n.hint;if(r!==!1||typeof o!="string")return null;let i=[];i.push(o.trim());let a=Jt(o);if(a!==null)try{let p=JSON.parse(a).message;typeof p=="string"&&p.trim()&&i.push(`Details: ${p.trim()}`)}catch{}return typeof s=="string"&&s.trim()&&i.push(`Hint: ${s.trim()}`),i.join(`
80
+
81
+ `)}var dx=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),gx={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 mx(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&mr(t)||t}function fx(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim())return mx(r,o.trim())}}function lf(e){if(ve(e))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!X(e))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let t=ae(e.tool),n=gx[t],r=e.state?.input;return n?{verb:n.verb,running:n.running,object:fx(r,n.objectKeys),tier:dx.has(t)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:t,tier:"primary"}}function V0(e){let t=0,n=0,r=!1,o=!1;for(let s of e){if(lf(s).tier==="plumbing"){r=!0;continue}if(ve(s)){if(!s.text?.trim())continue;o||(o=!0,t+=1);continue}o=!1,t+=1,X(s)&&cf(s)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function ls(e){return`${e} ${e===1?"step":"steps"}`}function z0(e,t){let{total:n,failed:r,completed:o,hasPlumbing:s}=e;return t?n===0?"Working":`Working \xB7 ${ls(n)}`:n===0?s?"Housekeeping":"Worked":r===0?`Completed ${ls(n)}`:o===0?`${ls(n)} failed`:`Completed ${o} of ${n} steps \xB7 ${r} failed`}function Q0(e){let t=!1,n=!1,r=!1,o=null,s=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),o==null&&d.error!=null&&(o=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},c=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");c&&(t=!0),e.userMessage&&s(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)s(p.info),i(p.parts);return c&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:o}}function Z0(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function eU(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 tU(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=Bm(n),n=Wm(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 nU(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let o=r.error.trim(),s;for(let i=0;i<3;i++){let a=Jt(o);if(a===null)break;let c;try{c=JSON.parse(a)}catch{break}if(typeof c.status=="number"&&(s=c.status),typeof c.message=="string"&&c.message.trim())o=c.message.trim();else if(typeof c.error=="string"&&c.error.trim())o=c.error.trim();else break}return{message:o,status:s}}function tn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function us(e,t=30){if(!e)return[];let n=[],r=new Set,o=(a,c,p)=>{!/^https?:\/\//i.test(c)||r.has(c)||n.length>=t||(r.add(c),n.push({title:a.trim()||c,url:c,snippet:p?.trim()||void 0}))},s=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=s.exec(e))!==null;)if(o(tn(i[1]),tn(i[2]),i[3]?tn(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(o(tn(i[2]),tn(i[1])),n.length>=t)return n}return n}function uf(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{return JSON.parse(n)}catch{}return null}}function Pr(e){return e.filter(t=>t.title&&t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function pf(e){if(!e)return[];let t=uf(e,!0);if(t?.success===!1)return[];if(Array.isArray(t?.results)&&t.results.length>0){let n=t.results[0];if(n&&typeof n.query=="string"){let r=[];for(let o of t.results)typeof o.query=="string"&&r.push({query:o.query,answer:o.answer||void 0,sources:Array.isArray(o.results)?Pr(o.results):[]});if(r.length>0)return r}else if(n&&(n.title||n.url)){let r=Pr(t.results);if(r.length>0)return[{query:t.query||"",answer:t.answer||void 0,sources:r}]}}if(t?.query&&typeof t.query=="string")return[{query:t.query,answer:t.answer||void 0,sources:Array.isArray(t.results)?Pr(t.results):[]}];if(Array.isArray(t)&&t.length>0&&t[0]&&(t[0].title||t[0].url)){let n=Pr(t);if(n.length>0)return[{query:"",sources:n}]}if(typeof e=="string"){let n=e.split(/(?=^Title: )/m).filter(Boolean),r=[];for(let o of n){let s=o.match(/^Title:\s*(.+)/m),i=o.match(/^URL:\s*(.+)/m),a=o.match(/^Author:\s*(.+)/m),c=o.match(/^Published Date:\s*(.+)/m),p=o.match(/^Text:\s*([\s\S]*?)$/m);s&&i&&r.push({title:s[1].trim(),url:i[1].trim(),snippet:p?.[1]?.trim()||void 0,author:a?.[1]?.trim()||void 0,publishedDate:c?.[1]?.trim()||void 0})}if(r.length>0)return[{query:"",sources:r}]}if(typeof e=="string"){let n=us(e);if(n.length>0)return[{query:"",sources:n.map(r=>({title:r.title,url:r.url,snippet:r.snippet}))}]}return[]}function ps(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function iU(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return ps(e)}}function aU(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function cU(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 yx(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let o=r.trim();/^https?:\/\//i.test(o)&&n.push(o)}return n}return[]}function hx(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let o=Hm(n,r)?.trim()||n;return{url:r,success:!1,error:o}})}function lU(e,t){let n=bx(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?hx(r,yx(t)):[]}function bx(e){if(!e)return null;let t=uf(e);if(!t)return null;if(t.results&&Array.isArray(t.results))return{total:t.total||t.results.length,successful:t.successful??t.results.filter(n=>n.success!==!1).length,failed:t.failed??t.results.filter(n=>n.success===!1).length,results:t.results.map(n=>({url:n.url||"",success:n.success!==!1,title:n.title||void 0,content:n.content||n.text||n.snippet||void 0,error:n.error||void 0}))};if(typeof e=="string"){let n=us(e);if(n.length>0)return{total:n.length,successful:n.length,failed:0,results:n.map(r=>({url:r.url,success:!0,title:r.title||void 0,content:r.snippet||void 0}))}}return null}function _x(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 Px={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function ds(e){return Px[re(e)]}function xr(e){let t=H(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var xx={run:"Terminal",memory:"Memory"};function fU(e){let t=ds(e);return(t==="hidden"?void 0:xx[t])??xr(e)}function nn(e,t,n){return e===1?t:n}function gs(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 mf(e){return e.length?os(e[0]):""}function me(e){return(e.state??{}).input??{}}var Sx={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 wx(e){let t=H(e.tool);if(t==="agent_task_update"||t==="task_update")switch(me(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return Sx[t]??"message"}function df(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 vx(e){let t=H(e.tool);if(t==="triggers"){let r=me(e).action||"list";return df(r)}let n=t.match(/^trigger_(.+)$/);return df(n?n[1]:"list")}var Ax={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 kx(e){return Ax[H(e.tool)]??"read"}var Rx={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function Ix(e){return Rx[H(e.tool)]??"open"}function ft(e){return e.every(t=>t===e[0])}var Tx={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function Cx(e){if(H(e.tool)!=="memory")return"read";let n=me(e).command;return n&&Tx[n]||"unknown"}var Ex={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},Mx={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 Ox(e){let t=Se(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function jx(e){let t=me(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 Dx(r,60);let o=typeof t.path=="string"?t.path:"";if(o)return Ox(o);let s=typeof t.url=="string"?t.url:"";if(s){let i=_x(s);return i?ps(i):"a link"}return""}function Dx(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function $x(e){let t=me(e).action;return t&&Ex[t]||"Worked on an image"}function Ux(e){let t=me(e).action;return t&&Mx[t]||"Worked on a presentation"}function Lx(e){return e.slice(0,e.indexOf(":"))}var Fx={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},Nx={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 Kx(e){let t=H(e.tool);if(t==="image_gen"){let n=me(e).action;return n&&Fx[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=me(e).action;return n&&Nx[n]||"presentation:unknown"}return"shown:result"}var qx=new Set(["create_slide","export_pdf","export_pptx"]);function yU(e){let t=H(e.tool);if(t==="image_gen")return"image";if(t==="video_gen")return"video";if(t==="presentation_gen"){let n=me(e).action;return n?qx.has(n)?"presentation":null:"presentation"}return null}var Gx={"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`},gf={image:"image",video:"video",presentation:"presentation",shown:"result"};function Bx(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[Lx(r)]++;let n=[];return Object.keys(t).forEach(r=>{let o=t[r];o&&n.push(`${o} ${nn(o,gf[r],`${gf[r]}s`)}`)}),`Worked on ${gs(n)}`}function ff(e,t){let n=t.length,r=mf(t);switch(e){case"explore":{let o=t.filter(s=>H(s.tool)==="read").length;return o===n?`Read ${n} ${nn(n,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(t.map(i=>Oe(me(i))).filter(Boolean)).size||n,s=t.every(i=>H(i.tool)==="write")?"Wrote":"Updated";return o===1?r?`${s} ${r}`:`${s} a file`:`${s} ${o} files`}case"run":return n===1?"Ran a command":`Ran ${n} commands`;case"web":{let o=c=>{let p=H(c.tool);return p==="web_search"||p==="websearch"||p==="image_search"},s=t.filter(o).length;if(s===n)return`Searched the web \xB7 ${n} ${nn(n,"query","queries")}`;if(s===0)return`Read ${n} ${nn(n,"page","pages")}`;let i=new Set;for(let c of t)if(o(c)){let p=c.state?.output;for(let d of pf(p).flatMap(g=>g.sources))d.url&&i.add(d.url)}else{let p=c.state?.input?.url;typeof p=="string"&&p&&i.add(p)}let a=i.size||n;return`Searched and read ${a} ${nn(a,"source","sources")}`}case"create":{if(n===1){let s=t[0],i=H(s.tool);if(i==="image_gen")return $x(s);if(i==="video_gen")return"Made a video";if(i==="presentation_gen")return Ux(s);let a=jx(s);return a?`Showed you ${a}`:"Showed you the result"}let o=t.map(Kx);return ft(o)?Gx[o[0]](n):Bx(o)}case"plan":return n===1?"Planned the work":`Planned the work \xB7 ${n} steps`;case"delegate":{let o=t.map(wx);if(ft(o))switch(o[0]){case"spawn":return n===1?"Asked a helper agent":`Worked with ${n} helper agents`;case"message":return n===1?"Sent instructions to a helper agent":`Sent instructions to ${n} helper agents`;case"status":return"Checked on a helper agent";case"stop":return n===1?"Stopped a helper agent":`Stopped ${n} helper agents`;case"done":return n===1?"A helper agent finished a task":`Helper agents finished ${n} tasks`;case"delete":return n===1?"Removed a task":`Removed ${n} tasks`}return n===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${n} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=t.map(Cx);if(ft(o))switch(o[0]){case"write":return n===1?"Wrote to its memory":`Wrote to its memory \xB7 ${n} updates`;case"delete":return n===1?"Deleted from its memory":`Deleted ${n} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=t.map(kx);if(ft(o))switch(o[0]){case"connect":return n===1?r?`Connected to ${r}`:"Connected a connector":`Connected ${n} connectors`;case"call":return n===1?"Used a connector":`Made ${n} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=t.map(vx);if(ft(o))switch(o[0]){case"create":return n===1?"Set up an automation":`Set up ${n} automations`;case"update":return n===1?"Updated an automation":`Updated ${n} automations`;case"delete":return n===1?"Deleted an automation":`Deleted ${n} automations`;case"control":return n===1?"Adjusted an automation":`Adjusted ${n} automations`;case"test":return n===1?"Tested an automation":`Tested ${n} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=t.map(Ix);if(ft(o))switch(o[0]){case"delete":return n===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${n} projects \u2014 deletion isn't allowed`;case"create":return n===1?r?`Created ${r}`:"Created a project":`Created ${n} projects`;case"update":return n===1?r?`Updated ${r}`:"Updated your project":`Updated ${n} projects`;case"open":return n===1?r?`Opened ${r}`:"Opened your project":`Opened ${n} projects`}return r?`Worked in ${r}`:"Worked in your project"}case"skills":return n===1?r?`Used the ${r} skill`:"Used a skill":`Used ${n} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(n===1)return`Used ${xr(t[0].tool)}`;let o=Array.from(new Set(t.map(s=>xr(s.tool))));return o.length===1?`Used ${o[0]} \xB7 ${n} times`:`Used ${gs(o)}`}}}function yf(e,t){let n=mf(t);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(t.length===1){let r=H(t[0].tool)==="write"?"write":"update";return n?`Couldn't ${r} ${n}`:`Couldn't ${r} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let r=t.filter(i=>i.state?.status==="error"),o=r.length?r:t,s=Array.from(new Set(o.map(i=>xr(i.tool))));return`Couldn't finish using ${gs(s)}`}}}function Wx(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function Hx(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let o=r.state.time;typeof o?.start=="number"&&(t=Math.min(t,o.start)),typeof o?.end=="number"&&(n=Math.max(n,o.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function hf(e,t){let n=Wx(t);return{id:t[0].callID,family:e,label:n==="error"?yf(e,t):ff(e,t),parts:t,status:n,durationMs:n==="running"?void 0:Hx(t)}}function bf(e){let t=[],n=null,r=[],o=()=>{n&&r.length&&t.push(hf(n,r)),n=null,r=[]};for(let s of e){let i=ds(s.tool);if(i!=="hidden"&&!yo(s)){if(Bd(s.tool)){o(),t.push(hf(i,[s]));continue}i!==n&&(o(),n=i),r.push(s)}}return o(),t}function Vx(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function wU(e,t){let n=[],r=null,o=[],s=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:c}=r,p=typeof a=="number"&&typeof c=="number"&&c>a?c-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(o.length!==0){for(let a of bf(o))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});o=[]}};for(let a of e)if(t(a)!=="plumbing"){if(ve(a)){let c=a.text?.trim();if(!c)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(c);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=Vx(a);continue}if(s(),X(a)){o.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}s(),i();for(let a=0;a<n.length-1;a++){let c=n[a];c.kind==="thought"&&(c.running=!1)}return n}var zx=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function Yx(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 vU(e){let t=e.flatMap(o=>{let s=Yx(o);return s?[s]:[]}).join(" ").trim();return t?zx.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function Qx(e){return e?.info?.time??{}}function kU(e){let t=Qx(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Sr=6e4,Xx=10080*Sr,_f=1440;function Pf(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 Jx(e,t){let n=t.getTime()-e.getTime(),r=n/Sr,o=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return o(Math.round(r),"minute");if(r<_f)return o(Math.round(r/60),"hour");let s=(n-(Pf(t)-Pf(e)))/Sr;return o(Math.round(s/_f),"day")}function wf(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 xf=new Map;function Zx(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,o=xf.get(r);return o||(o=new Intl.DateTimeFormat(t.locale,n),xf.set(r,o)),o}function wr(e,t,n){return Zx(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?eS(r.value,n):r.value).join("")}function eS(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function Sf(e,t){return wr(e,{year:"numeric"},t)}function RU(e,t,n={}){let r=wf(e);if(!r)return"";let o=i=>wr(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return o(!0);let s=Math.max(0,t-r.getTime());return s<Sr?"just now":s<Xx?Jx(r,new Date(t)):o(Sf(r,n)!==Sf(new Date(t),n))}function IU(e,t={}){let n=wf(e);if(!n)return"";let r=wr(n,{month:"long",day:"numeric",year:"numeric"},t),o=wr(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${o}`}function MU(e,t={}){let n=[],r=[],o=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let s of e)if(!Wd(s)){if(we(s)){o(),n.push({kind:"text",part:s});continue}if(X(s)&&(Hd(s.tool)||!!t.standaloneCallIds?.has(s.callID))){o(),n.push({kind:"standalone",part:s});continue}r.push(s)}return o(),n}function tS(e){let t=ae(e);return t==="show"||t==="show_user"}function $U(e,t={}){let n=[],r=[],o=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(s=>s.part)}),r=[]};for(let s of e){if(s.kind==="standalone"&&tS(s.part.tool)&&!t.standaloneCallIds?.has(s.part.callID)){r.push(s);continue}o(),n.push(s)}return o(),n}var nS=["title","description","path","url","content","language","aspect_ratio","attachment"];function vf(e,t){if(!t||typeof t!="object")return null;let n=t;if(Hn(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let o of nS){let s=n[o];typeof s=="string"&&s&&(r[o]=s)}return r}function rS(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 UU(e){let t=[];for(let n of e){let r=n.state,o=r.input??{};if(r.status==="error"){let a=typeof o.title=="string"&&o.title?o.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let s=rS(o.items),i=s?s.map(a=>vf(n.callID,a)).filter(a=>!!a):[vf(n.callID,o)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function Af(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var oS=e=>e.time?.completed;function KU(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function sS(e,t){let n=e.userMessage.info.id;return t.pendingTurnIds.has(n)||e.assistantMessages.length===0&&t.pendingPromptIds.has(n)}function qU(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(r.userMessage.info.id));if(t)return t.userMessage.info.id;let n=e.turns.findIndex(r=>sS(r,e));return n<=0?null:e.turns[n-1].userMessage.info.id}function GU(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function BU(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:Af({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function WU(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].userMessage.info.id;if(t(r))return e[n].assistantMessages.length===0?r:null}return null}function HU(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),o=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(c=>c.userMessage.info.id)}),s=e.hintMessageId??null;if(s){if(n>=0&&t[n].userMessage.info.id===s)return o(n);let a=r.indexOf(s);if(a>=0)return o(n+1+a)}if(n>=0){let a=t[n],c=a.assistantMessages[a.assistantMessages.length-1];if(!oS(c.info)&&!c.info.error)return o(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return o(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:o(n)}function iS(e){let t=e.userMessage.parts;if(t.length===0||!t.every(s=>we(s)&&s.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let o=r[0];return X(o)&&o.tool==="bash"}function YU(e){if(iS(e))return e.assistantMessages[0].parts[0]}function ZU(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 eL(e,t){return!t||!e?!1:e.type!=="idle"}function tL(e,t){return!e&&!!t}function nL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ge(n.error)?.message||ce(n.error)}}function rL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Cm(n.error)}}function oL(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ge(n.error)}}function kf(e){if(e){if(X(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(ve(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(we(e))return"Gathering thoughts..."}}function sL(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,o=X(r)?r:void 0;if(o&&(o.tool==="task"||o.tool==="agent_task"||o.tool==="agent-task"||o.tool==="task_create"||o.tool==="task-create"||o.tool==="task_start"||o.tool==="task-start")&&o.state.status==="running"&&t&&t.length>0){for(let i=t.length-1;i>=0;i--){let a=t[i];if(a.info.role==="assistant")for(let c=a.parts.length-1;c>=0;c--){let p=kf(a.parts[c]);if(p)return p}}return"Handing off to an agent..."}let s=kf(r);if(s)return s}return"Figuring out what\u2019s next..."}function iL(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 Rf=1.2;function If(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),o=e.cache?.read??0,s=e.cache?.write??0,i=Math.max(0,n-o-s),c=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*c.inputPer1M;return p+=r/1e6*c.outputPer1M,o>0&&(p+=o/1e6*(c.cacheReadPer1M??c.inputPer1M)),s>0&&(p+=s/1e6*(c.cacheWritePer1M??c.inputPer1M)),p}function ms(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function Tf(e,t,n,r){if(ms(t,n))return 0;let o=e.cost||0;if(o>0)return o;if(!r||!t||!n)return 0;let s=r(t,n);return s?If(e.tokens,s):0}function Cf(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function aL(e,t){let n=0,r=0,o=0,s=0,i=0,a=0,c=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){c=!0;let g=p,{providerID:m,modelID:f}=Cf(d.info);n+=Tf(g,m,f,t),r+=g.tokens?.input||0,o+=g.tokens?.output||0,s+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!c){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=Ef(g,t),f=g.tokens&&ms(g.providerID,g.modelID);if(m<=0&&!f)continue;c=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,o+=h.output??0,s+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(c)return{cost:n*Rf,tokens:{input:r,output:o,reasoning:s,cacheRead:i,cacheWrite:a}}}function Ef(e,t){if(ms(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?If({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function cL(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let o=r.info,{providerID:s,modelID:i}=Cf(o),a=0,c=!1;for(let p of r.parts)p.type==="step-finish"&&(c=!0,a+=Tf(p,s,i,t));c||(a+=Ef(o,t)),n+=a}return n*Rf}function lL(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function uL(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function pL(e){if(!e||e.type!=="retry")return;let t=e,n=ce(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:ge(t.message)}}function dL(e){if(!(!e||e.type!=="retry"))return ce(e.message)}function gL(e){return(e.info.summary?.diffs?.length??0)>0}function yL(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=Um(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 hL(e){return e?e.split(`
82
+ `).filter(n=>n.trim()).length<=3:!1}function bL(e){if(!e)return null;let n=e.split(`
83
+ `).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function _L(e){if(!e)return[];let t=[],n=e.split(`
84
+ `).filter(r=>r.trim());for(let r of n){let o=Km(r);if(o){let s=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...o,sessionId:s?.[0]})}}return t}var Be={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 xL(e,t){let n=Be[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function SL(e,t){return t?"failed":e?"running":"done"}var AL={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function kL(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function RL(e,t){if(!e)return null;let n=e.indexOf(`
85
+ `),r=n===-1?e:e.slice(0,n),o=n===-1?"":e.slice(n+1);if(Fm(r,"content of "," with line numbers"))return{type:"file",content:o.split(`
86
86
  `).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
87
87
  `)};if(/files and directories/i.test(r)){let s=t.replace(/\/$/,""),i=[];for(let a of o.split(`
88
- `)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==s&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var iS={add:{...Be.write,icon:"create"},delete:{...Be.delete,icon:"delete"},move:{...Be.rename,icon:"edit"},update:{...Be.edit,icon:"edit"}},Ef={...Be.change,icon:"edit"};function RL(e){if(e.length===0)return Ef;let t=Mf(e[0]);for(let n=1;n<e.length;n++)if(Mf(e[n])!==t)return Ef;return iS[t]}function Mf(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function TL(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 EL(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],o;for(;(o=n.exec(e))!==null;)r.push(o[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(s,i)=>r[i]?[r[i]]:[])}function jL(e){if(!e)return null;let t=Xt(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=ts(e,"content");if(r!==null){let s=r.split(`
88
+ `)){if(!a.trim())continue;let c=a.indexOf(" ");if(c===-1)continue;let p=a.slice(0,c).trim(),d=a.slice(c+1).trim();d!==s&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var aS={add:{...Be.write,icon:"create"},delete:{...Be.delete,icon:"delete"},move:{...Be.rename,icon:"edit"},update:{...Be.edit,icon:"edit"}},Mf={...Be.change,icon:"edit"};function CL(e){if(e.length===0)return Mf;let t=Of(e[0]);for(let n=1;n<e.length;n++)if(Of(e[n])!==t)return Mf;return aS[t]}function Of(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function ML(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 jL(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],o;for(;(o=n.exec(e))!==null;)r.push(o[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(s,i)=>r[i]?[r[i]]:[])}function UL(e){if(!e)return null;let t=Xt(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=ts(e,"content");if(r!==null){let s=r.split(`
89
89
  `).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
90
90
  `);return{path:n,type:"file",content:s}}let o=ts(e,"entries");if(o!==null){let s=o.split(`
91
- `).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:s}}return null}function UL(e){let t=Dm(e,"skill_content");return t!==null?t.trim():e}function aS(e){let t=Xt(e,"<skill_files>","</skill_files>");return t===null?[]:Um(t,"<file>","</file>").map(n=>n.trim())}function cS(e){let t=jm(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 lS(e){return Fm(e,["Base directory","Directory","Skill directory"])?.trim()??""}function uS(e){return Se(cS(e)||lS(e))}function LL(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Se(n.trim())}return""}var pS="skills";function dS(e){let t=Om(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(o=>o.trim());if(n.some(o=>o===".."||o==="."))return"";let r=n.at(-1)??"";return r?`${pS}/${r}`:""}function FL(e,t,n){let o=Se(t?.trim()??"")||uS(e)||dS(n),s=aS(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(s){if(s.startsWith("/"))return s;if(o)return`${o}/${s}`}return o?`${o}/SKILL.md`:null}var gS=4e3;function rn(e,t=gS){return e.length>t?`${e.slice(0,t)}
92
- \u2026`:e}function Of(e){if(e!==void 0)try{return rn(JSON.stringify(e,null,2))}catch{return}}function G(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function We(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function mS(e){let t=G(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=We(e.outputParsed);if(!n)return{kind:"web-search",query:t};let o=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(s=>{let i=We(s)??{};return{title:G(i.title)??"",url:G(i.url,i.link)??"",snippet:G(i.snippet,i.description,i.source)}});return{kind:"web-search",query:G(n.query)??t,results:o.length>0?o:void 0,answer:G(n.answer)}}var fS=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Df(e){let t=e.match(fS);return t?Number(t[1]):void 0}function yS(e,t,n){let r="",o=0;for(;;){let s=e.indexOf(t,o);if(s===-1)return r+e.slice(o);let i=e.indexOf(n,s+t.length);if(i===-1)return r+e.slice(o);r+=e.slice(o,s),o=i+n.length}}var hS=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function bS(e){let t=-1;for(let n of hS){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var _S=/\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 PS(e){return e.replace(_S,"")}function xS(e){let t=G(e.input?.command)??"",n=e.output??"",r=Df(n),s=PS(bS(yS(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:s||void 0,exitCode:r}}function ys(e){return G(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function SS(e){let t=e.status==="error"?e.error:e.output&&rn(e.output)||void 0;return{kind:"file-read",path:ys(e),preview:t}}function wS(e){let t=G(e.input?.content),n=e.status==="error"?e.error:rn(t??e.output??"")||void 0;return{kind:"file-write",path:ys(e),preview:n}}var vS=256*1024;function AS(e,t){if(e.length+t.length>vS)return;let n=e.split(`
91
+ `).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:s}}return null}function NL(e){let t=$m(e,"skill_content");return t!==null?t.trim():e}function cS(e){let t=Xt(e,"<skill_files>","</skill_files>");return t===null?[]:Lm(t,"<file>","</file>").map(n=>n.trim())}function lS(e){let t=Dm(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 uS(e){return Nm(e,["Base directory","Directory","Skill directory"])?.trim()??""}function pS(e){return Se(lS(e)||uS(e))}function KL(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Se(n.trim())}return""}var dS="skills";function gS(e){let t=jm(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(o=>o.trim());if(n.some(o=>o===".."||o==="."))return"";let r=n.at(-1)??"";return r?`${dS}/${r}`:""}function qL(e,t,n){let o=Se(t?.trim()??"")||pS(e)||gS(n),s=cS(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(s){if(s.startsWith("/"))return s;if(o)return`${o}/${s}`}return o?`${o}/SKILL.md`:null}var mS=4e3;function rn(e,t=mS){return e.length>t?`${e.slice(0,t)}
92
+ \u2026`:e}function jf(e){if(e!==void 0)try{return rn(JSON.stringify(e,null,2))}catch{return}}function G(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function We(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function fS(e){let t=G(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=We(e.outputParsed);if(!n)return{kind:"web-search",query:t};let o=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(s=>{let i=We(s)??{};return{title:G(i.title)??"",url:G(i.url,i.link)??"",snippet:G(i.snippet,i.description,i.source)}});return{kind:"web-search",query:G(n.query)??t,results:o.length>0?o:void 0,answer:G(n.answer)}}var yS=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function $f(e){let t=e.match(yS);return t?Number(t[1]):void 0}function hS(e,t,n){let r="",o=0;for(;;){let s=e.indexOf(t,o);if(s===-1)return r+e.slice(o);let i=e.indexOf(n,s+t.length);if(i===-1)return r+e.slice(o);r+=e.slice(o,s),o=i+n.length}}var bS=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function _S(e){let t=-1;for(let n of bS){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var PS=/\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 xS(e){return e.replace(PS,"")}function SS(e){let t=G(e.input?.command)??"",n=e.output??"",r=$f(n),s=xS(_S(hS(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:s||void 0,exitCode:r}}function ys(e){return G(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function wS(e){let t=e.status==="error"?e.error:e.output&&rn(e.output)||void 0;return{kind:"file-read",path:ys(e),preview:t}}function vS(e){let t=G(e.input?.content),n=e.status==="error"?e.error:rn(t??e.output??"")||void 0;return{kind:"file-write",path:ys(e),preview:n}}var AS=256*1024;function kS(e,t){if(e.length+t.length>AS)return;let n=e.split(`
93
93
  `),r=t.split(`
94
- `),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length,i=r.length;for(;s>o&&i>o&&n[s-1]===r[i-1];)s--,i--;let a=[];for(let c=0;c<o;c++)a.push({type:"unchanged",text:n[c]});for(let c=o;c<s;c++)a.push({type:"removed",text:n[c]});for(let c=o;c<i;c++)a.push({type:"added",text:r[c]});for(let c=s;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function kS(e){let t=G(e?.oldString),n=G(e?.newString);return t!==void 0&&n!==void 0?[[t,n]]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(o=>{let s=We(o),i=s&&G(s.oldText),a=s&&G(s.newText);return i!==void 0&&a!==void 0?[[i,a]]:[]})}function RS(e){let t=kS(e.input),n=t.map(([o,s])=>AS(o,s)),r=t.length&&n.every(Boolean)?n.flatMap(o=>o??[]):void 0;return{kind:"file-edit",path:ys(e),diff:r}}var $f=/^Found\s+(\d+)\s+match/i,IS=/^(\/[^:]+?):\s*/,jf=/Line\s+(\d+):/g;function TS(e){let t=e.trim(),n=t.match($f),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let o=[];for(let s of r.split(/\n\n+/)){let i=s.trim();if(!i)continue;let a=i.match(IS);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(jf.lastIndex=0;(g=jf.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,f).trim();o.push({path:c,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return o}function CS(e){return e.trim().split(`
95
- `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function ES(e){let t=G(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=$f.test(e.output.trim())?TS(e.output):CS(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function MS(e){let t=G(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=G(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function fs(e){let t=We(e)??{};return{content:G(t.content)??"",status:G(t.status)??"pending",priority:G(t.priority)}}function OS(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(fs)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(fs)};let n=We(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(fs)}:{kind:"todo",items:[]}}function jS(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let o=We(r)??{},i=(Array.isArray(o.options)?o.options:[]).flatMap(a=>{let c=We(a),p=c&&G(c.label);return p?[{label:p,description:c?G(c.description):void 0}]:[]});return{question:G(o.question)??"",header:G(o.header),options:i}})}}function DS(e){let n=e.input&&Object.keys(e.input).length>0?Of(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?rn(e.outputParsed):Of(e.outputParsed):e.outputText!==void 0?r=rn(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function $S(e){switch(re(e.name)){case"web_search":return mS(e);case"bash":return xS(e);case"read":return SS(e);case"write":return wS(e);case"edit":return RS(e);case"grep":case"glob":return ES(e);case"task":return MS(e);case"todowrite":return OS(e);case"question":return jS(e);default:return DS(e)}}var US=new Set(["AbortError","MessageAbortedError"]),LS=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],FS=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function Uf(e){let t=e.toLowerCase();return FS.some(n=>t.includes(n))?!1:LS.some(n=>t.includes(n))}function NS(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 vr(e){if(typeof e=="string")return Uf(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&US.has(n))return!0;let r=NS(t);return typeof r=="string"?Uf(r):!1}var KS=["user","runtime-disposed","orphan-finalized","wake"],GL=["orphan-finalized","wake"];function BL(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 KS.includes(n)?n:void 0}var Ar="kortix-active-instance",qS=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function GS(e){return qS.some(t=>e===t||e.startsWith(`${t}/`))}function on(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 HL(e){let t=on(e);return!!t&&t.innerPath===""}function VL(e){let t=on(e);return!t||!t.innerPath?e:t.innerPath}function BS(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=on(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return GS(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function WS(e){return e?on(e)?.instanceId??null:null}function zL(){return typeof window>"u"?null:WS(window.location.pathname)||HS()}function HS(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Ar}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function YL(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Ar}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Ar}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Ar}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function QL(e,t){return t?BS(t,e):e}function XL(e){let t=on(e);return t?t.innerPath||"/dashboard":e}function sn(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 Lf(e){let t=sn(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let o of n)if(o)try{return JSON.parse(o)}catch{}return null}var ZL=Lf;function hs(e){let t=Lf(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var eF=hs;function VS(e){return hs(e)!==null}var tF=VS,zS=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],nF=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],YS=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function QS(e){return YS.test(sn(e))}function an(e){let t=sn(e);return t?QS(t)||zS.some(n=>n.test(t)):!1}var XS=/server url not ready|sandbox is still loading/i;function rF(e){return XS.test(sn(e))||an(e)}var kr=class extends Error{constructor(t){let n=t?.trim();super(n&&an(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function JS(e){let t=hs(e);if(t){let o=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),s=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${o} is preventing OpenCode from loading. ${a}`,detail:s?`${i?`${i}: `:""}${s}`:void 0}}let n=sn(e);return an(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 oF=JS;function Ff(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`${Te()}/p/${e.external_id}/${Ie.KORTIX_MASTER}`}function cF(e,t){return e.external_id?`${Te()}/p/${e.external_id}/${t}`:null}async function mF(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function ZS(e){let t=await Le();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Je())[0];if(!r)throw new Error("Create a project before starting a sandbox");let o=await et(r.project_id,{...e?.provider?{provider:e.provider}:{}}),s=(await Ue(r.project_id,o.session_id))?.sandbox??null;return{sandbox:So(r,o,s),created:!0}}async function fF(){return(await Le().catch(()=>null))?.sandbox??null}async function yF(e){return{sandbox:(await ZS(e)).sandbox}}async function hF(e){let t=Tt(e);return t?(await Le(t).catch(()=>null))?.sandbox??null:null}async function bF(e,t){throw await Le(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function _F(e){let t=Tt(e);return(await wo().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function PF(){return null}async function xF(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Le(e);if(!t)throw new Error("Project session sandbox not found");await Un(t.project.project_id,t.session.session_id)}async function SF(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Le(e);if(!t)throw new Error("Project session sandbox not found");await Ln(t.project.project_id,t.session.session_id)}async function wF(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function vF(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function bs(e,t,n){let r=Ff(e),o=await D(`${de(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`Request failed (${o.status})`)}return await o.json()}async function TF(e,t){return bs(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function CF(e,t,n,r="member"){await bs(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function EF(e,t,n){await bs(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var _s="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function jF(e){throw F("getInvite",_s)}async function DF(e){throw F("acceptInvite",_s)}async function $F(e){throw F("declineInvite",_s)}async function LF(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function FF(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function NF(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function KF(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function GF(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function BF(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var ew=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function VF(e){return ew.includes(e)}async function zF(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 YF(e){let t=e?`?channel=${e}`:"",n=await fetch(`${Te()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Version check failed: ${n.status}`);let r=await n.json();try{let o=await tw(e||"stable");r.changelog=o.find(s=>s.version===r.version)??o[0]??null}catch{r.changelog=null}return r}async function tw(e){let t=e?`?channel=${e}`:"",n=await fetch(`${Te()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Changelog fetch failed: ${n.status}`);return(await n.json()).changelog}async function QF(){let e=await fetch(`${Te()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`All versions fetch failed: ${e.status}`);return e.json()}async function XF(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function JF(e){}async function ZF(e){}async function nN(e){return{serverTypes:[],location:e||"hel1"}}async function rN(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function oN(e){throw F("deleteInstance")}async function sN(e,t){}async function iN(){throw F("claimComputer")}async function aN(e){return null}function cN(e,t){throw F("getSandboxProvisionStreamUrl")}var Rr=class extends Error{constructor(n,r,o){super(n);this.status=r;this.body=o;this.name="HostBoundaryError"}status;body};function Nf(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 Kf(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function qf(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 W(e,t,n){let r=n?.body!==void 0,o=await fetch(`${Ct(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:Nf(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),s=await Kf(o);if(!o.ok)throw new Rr(qf(o,s),o.status,s);return s}function nw(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 gN(e,t){return W(`/marketplace/items${nw(t)}`,e)}function mN(e){return W("/marketplace/marketplaces",e)}function fN(e,t){return W(`/marketplace/items/${encodeURIComponent(e)}`,t)}function yN(e,t,n){return W(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function hN(e,t){return W("/access/check-email",t,{method:"POST",body:{email:e}})}function bN(e,t){return W("/access/request-access",t,{method:"POST",body:e})}function _N(e){return W("/auth/logout",e,{method:"POST",body:{}})}function PN(e,t){return W(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function xN(e,t){return W("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function SN(e,t){return W(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function wN(e,t){return W(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function vN(e,t,n={}){return W(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function AN(e,t){return W(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function kN(e,t,n,r){return W(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function RN(e,t){return W(`/p/public-share/${encodeURIComponent(e)}`,t)}function IN(e,t,n){return W(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function TN(e){return W("/system/maintenance",e)}function CN(e,t){return W("/system/maintenance",t,{method:"PUT",body:e})}function EN(e){return W("/user-roles",e)}function MN(e,t){return W("/system/demo-request",t,{method:"POST",body:e})}async function ON(e,t,n){let r=await fetch(`${Ct(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${nt(t)}`,{headers:Nf(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let o=await Kf(r);throw new Rr(qf(r,o),r.status,o)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function jN(e,t){throw F("openStressTestStream")}function DN(e,t){throw F("buildPublicTemplateUrl")}async function $N(e,t,n){throw F("getPublicTemplate")}var rw="kortix:connect-link:";function Ps(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let o=e.charCodeAt(r);t=Math.imul(t^o,16777619)>>>0,n=Math.imul(n^o,1540483477)>>>0}return`${rw}${t.toString(36)}${n.toString(36)}`}function LN(e,{storage:t}={}){let n=new Map,r=new Map,o=i=>{if(t)try{let a=t.getItem(Ps(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(Ps(i));return}return c}catch{return}},s=(i,a)=>{if(t)try{t.setItem(Ps(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=o(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),s(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var Gf="Could not start the connect flow.";async function FN(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:Gf}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:Gf};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var ow=3e3,sw=5e3,iw=5*6e4;function NN(e,t){let n=e===0?ow:sw;return t+n>iw?null:n}function KN(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 BN(){let e=await l.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function WN(e={}){let t=await l.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function HN(e){let t=await l.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function VN(e){let t=await l.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function zN(){let e=await l.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var QN="1";var aw="kortix.query-cache";function Wf(e){return!!e&&typeof e.then=="function"}function Bf(e){return Wf(e)?e:Promise.resolve()}function XN(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 JN(e){let{storage:t,userId:n,shouldPersist:r,version:o="1",maxAgeMs:s=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=aw,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),w=()=>{try{return Bf(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},L=(x,_)=>{if(!_)return 0;let A;try{A=JSON.parse(_)}catch{return w(),0}if(!A||A.v!==o||A.user!==n||!Array.isArray(A.queries)||p()-A.at>s)return w(),0;let T=0;for(let C of A.queries){if(!C||!Array.isArray(C.k)||C.d===void 0||typeof C.t!="number"||p()-C.t>s||!r(C.k))continue;let E=x.getQueryState(C.k);E&&E.data!==void 0&&E.dataUpdatedAt>=C.t||(x.setQueryData(C.k,C.d,{updatedAt:C.t}),x.invalidateQueries?.({queryKey:C.k,exact:!0,refetchType:"none"}),T+=1)}return T},O=x=>x.getQueryCache().getAll().filter(_=>_.state.data!==void 0&&r(_.queryKey)).map(_=>({k:_.queryKey,d:_.state.data,t:_.state.dataUpdatedAt})).sort((_,A)=>A.t-_.t),j=(x,_)=>{let A=[],T=0;for(let C of x){let E=JSON.stringify(C).length+1;T+E>_||(A.push(C),T+=E)}return A},y=async x=>{let _=j(O(x),i);for(;;){let A={v:o,user:n,at:p(),queries:_};try{await Bf(t.setItem(d,JSON.stringify(A)));return}catch{if(_.length===0)return;_=_.slice(0,Math.floor(_.length/2))}}},P=()=>{f!==null&&(clearTimeout(f),f=null)},v=()=>{P();let x=g;return!x||!m||(m=!1,h=h.then(()=>y(x)).catch(()=>{})),h},$=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,v()},a))};return{storageKey:d,restore(x){let _;try{_=t.getItem(d)}catch{return 0}return Wf(_)?_.then(A=>L(x,A)).catch(()=>0):L(x,_)},persist(x){g=x,m=!0;let _=x.getQueryCache().subscribe(A=>{A.type!=="updated"&&A.type!=="removed"&&A.type!=="added"||r(A.query.queryKey)&&$()});return()=>{_(),g===x&&(g=null,P())}},flush(){return v()},async clear(){P(),g=null,m=!1,await h,await w()}}}function ZN(){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 cw="/kortix/part/";function lw(e){return typeof e=="string"&&e.startsWith(cw)}async function rK(e){if(!lw(e))throw new Error(`not an attachment part reference: ${e}`);let t=Pe();if(!t)throw new Error("runtime url not bound");let n=await D(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function Hf(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 uw(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let s=new Set;if(t)try{s.add(new URL(t).origin)}catch{}return typeof window<"u"&&s.add(window.location.origin),s.has(n.origin)}catch{return!1}}function Vf(e,t){return uw(e,t)?(t?Hf(t):null)??Hf(e):null}function Ir(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 zf(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var pw=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function dw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gw(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let o=(t.slice(n+3).split("/")[0]??"").toLowerCase(),s=`${r}://${o}`.split("{port}").map(i=>i.split("{sandbox}").map(dw).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${s}$`).test(e)}function mw(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function Yf(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function fw(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:pw.test(n.hostname)?t.backendUrls.some(r=>{let o=mw(r);return o!==null&&Yf(o)===Yf(n)}):t.templates.some(r=>gw(n.origin,r))}async function Qf(e,t={}){if(!Ir(e))return!1;let n=R().backendUrl;n&&await ot(n).catch(()=>null);let r=[n,t.serverUrl].filter(o=>typeof o=="string"&&o.length>0);return fw(e,{templates:ng(),backendUrls:r})}async function yw(e,t={}){let n=Vf(e,t.serverUrl||R().backendUrl||void 0);if(!n)return!1;let r=await wt();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 mK(e,t={}){if(Ir(e)){if(!await Qf(e,t))return e;let n=await wt();return n?zf(e,n):e}return await yw(e,t),e}var yK=3e3;function hw(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 hK(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let o=setTimeout(r,t?.timeoutMs??3e3);try{let s=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return hw(s.status)}catch{return"unknown"}finally{clearTimeout(o),t?.signal?.removeEventListener("abort",r)}}function bw(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function PK(e,t){throw F("buildPresentationTemplatePdfUrl")}function xK(e,t){throw F("buildPresentationTemplateImageUrl")}function _w(e,t){return`${bw(e)}/presentation/convert-to-${t}`}async function SK(e,t,n,r){let o=_w(t,e),s=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!1;for(;;){let p=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,w)=>{let L=setTimeout(h,s);r?.signal?.addEventListener("abort",()=>{clearTimeout(L),w(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let h=JSON.parse(m);f=String(h.error||h.detail||h.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function AK(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 kK(e){return e==="unreachable"}function RK(e){return!e||e.status===0?"unknown":e.ok&&Xg(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var Pw=1e4,IK={connection:"unknown",faultSinceMs:null};function TK(e,t,n,r=Pw){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let o=e.faultSinceMs??n;return n-o>=r?{connection:t,faultSinceMs:o}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:o}}function Xf({optimistic:e,abort:t,inbox:n,server:r,stream:o,activity:s,nowMs:i}){let a=!!e&&i-e.atMs<xs,c=!!t&&i-t.atMs<vs;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:c,abortFloor:c?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=Ss,streamFresh:!!o&&i-o.atMs<=cn,inboxFresh:!!n&&i-n.atMs<=ws,activityFresh:!!s&&i-s.atMs<=cn}}function yt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function As(e,t,n){if(!t)return!1;let r=yt(e.started_at);if(r===null||r>=t.atMs)return!1;let o=n?.lastEnded,s=yt(o?.ended_at);return!(o&&s!==null&&Math.abs(s-t.atMs)<=1e3&&o.turn_token!==e.turn_token)}function xw(e,t,n,r){let{activity:o,server:s}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||o.atMs>n.atMs)&&o.atMs>=a?{state:"working",source:"stream",turnId:i?s.turns.find(d=>d.state==="active"&&!As(d,n,s))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:r}:null}function Sw(e,t,n,r){let{server:o,stream:s}=e,{serverFresh:i,abortFloor:a}=t,c=i?o.turns.filter(g=>!As(g,n,o)):[],p=c.find(g=>g.state==="active")??c[0],d=!!s&&!(s.type==="idle"&&s.origin==="local");return p&&o.atMs>=a&&(!d||o.atMs>=s.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:yt(p.started_at)??o.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function ww(e,t,n){let{inbox:r,server:o,stream:s}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&s.type!=="idle"&&(!p||s.atMs>o.atMs)&&s.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&o.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function vw(e,t,n,r){let{server:o,stream:s,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,w=c&&!n&&o.atMs>=p,L=d&&s.atMs>=g&&(s.type==="idle"||s.atMs>=m);if(w&&(!s||o.atMs>=s.atMs))return{state:"idle",source:"server",turnId:null,since:yt(o.lastEnded?.ended_at)??o.atMs,serverOpenTurnToken:r};if(L)return{state:s.type==="idle"?"idle":"working",source:"stream",turnId:null,since:s.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let O=o&&s?o.atMs>=s.atMs?{source:"server",atMs:o.atMs}:{source:"stream",atMs:s.atMs}:o?{source:"server",atMs:o.atMs}:s?{source:"stream",atMs:s.atMs}:{source:"server",atMs:a};return{state:"idle",source:O.source,turnId:null,since:O.atMs,serverOpenTurnToken:r}}function Jf(e){let t=Xf(e),{server:n,stream:r}=e,o=r&&r.type==="idle"&&r.origin!=="local"?r:null,s=n?.turns[0]?.turn_token??null,i=xw(e,t,o,s);if(i)return i;let{result:a,openTurn:c}=Sw(e,t,o,s);return a??ww(e,t,s)??vw(e,t,c,s)}var xs=6e4,Ss=45e3,cn=45e3,ws=1e4,NK=3e3,vs=15e3;function KK(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function qK(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 BK(e){return Jf(e)}function WK(e){let{optimistic:t,abort:n,inbox:r,server:o,stream:s,activity:i,nowMs:a}=e,c=[null,t?t.atMs+xs:null,n?n.atMs+vs:null,r?r.atMs+ws:null,o?o.atMs+Ss:null,s?s.atMs+cn:null,i?i.atMs+cn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function Aw(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(s=>s.message_id===t),r=e.last_ended,o=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!o?.message||vr({name:o.name??void 0,message:o.message})?null:o}var kw="SandboxMemoryGuard";function YK(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=Aw(e,t);if(r?.message){if(r.name!==kw)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let o=e.recent_failures?.find(a=>a.message_id===t);if(!o)return null;let s=o.ended_at?Date.parse(o.ended_at):Number.NaN;return Number.isFinite(s)&&typeof e.atMs=="number"&&e.atMs-s<2500?null:{kind:"unexplained"}}var XK=6e4;function JK(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function ZK(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var Rw=9e4;function eq(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+Rw}var nq=75e3,rq=2,oq=2e4;function Zf(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function sq(e){return e.filter(t=>t!=null).join("|")}function Iw(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function iq(e,t,n={}){let r=n.noProgressMs??75e3,o=n.maxRestarts??2,s=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Zf(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Zf(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!c&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<s)return g;let f=Iw(e.attempts,o);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var Tw={"retry-start":"retrying",restart:"restarting"};function aq(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${Tw[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function Cw(e){return e===1?"once":e===2?"twice":`${e} times`}function cq(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(o=>o.step==="restart").length,n=e.attempts.some(o=>o.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${Cw(t)}`),`Tried: ${r.join(", then ")}.`}var uq={"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 Ew(e){return!!(e.metadata??{}).legacy_migration}function pq(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return"running";case"completed":case"stopped":return Ew(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 gq={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 mq(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function ks(e){return e.runtime_sessions??e.opencode_sessions??[]}function Mw(e){let t=ks(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 yq(e){let t=Mw(e);return t?ks(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function hq(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=>ks(r).some(o=>o.id===t))??null)}var Ow=new Set;function jw(e){for(let t of[...Ow])try{t(e)}catch{}}var Dw=12e4,Tr=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},$w=1e3,Uw=15e3,ey=100,Lw=50,Fw=10;function ty(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:o},s)=>{let i=new URLSearchParams({limit:String(r)});o&&i.set("before",o);let a=await e.getToken?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...s?{signal:s}:{}});if(!c.ok)throw c.status===503?new kr(`session ${c.status}`):new b(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function Nw(e){return qw(ty(e))}function Kw(e){return new Rs({...e,loadPage:ty(e)})}async function qw(e){let t=[],n=new Set,r;do{let i=await e({limit:ey,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let o=[],s=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])s.has(a.info.id)||(s.add(a.info.id),o.push(a));return o}var Gw={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Rs=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??Gw,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??Dw,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof Tr;if(!r&&vr(n))return;if(r||this.update({freshness:an(n)?"loading":"error"}),n instanceof b&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min($w*2**this.retryAttempt,Uw);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let o=this.scheduler.now();try{let s=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?Lw:ey,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:s.messages.length,succeeded:!0}),s}catch(s){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:0,succeeded:!1}),s}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,o=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",o,{once:!0});let s,i=new Promise((c,p)=>{s=this.startTimer(()=>{let d=new Tr(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(s),n.removeEventListener("abort",o)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,o,s){let i=[...t.messages],a=new Set(this.knownUserMessageIds),c=new Set(o?[o]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<Fw&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw s?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,s?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let o,s=!1,i=()=>{s||(s=!0,this.cancelTimer(o),r())};o=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};function ny(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 Cr=1,Bw=12,Ww=15e5,Hw=3e5,Vw=336*60*60*1e3,zw="kortix.saved-copy";function Is(e){return!!e&&typeof e.then=="function"}function Yw(e,t){return Is(e)?e.then(t):t(e)}function Qw(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let o=a=>{let c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},s=o(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(s+a>t)break;s+=a,i+=1}for(;i>0;i-=1){let a=o(i);if(a.length<=t)return a}return null}function Xw(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}function Fq(e){let{storage:t,userId:n,maxSessions:r=Bw,maxBytes:o=Ww,maxEnvelopeBytes:s=Hw,maxAgeMs:i=Vw,namespace:a=zw,now:c=()=>Date.now()}=e,p=`${a}:${n}:`,d=`${p}index`,g=(x,_)=>`${p}${x}/${_}`,m=x=>{try{let _=t.getItem(x);return Is(_)?_.catch(()=>null):_}catch{return null}},f=x=>{try{let _=t.removeItem(x);Is(_)&&_.catch(()=>{})}catch{}},h=async x=>{try{await t.removeItem(x)}catch{}},w=x=>{if(!x)return[];try{let _=JSON.parse(x);return _?.v===Cr&&Array.isArray(_.entries)?_.entries:[]}catch{return[]}},L=Promise.resolve(),O=x=>{let _=L.then(x,x);return L=_.catch(()=>{}),_},j=async x=>{try{await t.setItem(d,JSON.stringify({v:Cr,entries:x}))}catch{}},y=async()=>w(await m(d)),P=async(x,_)=>{let A=[...x].sort((C,E)=>C.u-E.u),T=A.reduce((C,E)=>C+E.b,0);for(;A.length>r||T>o;){let C=A.findIndex(N=>N.s!==_);if(C===-1)break;let[E]=A.splice(C,1);T-=E.b,await h(`${p}${E.s}`)}return A},v=x=>{O(async()=>{let _=await y(),A=_.find(T=>T.s===x);A&&(A.u=c(),await j(_))})},$=x=>O(async()=>{await h(`${p}${x}`);let _=await y(),A=_.filter(T=>T.s!==x);A.length!==_.length&&await j(A)});return{keyFor:g,read(x,_){let A=`${x}/${_}`;return Yw(m(g(x,_)),T=>{if(!T)return null;let C;try{C=JSON.parse(T)}catch{return f(g(x,_)),$(A),null}return!C||C.v!==Cr||C.user!==n||c()-C.at>i||!ny(C.e)?(f(g(x,_)),$(A),null):(v(A),C.e)})},write(x,_,A){let T=`${x}/${_}`;if(!ny(A))return $(T);let C={v:Cr,user:n,at:c(),e:A},E=Qw(C,s);if(E===null)return $(T);let N=Xw(A);return O(async()=>{let Z=await y(),Y=Z.find(V=>V.s===T);if(Y&&N>0&&Y.c>N)return;let Ls=Z.filter(V=>V.s!==T),Fs={s:T,b:E.length,u:c(),c:N},Ae=await P([...Ls,Fs],T),ie=g(x,_);try{await t.setItem(ie,E)}catch{let V=Ae.filter(ee=>ee.s!==T).sort((ee,He)=>ee.u-He.u)[0];V&&(await h(`${p}${V.s}`),Ae=Ae.filter(ee=>ee.s!==V.s));try{await t.setItem(ie,E)}catch{await h(ie),Ae=Ae.filter(ee=>ee.s!==T)}}await j(Ae)})},remove(x,_){return $(`${x}/${_}`)},clear(){return O(async()=>{let x=await y();for(let _ of x)await h(`${p}${_.s}`);await h(d)})}}}var ry=null;function Nq(e){ry=e}function Kq(){return ry}function Jw(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 Zw(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function Wq(e){throw F("buildTunnelEventStreamUrl")}function Hq(e){let{url:t,token:n,method:r="GET",body:o,onEvent:s,onOpen:i,onError:a,signal:c}=e,p=new Map,d=null,g=!1;function m(O,j){s?.(O,j);let y=p.get(O);if(y)for(let P of y)try{P(j)}catch{}}async function f(){if(g)return;d=new AbortController;let O=c?AbortSignal.any([d.signal,c]):d.signal;try{let j={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&o!==void 0&&(j["Content-Type"]="application/json");let y=await fetch(t,{method:r,headers:j,body:r!=="GET"&&o!==void 0?JSON.stringify(o):void 0,signal:O,credentials:"include"});if(!y.ok)throw new Error(`SSE connection failed: ${y.status} ${y.statusText}`);if(!y.body)throw new Error("SSE response has no body");i?.();let P=y.body.getReader(),v=new TextDecoder,$="",x="message",_="";for(;!g;){let{done:A,value:T}=await P.read();if(A)break;$+=v.decode(T,{stream:!0});let C=$.split(`
94
+ `),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o++;let s=n.length,i=r.length;for(;s>o&&i>o&&n[s-1]===r[i-1];)s--,i--;let a=[];for(let c=0;c<o;c++)a.push({type:"unchanged",text:n[c]});for(let c=o;c<s;c++)a.push({type:"removed",text:n[c]});for(let c=o;c<i;c++)a.push({type:"added",text:r[c]});for(let c=s;c<n.length;c++)a.push({type:"unchanged",text:n[c]});return a}function RS(e){let t=G(e?.oldString),n=G(e?.newString);return t!==void 0&&n!==void 0?[[t,n]]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(o=>{let s=We(o),i=s&&G(s.oldText),a=s&&G(s.newText);return i!==void 0&&a!==void 0?[[i,a]]:[]})}function IS(e){let t=RS(e.input),n=t.map(([o,s])=>kS(o,s)),r=t.length&&n.every(Boolean)?n.flatMap(o=>o??[]):void 0;return{kind:"file-edit",path:ys(e),diff:r}}var Uf=/^Found\s+(\d+)\s+match/i,TS=/^(\/[^:]+?):\s*/,Df=/Line\s+(\d+):/g;function CS(e){let t=e.trim(),n=t.match(Uf),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let o=[];for(let s of r.split(/\n\n+/)){let i=s.trim();if(!i)continue;let a=i.match(TS);if(!a)continue;let c=a[1],p=i.slice(a[0].length),d=[],g;for(Df.lastIndex=0;(g=Df.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,f).trim();o.push({path:c,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return o}function ES(e){return e.trim().split(`
95
+ `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function MS(e){let t=G(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=Uf.test(e.output.trim())?CS(e.output):ES(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function OS(e){let t=G(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=G(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function fs(e){let t=We(e)??{};return{content:G(t.content)??"",status:G(t.status)??"pending",priority:G(t.priority)}}function jS(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(fs)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(fs)};let n=We(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(fs)}:{kind:"todo",items:[]}}function DS(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let o=We(r)??{},i=(Array.isArray(o.options)?o.options:[]).flatMap(a=>{let c=We(a),p=c&&G(c.label);return p?[{label:p,description:c?G(c.description):void 0}]:[]});return{question:G(o.question)??"",header:G(o.header),options:i}})}}function $S(e){let n=e.input&&Object.keys(e.input).length>0?jf(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?rn(e.outputParsed):jf(e.outputParsed):e.outputText!==void 0?r=rn(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function US(e){switch(re(e.name)){case"web_search":return fS(e);case"bash":return SS(e);case"read":return wS(e);case"write":return vS(e);case"edit":return IS(e);case"grep":case"glob":return MS(e);case"task":return OS(e);case"todowrite":return jS(e);case"question":return DS(e);default:return $S(e)}}var LS=new Set(["AbortError","MessageAbortedError"]),FS=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],NS=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function Lf(e){let t=e.toLowerCase();return NS.some(n=>t.includes(n))?!1:FS.some(n=>t.includes(n))}function KS(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 vr(e){if(typeof e=="string")return Lf(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&LS.has(n))return!0;let r=KS(t);return typeof r=="string"?Lf(r):!1}var qS=["user","runtime-disposed","orphan-finalized","wake"],HL=["orphan-finalized","wake"];function VL(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 qS.includes(n)?n:void 0}var Ar="kortix-active-instance",GS=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function BS(e){return GS.some(t=>e===t||e.startsWith(`${t}/`))}function on(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 YL(e){let t=on(e);return!!t&&t.innerPath===""}function QL(e){let t=on(e);return!t||!t.innerPath?e:t.innerPath}function WS(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=on(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return BS(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function HS(e){return e?on(e)?.instanceId??null:null}function XL(){return typeof window>"u"?null:HS(window.location.pathname)||VS()}function VS(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Ar}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function JL(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Ar}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Ar}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Ar}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function ZL(e,t){return t?WS(t,e):e}function eF(e){let t=on(e);return t?t.innerPath||"/dashboard":e}function sn(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 Ff(e){let t=sn(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let o of n)if(o)try{return JSON.parse(o)}catch{}return null}var nF=Ff;function hs(e){let t=Ff(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var rF=hs;function zS(e){return hs(e)!==null}var oF=zS,YS=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],sF=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],QS=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function XS(e){return QS.test(sn(e))}function an(e){let t=sn(e);return t?XS(t)||YS.some(n=>n.test(t)):!1}var JS=/server url not ready|sandbox is still loading/i;function iF(e){return JS.test(sn(e))||an(e)}var kr=class extends Error{constructor(t){let n=t?.trim();super(n&&an(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function ZS(e){let t=hs(e);if(t){let o=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),s=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${o} is preventing OpenCode from loading. ${a}`,detail:s?`${i?`${i}: `:""}${s}`:void 0}}let n=sn(e);return an(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 aF=ZS;function Nf(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`${Te()}/p/${e.external_id}/${Ie.KORTIX_MASTER}`}function pF(e,t){return e.external_id?`${Te()}/p/${e.external_id}/${t}`:null}async function hF(){let e=await l.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function ew(e){let t=await Le();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Je())[0];if(!r)throw new Error("Create a project before starting a sandbox");let o=await et(r.project_id,{...e?.provider?{provider:e.provider}:{}}),s=(await Ue(r.project_id,o.session_id))?.sandbox??null;return{sandbox:So(r,o,s),created:!0}}async function bF(){return(await Le().catch(()=>null))?.sandbox??null}async function _F(e){return{sandbox:(await ew(e)).sandbox}}async function PF(e){let t=Tt(e);return t?(await Le(t).catch(()=>null))?.sandbox??null:null}async function xF(e,t){throw await Le(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function SF(e){let t=Tt(e);return(await wo().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function wF(){return null}async function vF(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Le(e);if(!t)throw new Error("Project session sandbox not found");await Un(t.project.project_id,t.session.session_id)}async function AF(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Le(e);if(!t)throw new Error("Project session sandbox not found");await Ln(t.project.project_id,t.session.session_id)}async function kF(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function RF(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function bs(e,t,n){let r=Nf(e),o=await D(`${de(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`Request failed (${o.status})`)}return await o.json()}async function MF(e,t){return bs(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function OF(e,t,n,r="member"){await bs(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function jF(e,t,n){await bs(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var _s="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function UF(e){throw F("getInvite",_s)}async function LF(e){throw F("acceptInvite",_s)}async function FF(e){throw F("declineInvite",_s)}async function KF(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function qF(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function GF(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function BF(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function HF(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function VF(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var tw=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function QF(e){return tw.includes(e)}async function XF(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 JF(e){let t=e?`?channel=${e}`:"",n=await fetch(`${Te()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Version check failed: ${n.status}`);let r=await n.json();try{let o=await nw(e||"stable");r.changelog=o.find(s=>s.version===r.version)??o[0]??null}catch{r.changelog=null}return r}async function nw(e){let t=e?`?channel=${e}`:"",n=await fetch(`${Te()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Changelog fetch failed: ${n.status}`);return(await n.json()).changelog}async function ZF(){let e=await fetch(`${Te()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`All versions fetch failed: ${e.status}`);return e.json()}async function eN(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function tN(e){}async function nN(e){}async function sN(e){return{serverTypes:[],location:e||"hel1"}}async function iN(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function aN(e){throw F("deleteInstance")}async function cN(e,t){}async function lN(){throw F("claimComputer")}async function uN(e){return null}function pN(e,t){throw F("getSandboxProvisionStreamUrl")}var Rr=class extends Error{constructor(n,r,o){super(n);this.status=r;this.body=o;this.name="HostBoundaryError"}status;body};function Kf(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 qf(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Gf(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 W(e,t,n){let r=n?.body!==void 0,o=await fetch(`${Ct(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:Kf(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),s=await qf(o);if(!o.ok)throw new Rr(Gf(o,s),o.status,s);return s}function rw(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 yN(e,t){return W(`/marketplace/items${rw(t)}`,e)}function hN(e){return W("/marketplace/marketplaces",e)}function bN(e,t){return W(`/marketplace/items/${encodeURIComponent(e)}`,t)}function _N(e,t,n){return W(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function PN(e,t){return W("/access/check-email",t,{method:"POST",body:{email:e}})}function xN(e,t){return W("/access/request-access",t,{method:"POST",body:e})}function SN(e){return W("/auth/logout",e,{method:"POST",body:{}})}function wN(e,t){return W(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function vN(e,t){return W("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function AN(e,t){return W(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function kN(e,t){return W(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function RN(e,t,n={}){return W(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function IN(e,t){return W(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function TN(e,t,n,r){return W(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function CN(e,t){return W(`/p/public-share/${encodeURIComponent(e)}`,t)}function EN(e,t,n){return W(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function MN(e){return W("/system/maintenance",e)}function ON(e,t){return W("/system/maintenance",t,{method:"PUT",body:e})}function jN(e){return W("/user-roles",e)}function DN(e,t){return W("/system/demo-request",t,{method:"POST",body:e})}async function $N(e,t,n){let r=await fetch(`${Ct(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${nt(t)}`,{headers:Kf(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let o=await qf(r);throw new Rr(Gf(r,o),r.status,o)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function UN(e,t){throw F("openStressTestStream")}function LN(e,t){throw F("buildPublicTemplateUrl")}async function FN(e,t,n){throw F("getPublicTemplate")}var ow="kortix:connect-link:";function Ps(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let o=e.charCodeAt(r);t=Math.imul(t^o,16777619)>>>0,n=Math.imul(n^o,1540483477)>>>0}return`${ow}${t.toString(36)}${n.toString(36)}`}function KN(e,{storage:t}={}){let n=new Map,r=new Map,o=i=>{if(t)try{let a=t.getItem(Ps(i));if(!a)return;let c=JSON.parse(a);if(Date.parse(c.expires_at)<=Date.now()){t.removeItem(Ps(i));return}return c}catch{return}},s=(i,a)=>{if(t)try{t.setItem(Ps(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let c=o(i);return c&&r.set(i,c),c},load(i){let a=n.get(i);if(a)return a;let c=e(i).then(p=>(r.set(i,p),s(i,p),p),p=>{throw n.delete(i),p});return n.set(i,c),c}}}var Bf="Could not start the connect flow.";async function qN(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:Bf}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:Bf};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var sw=3e3,iw=5e3,aw=5*6e4;function GN(e,t){let n=e===0?sw:iw;return t+n>aw?null:n}function BN(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 VN(){let e=await l.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function zN(e={}){let t=await l.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function YN(e){let t=await l.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function QN(e){let t=await l.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function XN(){let e=await l.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var ZN="1";var cw="kortix.query-cache";function Hf(e){return!!e&&typeof e.then=="function"}function Wf(e){return Hf(e)?e:Promise.resolve()}function eK(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 tK(e){let{storage:t,userId:n,shouldPersist:r,version:o="1",maxAgeMs:s=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:c=cw,now:p=()=>Date.now()}=e,d=`${c}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),w=()=>{try{return Wf(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},L=(x,_)=>{if(!_)return 0;let A;try{A=JSON.parse(_)}catch{return w(),0}if(!A||A.v!==o||A.user!==n||!Array.isArray(A.queries)||p()-A.at>s)return w(),0;let T=0;for(let C of A.queries){if(!C||!Array.isArray(C.k)||C.d===void 0||typeof C.t!="number"||p()-C.t>s||!r(C.k))continue;let E=x.getQueryState(C.k);E&&E.data!==void 0&&E.dataUpdatedAt>=C.t||(x.setQueryData(C.k,C.d,{updatedAt:C.t}),x.invalidateQueries?.({queryKey:C.k,exact:!0,refetchType:"none"}),T+=1)}return T},O=x=>x.getQueryCache().getAll().filter(_=>_.state.data!==void 0&&r(_.queryKey)).map(_=>({k:_.queryKey,d:_.state.data,t:_.state.dataUpdatedAt})).sort((_,A)=>A.t-_.t),j=(x,_)=>{let A=[],T=0;for(let C of x){let E=JSON.stringify(C).length+1;T+E>_||(A.push(C),T+=E)}return A},y=async x=>{let _=j(O(x),i);for(;;){let A={v:o,user:n,at:p(),queries:_};try{await Wf(t.setItem(d,JSON.stringify(A)));return}catch{if(_.length===0)return;_=_.slice(0,Math.floor(_.length/2))}}},P=()=>{f!==null&&(clearTimeout(f),f=null)},v=()=>{P();let x=g;return!x||!m||(m=!1,h=h.then(()=>y(x)).catch(()=>{})),h},$=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,v()},a))};return{storageKey:d,restore(x){let _;try{_=t.getItem(d)}catch{return 0}return Hf(_)?_.then(A=>L(x,A)).catch(()=>0):L(x,_)},persist(x){g=x,m=!0;let _=x.getQueryCache().subscribe(A=>{A.type!=="updated"&&A.type!=="removed"&&A.type!=="added"||r(A.query.queryKey)&&$()});return()=>{_(),g===x&&(g=null,P())}},flush(){return v()},async clear(){P(),g=null,m=!1,await h,await w()}}}function nK(){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 lw="/kortix/part/";function uw(e){return typeof e=="string"&&e.startsWith(lw)}async function iK(e){if(!uw(e))throw new Error(`not an attachment part reference: ${e}`);let t=Pe();if(!t)throw new Error("runtime url not bound");let n=await D(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function Vf(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 pw(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let s=new Set;if(t)try{s.add(new URL(t).origin)}catch{}return typeof window<"u"&&s.add(window.location.origin),s.has(n.origin)}catch{return!1}}function zf(e,t){return pw(e,t)?(t?Vf(t):null)??Vf(e):null}function Ir(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 Yf(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var dw=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function gw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mw(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let o=(t.slice(n+3).split("/")[0]??"").toLowerCase(),s=`${r}://${o}`.split("{port}").map(i=>i.split("{sandbox}").map(gw).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${s}$`).test(e)}function fw(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function Qf(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function yw(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:dw.test(n.hostname)?t.backendUrls.some(r=>{let o=fw(r);return o!==null&&Qf(o)===Qf(n)}):t.templates.some(r=>mw(n.origin,r))}async function Xf(e,t={}){if(!Ir(e))return!1;let n=R().backendUrl;n&&await ot(n).catch(()=>null);let r=[n,t.serverUrl].filter(o=>typeof o=="string"&&o.length>0);return yw(e,{templates:rg(),backendUrls:r})}async function hw(e,t={}){let n=zf(e,t.serverUrl||R().backendUrl||void 0);if(!n)return!1;let r=await wt();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 hK(e,t={}){if(Ir(e)){if(!await Xf(e,t))return e;let n=await wt();return n?Yf(e,n):e}return await hw(e,t),e}var _K=3e3;function bw(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 PK(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let o=setTimeout(r,t?.timeoutMs??3e3);try{let s=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return bw(s.status)}catch{return"unknown"}finally{clearTimeout(o),t?.signal?.removeEventListener("abort",r)}}function _w(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function wK(e,t){throw F("buildPresentationTemplatePdfUrl")}function vK(e,t){throw F("buildPresentationTemplateImageUrl")}function Pw(e,t){return`${_w(e)}/presentation/convert-to-${t}`}async function AK(e,t,n,r){let o=Pw(t,e),s=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),c=!1;for(;;){let p=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(c||(c=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,w)=>{let L=setTimeout(h,s);r?.signal?.addEventListener("abort",()=>{clearTimeout(L),w(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let h=JSON.parse(m);f=String(h.error||h.detail||h.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function IK(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 TK(e){return e==="unreachable"}function CK(e){return!e||e.status===0?"unknown":e.ok&&Jg(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var xw=1e4,EK={connection:"unknown",faultSinceMs:null};function MK(e,t,n,r=xw){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let o=e.faultSinceMs??n;return n-o>=r?{connection:t,faultSinceMs:o}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:o}}function Jf({optimistic:e,abort:t,inbox:n,server:r,stream:o,activity:s,nowMs:i}){let a=!!e&&i-e.atMs<xs,c=!!t&&i-t.atMs<vs;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:c,abortFloor:c?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=Ss,streamFresh:!!o&&i-o.atMs<=cn,inboxFresh:!!n&&i-n.atMs<=ws,activityFresh:!!s&&i-s.atMs<=cn}}function yt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function As(e,t,n){if(!t)return!1;let r=yt(e.started_at);if(r===null||r>=t.atMs)return!1;let o=n?.lastEnded,s=yt(o?.ended_at);return!(o&&s!==null&&Math.abs(s-t.atMs)<=1e3&&o.turn_token!==e.turn_token)}function Sw(e,t,n,r){let{activity:o,server:s}=e,{serverFresh:i,abortFloor:a,activityFresh:c}=t;return c&&(!n||o.atMs>n.atMs)&&o.atMs>=a?{state:"working",source:"stream",turnId:i?s.turns.find(d=>d.state==="active"&&!As(d,n,s))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:r}:null}function ww(e,t,n,r){let{server:o,stream:s}=e,{serverFresh:i,abortFloor:a}=t,c=i?o.turns.filter(g=>!As(g,n,o)):[],p=c.find(g=>g.state==="active")??c[0],d=!!s&&!(s.type==="idle"&&s.origin==="local");return p&&o.atMs>=a&&(!d||o.atMs>=s.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:yt(p.started_at)??o.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function vw(e,t,n){let{inbox:r,server:o,stream:s}=e,{inboxFresh:i,abortFloor:a,streamFresh:c,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...c&&s.type!=="idle"&&(!p||s.atMs>o.atMs)&&s.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&o.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function Aw(e,t,n,r){let{server:o,stream:s,optimistic:i,nowMs:a}=e,{serverFresh:c,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,w=c&&!n&&o.atMs>=p,L=d&&s.atMs>=g&&(s.type==="idle"||s.atMs>=m);if(w&&(!s||o.atMs>=s.atMs))return{state:"idle",source:"server",turnId:null,since:yt(o.lastEnded?.ended_at)??o.atMs,serverOpenTurnToken:r};if(L)return{state:s.type==="idle"?"idle":"working",source:"stream",turnId:null,since:s.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let O=o&&s?o.atMs>=s.atMs?{source:"server",atMs:o.atMs}:{source:"stream",atMs:s.atMs}:o?{source:"server",atMs:o.atMs}:s?{source:"stream",atMs:s.atMs}:{source:"server",atMs:a};return{state:"idle",source:O.source,turnId:null,since:O.atMs,serverOpenTurnToken:r}}function Zf(e){let t=Jf(e),{server:n,stream:r}=e,o=r&&r.type==="idle"&&r.origin!=="local"?r:null,s=n?.turns[0]?.turn_token??null,i=Sw(e,t,o,s);if(i)return i;let{result:a,openTurn:c}=ww(e,t,o,s);return a??vw(e,t,s)??Aw(e,t,c,s)}var xs=6e4,Ss=45e3,cn=45e3,ws=1e4,GK=3e3,vs=15e3;function BK(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function WK(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 VK(e){return Zf(e)}function zK(e){let{optimistic:t,abort:n,inbox:r,server:o,stream:s,activity:i,nowMs:a}=e,c=[null,t?t.atMs+xs:null,n?n.atMs+vs:null,r?r.atMs+ws:null,o?o.atMs+Ss:null,s?s.atMs+cn:null,i?i.atMs+cn:null],p=null;for(let d of c)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function kw(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(s=>s.message_id===t),r=e.last_ended,o=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!o?.message||vr({name:o.name??void 0,message:o.message})?null:o}var Rw="SandboxMemoryGuard";function JK(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=kw(e,t);if(r?.message){if(r.name!==Rw)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],c=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:c}}let o=e.recent_failures?.find(a=>a.message_id===t);if(!o)return null;let s=o.ended_at?Date.parse(o.ended_at):Number.NaN;return Number.isFinite(s)&&typeof e.atMs=="number"&&e.atMs-s<2500?null:{kind:"unexplained"}}var eq=6e4;function tq(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function nq(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var Iw=9e4;function rq(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+Iw}var sq=75e3,iq=2,aq=2e4;function ey(){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 Tw(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function lq(e,t,n={}){let r=n.noProgressMs??75e3,o=n.maxRestarts??2,s=n.cooldownMs??2e4;if(t.runtimeReachable)return{...ey(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...ey(),settled:!0};let i=e.lastProgressAtMs,a=i===null,c=t.progress!==e.fingerprint,p=i===null||c?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!c&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<s)return g;let f=Tw(e.attempts,o);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var Cw={"retry-start":"retrying",restart:"restarting"};function uq(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${Cw[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function Ew(e){return e===1?"once":e===2?"twice":`${e} times`}function pq(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(o=>o.step==="restart").length,n=e.attempts.some(o=>o.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${Ew(t)}`),`Tried: ${r.join(", then ")}.`}var gq={"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 Mw(e){return!!(e.metadata??{}).legacy_migration}function mq(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return"running";case"completed":case"stopped":return Mw(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function fq(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 yq={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 hq(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function ks(e){return e.runtime_sessions??e.opencode_sessions??[]}function Ow(e){let t=ks(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 _q(e){let t=Ow(e);return t?ks(e).filter(n=>n.parent_id===t.id&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function Pq(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=>ks(r).some(o=>o.id===t))??null)}var jw=new Set;function Dw(e){for(let t of[...jw])try{t(e)}catch{}}var $w=12e4,Tr=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},Uw=1e3,Lw=15e3,ty=100,Fw=50,Nw=10;function ny(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:o},s)=>{let i=new URLSearchParams({limit:String(r)});o&&i.set("before",o);let a=await e.getToken?.(),c=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...s?{signal:s}:{}});if(!c.ok)throw c.status===503?new kr(`session ${c.status}`):new b(`Session synchronization failed: ${c.status}`,{status:c.status});return{messages:await c.json(),nextCursor:c.headers.get("x-next-cursor")||void 0}}}function Kw(e){return Gw(ny(e))}function qw(e){return new Rs({...e,loadPage:ny(e)})}async function Gw(e){let t=[],n=new Set,r;do{let i=await e({limit:ty,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let o=[],s=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])s.has(a.info.id)||(s.add(a.info.id),o.push(a));return o}var Bw={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Rs=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??Bw,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??$w,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof Tr;if(!r&&vr(n))return;if(r||this.update({freshness:an(n)?"loading":"error"}),n instanceof b&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(Uw*2**this.retryAttempt,Lw);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let o=this.scheduler.now();try{let s=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?Fw:ty,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:s.messages.length,succeeded:!0}),s}catch(s){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:0,succeeded:!1}),s}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,o=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",o,{once:!0});let s,i=new Promise((c,p)=>{s=this.startTimer(()=>{let d=new Tr(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(c){a=Promise.reject(c)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(s),n.removeEventListener("abort",o)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,o,s){let i=[...t.messages],a=new Set(this.knownUserMessageIds),c=new Set(o?[o]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<Nw&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(c.has(p))throw new Error(`Session history cursor repeated: ${p}`);c.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw s?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,s?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let o,s=!1,i=()=>{s||(s=!0,this.cancelTimer(o),r())};o=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};function ry(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 Cr=1,Ww=12,Hw=15e5,Vw=3e5,zw=336*60*60*1e3,Yw="kortix.saved-copy";function Is(e){return!!e&&typeof e.then=="function"}function Qw(e,t){return Is(e)?e.then(t):t(e)}function Xw(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let o=a=>{let c=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:c,message_count:c.length,complete:!1,next_cursor:String(c[0].info.id)}})},s=o(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(s+a>t)break;s+=a,i+=1}for(;i>0;i-=1){let a=o(i);if(a.length<=t)return a}return null}function Jw(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}function qq(e){let{storage:t,userId:n,maxSessions:r=Ww,maxBytes:o=Hw,maxEnvelopeBytes:s=Vw,maxAgeMs:i=zw,namespace:a=Yw,now:c=()=>Date.now()}=e,p=`${a}:${n}:`,d=`${p}index`,g=(x,_)=>`${p}${x}/${_}`,m=x=>{try{let _=t.getItem(x);return Is(_)?_.catch(()=>null):_}catch{return null}},f=x=>{try{let _=t.removeItem(x);Is(_)&&_.catch(()=>{})}catch{}},h=async x=>{try{await t.removeItem(x)}catch{}},w=x=>{if(!x)return[];try{let _=JSON.parse(x);return _?.v===Cr&&Array.isArray(_.entries)?_.entries:[]}catch{return[]}},L=Promise.resolve(),O=x=>{let _=L.then(x,x);return L=_.catch(()=>{}),_},j=async x=>{try{await t.setItem(d,JSON.stringify({v:Cr,entries:x}))}catch{}},y=async()=>w(await m(d)),P=async(x,_)=>{let A=[...x].sort((C,E)=>C.u-E.u),T=A.reduce((C,E)=>C+E.b,0);for(;A.length>r||T>o;){let C=A.findIndex(N=>N.s!==_);if(C===-1)break;let[E]=A.splice(C,1);T-=E.b,await h(`${p}${E.s}`)}return A},v=x=>{O(async()=>{let _=await y(),A=_.find(T=>T.s===x);A&&(A.u=c(),await j(_))})},$=x=>O(async()=>{await h(`${p}${x}`);let _=await y(),A=_.filter(T=>T.s!==x);A.length!==_.length&&await j(A)});return{keyFor:g,read(x,_){let A=`${x}/${_}`;return Qw(m(g(x,_)),T=>{if(!T)return null;let C;try{C=JSON.parse(T)}catch{return f(g(x,_)),$(A),null}return!C||C.v!==Cr||C.user!==n||c()-C.at>i||!ry(C.e)?(f(g(x,_)),$(A),null):(v(A),C.e)})},write(x,_,A){let T=`${x}/${_}`;if(!ry(A))return $(T);let C={v:Cr,user:n,at:c(),e:A},E=Xw(C,s);if(E===null)return $(T);let N=Jw(A);return O(async()=>{let Z=await y(),Y=Z.find(V=>V.s===T);if(Y&&N>0&&Y.c>N)return;let Ls=Z.filter(V=>V.s!==T),Fs={s:T,b:E.length,u:c(),c:N},Ae=await P([...Ls,Fs],T),ie=g(x,_);try{await t.setItem(ie,E)}catch{let V=Ae.filter(ee=>ee.s!==T).sort((ee,He)=>ee.u-He.u)[0];V&&(await h(`${p}${V.s}`),Ae=Ae.filter(ee=>ee.s!==V.s));try{await t.setItem(ie,E)}catch{await h(ie),Ae=Ae.filter(ee=>ee.s!==T)}}await j(Ae)})},remove(x,_){return $(`${x}/${_}`)},clear(){return O(async()=>{let x=await y();for(let _ of x)await h(`${p}${_.s}`);await h(d)})}}}var oy=null;function Gq(e){oy=e}function Bq(){return oy}function Zw(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 ev(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function zq(e){throw F("buildTunnelEventStreamUrl")}function Yq(e){let{url:t,token:n,method:r="GET",body:o,onEvent:s,onOpen:i,onError:a,signal:c}=e,p=new Map,d=null,g=!1;function m(O,j){s?.(O,j);let y=p.get(O);if(y)for(let P of y)try{P(j)}catch{}}async function f(){if(g)return;d=new AbortController;let O=c?AbortSignal.any([d.signal,c]):d.signal;try{let j={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&o!==void 0&&(j["Content-Type"]="application/json");let y=await fetch(t,{method:r,headers:j,body:r!=="GET"&&o!==void 0?JSON.stringify(o):void 0,signal:O,credentials:"include"});if(!y.ok)throw new Error(`SSE connection failed: ${y.status} ${y.statusText}`);if(!y.body)throw new Error("SSE response has no body");i?.();let P=y.body.getReader(),v=new TextDecoder,$="",x="message",_="";for(;!g;){let{done:A,value:T}=await P.read();if(A)break;$+=v.decode(T,{stream:!0});let C=$.split(`
96
96
  `);$=C.pop()||"";for(let E of C)E===""?_&&(m(x,_.trimEnd()),x="message",_=""):E.startsWith("event: ")?x=E.slice(7).trim():E.startsWith("data: ")?_+=(_?`
97
97
  `:"")+E.slice(6):E.startsWith("data:")&&(_+=(_?`
98
- `:"")+E.slice(5))}}catch(j){if(g||j instanceof DOMException&&j.name==="AbortError")return;a?.(j instanceof Error?j:new Error(String(j)))}}function h(){g=!0,d?.abort(),d=null,p.clear()}function w(O,j){let y=p.get(O)??new Set;y.add(j),p.set(O,y)}function L(O,j){p.get(O)?.delete(j)}return{connect:f,close:h,addEventListener:w,removeEventListener:L}}function Vq(e,t){throw F("createTunnelEventStream")}var oy="/_kortix/viewer";var ht=new Map;function ev(){ht.clear()}async function tv(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 sy(e={}){let t=e.path??oy,n=e.fetch??((s,i)=>fetch(s,i)),r=ht.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let o=tv(t,n).then(s=>{let i=s?.expires_at?Date.parse(s.expires_at):Number.NaN,a=Number.isFinite(i)?i-6e4:Date.now()+6e4;return ht.set(t,{session:s,expiresAt:a}),s});return ht.set(t,{session:r?.session??null,expiresAt:0,inflight:o}),o}function nv(e={}){let t=e.path??oy;return Object.assign(async()=>(await sy(e))?.access_token??null,{invalidate:n=>{let r=ht.get(t);r&&!r.inflight&&r.session?.access_token===n&&ht.delete(t)}})}function iy(e){let t=e.agents.map(rv),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function rv(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function ay(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>xo(n?{...r,mode:null}:r))}function ov(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let s=e.selectedAgent?.trim();return s?{selected:s,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=ay(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(s=>s.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let o=e.defaultAgent?.trim();return o&&n.some(s=>s.name===o)?{selected:o,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var sv=iy;function cy(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Ts(e){return{providerID:"kortix",modelID:e}}function iv(e,t){let n=e.startsWith("kortix/")?e.slice(7):e;if(!t){let r=n.indexOf("/");if(r>0&&r<n.length-1)return{providerID:n.slice(0,r),modelID:n.slice(r+1)}}return Ts(n)}var Cs=[{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"v0",env:["V0_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"kimi-for-coding",env:["KIMI_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]}];function Es(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function cv(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function ly(e,t){let n=new Map;for(let r of e){let o=t(r),s=n.get(o);s?s.push(r):n.set(o,[r])}return n}function se(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function uy(e){return e.reduce((t,n)=>{let r=Es(n)??0,o=Es(t)??0;return r!==o?r>o?n:t:se(n.id)>se(t.id)?n:t})}function Ms(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,o=new Set;for(let[,s]of ly(e,cv)){let a=[...ly(s,p=>p.family||p.id).values()].map(uy),c=a.filter(p=>{let d=Es(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[uy(a)])o.add(p.id)}return o}function Er(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>se(r.id)>0)?n.filter(r=>se(r.id)>0):n}function ln(e){let t;for(let n of Er(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&se(n.id)>se(t.id))&&(t=n)}return t}var lv={"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 py(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var uv=(()=>{let e=new Map;for(let{id:n,env:r}of Cs)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let o=[...r].sort((s,i)=>s.length-i.length||s.localeCompare(i));t.set(n,r.find(s=>py(s)===n)??o[0])}return t})();function dy(e){let t=lv[e.id];if(t)return t;let n=e.env??[],r=n.length===1?uv.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[py(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function js(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var pv=["low","medium","high"];function gy(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:[...pv]}:void 0,o=e.temperature===!0,s=e.limit?.output,i=typeof s=="number"&&s>0?{ceiling:s}:void 0;return{reasoningEffort:r,temperature:o,topP:o,maxOutputTokens:i}}var my=Cs;var Os={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var Mr=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash",transport:"openrouter",morphModelId:"morph-dsv41flash",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"coreweave/fp8":{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["coreweave/fp8"],...Os,max_price:{prompt:.3,completion:1.2}}},{id:"glm-5.3-flash",name:"GLM 5.3 Flash",upstreamModelId:"z-ai/glm-5.3-flash",transport:"openrouter",morphModelId:"morph-glm53flash",morphPricing:{inputPerMillion:.1,cachedInputPerMillion:.02,outputPerMillion:.35},pricingRef:"openrouter/z-ai/glm-5.3-flash",pricing:{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5},openrouterEndpointPricing:{"decart/fp4":{inputPerMillion:.1275,cachedInputPerMillion:.0255,outputPerMillion:.425},"coreweave/nvfp4":{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5}},tier:"fast",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["low","high","max"]}],openrouterProvider:{only:["decart/fp4","coreweave/nvfp4"],...Os,max_price:{prompt:.15,completion:.5}}},{id:"kimi-k3",name:"Kimi K3 2.8T",upstreamModelId:"moonshotai/kimi-k3",transport:"openrouter",morphModelId:"morph-kimik3",morphPricing:{inputPerMillion:2.5,cachedInputPerMillion:.29,outputPerMillion:14},pricingRef:"openrouter/moonshotai/kimi-k3",pricing:{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5},openrouterEndpointPricing:{"fireworks/us":{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5}},tier:"flagship",vision:!0,limit:{context:1e6,output:65536},openrouterProvider:{only:["fireworks/us"],...Os,max_price:{prompt:3.3,completion:16.5}}}],rG=new Map(Mr.map(e=>[e.id,e]));var fy=Mr.map(e=>e.id),yy=(Mr.find(e=>e.tier==="flagship")??Mr[0]).id;var by=my.map(e=>({id:e.id,authRequirement:dy(e)})),un=new Set(["kortix"]),Ds=new Set(["kortix"]);function bt(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,o=Array.isArray(r)?r:[];return o.length===0?{...e,all:[],connected:[]}:{...e,all:o,connected:o.map(s=>s.id)}}function dv(e){if(!e)return!1;let t=bt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(o=>r.includes(o.id)&&o.models&&Object.keys(o.models).length>0)}function gv(e){let t=bt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(o=>!Ds.has(o.id)),connected:r.filter(o=>!Ds.has(o))}}function mv(e,t,n){let r=bt(e),o=Array.isArray(r.all)?r.all:[],s=new Set(o.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)s.has(a.id)&&js(a.authRequirement,c=>t.has(c))&&i.add(a.id);return s.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var fv=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function yv(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var $s="opencode";function hv(e){return e.cost?.input===0&&e.cost?.output===0}function hy(e){return e===$s?Number.MAX_SAFE_INTEGER:fv.get(e)??Number.MAX_SAFE_INTEGER-1}function bv(e,t){let n=Pv(t),r={},o=(e.providers??[]).map(s=>{let i=(s.models??[]).filter(a=>a.status!=="deprecated");return s.id===$s&&!n.has($s)?{...s,models:i.filter(hv),keyless:!0}:{...s,models:i,keyless:!1}}).filter(s=>(s.keyless||n.has(s.id))&&!Ds.has(s.id)&&(s.models?.length??0)>0).sort((s,i)=>hy(s.id)-hy(i.id)).map(s=>{let i=[...s.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||se(p.id)-se(c.id)),a=ln(i)?.id??i[0]?.id;return a&&(r[s.id]=a),{id:s.id,name:s.name,source:s.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=yv(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:o,connected:o.map(s=>s.id),default:r}}function _v(e,t){if(!e)return t;if(!t)return e;let n=bt(e),r=bt(t),o=new Map;for(let d of Array.isArray(r.all)?r.all:[])o.set(d.id,d);let s=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])s.push(o.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(s.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=o.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:s,connected:a,default:p}}function Pv(e){let t=new Set;for(let n of by)js(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function xv(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,o])=>{if(o.variants&&Object.keys(o.variants).length>0)return[r,o];let s=gy({id:r,name:o.name,reasoning:o.reasoning,reasoning_options:o.reasoning_options}).reasoningEffort?.values;return s?.length?[r,{...o,variants:Object.fromEntries(s.map(i=>[i,{}]))}]:[r,o]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function Sv(e,t){return gv(mv(bt(e),t,by))}function wv(e){if(e.gatewayEnabled)return e.modelPicker?xv(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?Sv(e.runtimeProviders,t):void 0;return _v(e.llmCatalogProviders?bv(e.llmCatalogProviders,t):void 0,dv(n)?n:void 0)}function vv(e){return"capabilities"in e&&e.capabilities!=null}function Us(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function Av(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],o=Array.isArray(e.connected)?e.connected:[],s=[];for(let i of r)if(o.includes(i.id)&&!(n==="gateway"?!un.has(i.id):un.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(vv(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}s.push({id:cy({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return s}function _y(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var kv=new Set([yy]),Rv="kortix",Py="codex",Iv=new Set(fy);function Tv(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function _t(e){return kv.has(e.modelID)}function Cv(e){return Ms(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function Ev(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=Cv(e.catalogModels),o=_y(e.catalogModels),s=new Map;for(let i of e.pins??[])s.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,c=s.get(a);if(c==="hide")return!1;if(i.providerID===Rv){let d=Tv(i.modelID,i.provider),g=d===Py?t?.has(Py)??!1:t?.has(d)??!1;if(Iv.has(i.modelID))return!n;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=o.get(a);if(!m?.releaseDate)return _t(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return _t(i)}catch{return _t(i)}return!1}if(c==="show"||r.has(a))return!0;let p=o.get(a);if(!p?.releaseDate)return _t(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return _t(i)}catch{return _t(i)}return!1}}function Mv(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 xy(e,t){if(!e||un.has(e.providerID)||se(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>se(i.modelID)>0))return e;let r=i=>se(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,s=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??ln(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!s||s===e.modelID?e:{...e,modelID:s}}function Ov(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??(e?.freeTier?void 0:e?.platformDefault);return n?Ts(n):void 0}function jv(e){let{models:t,providers:n}=e,r=c=>Us(t,c),o=c=>c.find(p=>!!p&&r(p)),s=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=c[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of Er(Object.keys(m.models).map(w=>({id:w})))){let w={providerID:m.id,modelID:h.id};if(r(w))return w}}}})(),i=o(e.picks??[]),a=i??o([e.serverDefault,e.globalDefault,e.agentModel,s]);return{model:xy(a,t),explicit:i,fallback:s}}export{KS as ABORT_REASONS,GL as ABORT_REASONS_NOT_YET_EMITTED,ei as ACCOUNTS_LIST_UNAVAILABLE_CODE,Ar as ACTIVE_INSTANCE_COOKIE,Zs as ANALYTICS_UNAVAILABLE_CODE,cw as ATTACHMENT_PART_REF_PREFIX,b as ApiError,te as AuthError,De as BillingError,Pw as CONNECTION_FAULT_GRACE_MS,ow as CONNECTOR_POLL_FIRST_DELAY_MS,sw as CONNECTOR_POLL_INTERVAL_MS,iw as CONNECTOR_POLL_WINDOW_MS,bP as CONTEXT_TOOLS,kf as COST_MARKUP,_P as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,vm as DEFAULT_TRANSCRIPT_OPTIONS,ew as DESTRUCTIVE_PHASES,Lr as FEATURE_DISABLED_CODE,vA as FEATURE_FLAG_KEYS,Qs as FEATURE_NOT_SUPPORTED_CODE,Be as FILE_VERBS,qt as FileExistsError,Et as HeadlessAuthError,Rr as HostBoundaryError,Oy as IMPERSONATION_HEADER,ws as INBOX_OBSERVATION_MAX_MS,IK as INITIAL_SETTLED_CONNECTION,qS as INSTANCE_SCOPED_ROUTES,eO as KORTIX_TRANSCRIPT_SCHEMA,ah as MAX_PROMPT_ATTACHMENTS_BYTES,eo as MAX_PROMPT_ATTACHMENT_BYTES,Nc as MAX_PROMPT_ATTACHMENT_FILES,SL as MEMORY_VERBS,Xs as MODEL_NOT_SERVABLE_CODE,Gh as NO_GROUP_ACTIVITY_TOOLS,vs as OPTIMISTIC_ABORT_MAX_MS,XK as OPTIMISTIC_COMPACTION_MAX_MS,xs as OPTIMISTIC_RECEIPT_MAX_MS,QN as PERSISTED_QUERY_CACHE_VERSION,px as PLUMBING_TOOLS,yK as PREVIEW_PROBE_TIMEOUT_MS,cR as PROJECT_SESSION_NAME_LOOKUP_LIMIT,aR as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,Ph as PROJECT_SESSION_PAGE_MAX_LIMIT,Js as PROVISION_IN_FLIGHT_CODE,uo as PublicSessionShareError,nF as RUNTIME_NOT_READY_MARKERS,rO as RUNTIME_PERMISSION_CAPABILITIES,nO as RUNTIME_PERMISSION_REPLIES,Ye as RequestTooLargeError,Ft as RuntimeNotReadyError,Yo as SANDBOX_FS_ROOTS,Ie as SANDBOX_PORTS,Rw as SERVER_COMPACTION_REVALIDATE_MS,Ss as SERVER_OBSERVATION_MAX_MS,uq as SESSION_LIST_STATUS,gq as SESSION_NOTICE,Bh as STANDALONE_TOOLS,cn as STREAM_OBSERVATION_MAX_MS,kr as SandboxNotReadyError,st as SessionNotReadyError,oo as SessionStartError,NK as TURN_END_LEDGER_LAG_MS,yb as TURN_ERROR_CODES,oq as WAKE_ESCALATION_COOLDOWN_MS,rq as WAKE_MAX_RESTARTS,nq as WAKE_NO_PROGRESS_MS,Ko as WIRE_ID_BACKDATE_MS,Ne as WIRE_ID_CLOCK_TOLERANCE,Ce as WIRE_ID_TIME_MASK,$t as WIRE_ID_TIME_SCALE,pb as WIRE_MESSAGE_ID,$v as __getConfigResolver,Dv as __setConfigResolver,BL as abortErrorReason,vi as acceptAccountInvite,DF as acceptInvite,Fp as actReviewItem,Za as activateConnection,nc as addComputerToProject,dp as addGroupMembers,Sd as addMarketplaceSource,iq as advanceWakeEscalation,ox as allDescendantIds,zf as appendPreviewToken,na as approveProjectAccessRequest,kO as approveTask,kn as archiveProject,jO as assignTicket,da as attachGroupToProject,Do as authMfa,Mo as authUser,D as authenticatedFetch,mK as authorizePreviewUrl,l as backendApi,pI as bindSlackIdentity,dI as bindTeamsIdentity,va as brokerProjectSecretRequest,ZN as browserKeyValueStorage,BS as buildInstancePath,xK as buildPresentationTemplateImageUrl,PK as buildPresentationTemplatePdfUrl,Vf as buildPreviewAuthEndpoint,DN as buildPublicTemplateUrl,_w as buildRuntimePresentationConversionUrl,jc as buildSandboxTemplate,yx as buildScrapeFailureResults,dD as buildStaticFileHealthPreviewUrl,pD as buildStaticFileLocalUrl,uD as buildStaticFilePreviewUrl,v_ as buildStaticFileServicePath,Wq as buildTunnelEventStreamUrl,hD as buildWebProxyUrl,Np as bulkActReviewItems,XI as bulkDeletePolicies,JI as bulkImportPolicies,B0 as burstSummary,W0 as burstSummaryLabel,Ba as callConnector,xC as cancelAccountDeletion,Pi as cancelAccountInvite,wF as cancelSandbox,ZF as cancelSandboxUpdate,hu as cancelScheduledChange,mu as cancelSubscription,hN as checkAccessEmail,R0 as childMapByParent,iN as claimComputer,$_ as claimNext,JR as claimPerSeatBilling,bl as claimWarmProjectSession,Jm as classifyPart,hw as classifyPreviewProbeStatus,_b as classifyPtyClose,ex as classifyTurn,j0 as cleanErrorMessage,J0 as cleanResultSnippet,gL as cleanWorkerOutput,ni as clearImpersonationSession,ev as clearKortixAppViewerCache,Xl as clearModelDefault,tR as clearSessionFresh,ol as closeChangeRequest,cj as closeMilestone,w0 as collectTurnParts,$O as commentTicket,al as commitSessionChanges,ZK as compactionExpiryAtMs,V0 as compactionTurnInfo,x0 as compareMessagesForDisplay,U_ as completeInFlight,Eu as completeSlackInstall,Mu as completeTeamsInstall,ay as composerSelectableAgents,Af as computeStatusFromPart,xu as configureAutoTopup,Dr as configureKortix,du as confirmCheckoutSession,Fu as connectEmail,Iu as connectSlack,RK as connectionFromHealth,kK as connectionIsFaulted,dk as connectionSharedWithEveryone,sh as connectorConnect,ih as connectorFinalize,KN as connectorHeadline,dU as contextLabelForTool,U$ as contextToolSummary,L$ as contextToolTrigger,UC as convertPresentationToGoogleSlides,SK as convertRuntimePresentation,ir as copyFile,wu as costExportUrl,qK as countLiveInboxPrompts,GC as countReviewItemsBySegment,li as createAccount,pd as createAccountAuditWebhook,Oa as createAccountSecretResource,ed as createAccountToken,Ad as createApp,Md as createAppAccessSession,jd as createAppDeployment,gU as createArtifactKind,Mp as createAssignment,QT as createAuditWebhook,FF as createBackup,pu as createCheckoutSession,yc as createConnector,LN as createConnectorLinkInfoCache,sr as createFile,rp as createGatewayKey,cp as createGroup,Kw as createHttpSessionSyncController,rN as createInstance,M_ as createKortix,Rg as createKortixPty,Uo as createKortixSession,hE as createMarketplaceInstallSession,ij as createMilestone,Ev as createModelVisibility,Rp as createOAuthClient,XR as createPerSeatCheckout,JN as createPersistedQueryCache,zI as createPolicy,gu as createPortalSession,Di as createProject,HO as createProjectAgent,sd as createProjectCliToken,$i as createProjectRepo,ya as createProjectResourceGrant,et as createProjectSession,Fl as createProjectTrigger,fm as createPromptAttachmentController,_p as createRole,Hq as createSSEStream,yF as createSandbox,Bp as createSandboxShare,Ec as createSandboxTemplate,Fq as createSavedCopyStore,cT as createScimToken,qT as createServiceAccountApi,$n as createSessionPrompt,fl as createSessionPublicShare,j_ as createSessionQueue,Yp as createSessionReminder,RT as createSsoGroupMapping,wO as createTask,EO as createTicket,Vq as createTunnelEventStream,Kq as currentSavedCopyStore,Ai as declineAccountInvite,$F as declineInvite,SC as deleteAccountImmediately,Da as deleteAccountSecretResource,Id as deleteApp,Nd as deleteAppDeployment,JT as deleteAuditWebhook,KF as deleteBackup,bc as deleteConnector,fj as deleteCredential,Ag as deleteEnv,dt as deleteFile,tp as deleteGatewayBudget,Ji as deleteGitHubInstallation,up as deleteGroup,oN as deleteInstance,tj as deleteKortixProject,uj as deleteMilestone,Cp as deleteOAuthClient,Ca as deletePersonalProjectSecret,QI as deletePolicy,zO as deleteProjectAgent,ka as deleteProjectProviderOAuth,ha as deleteProjectResourceGrant,Ia as deleteProjectSecret,Tl as deleteProjectSession,Kl as deleteProjectTrigger,kt as deletePromptAttachment,Sp as deleteRole,Oc as deleteSandboxTemplate,BT as deleteServiceAccountApi,vl as deleteSessionPrompt,Xp as deleteSessionReminder,IT as deleteSsoGroupMapping,AT as deleteSsoProvider,RO as deleteTask,UO as deleteTicket,wi as describeAccountInvite,Ga as describeConnectorTool,ma as detachGroupFromProject,P_ as detectLocalhostUrls,yq as directSubsessions,GT as disableServiceAccountApi,Nu as disconnectEmail,zN as disconnectGitHubApp,ju as disconnectSlack,yk as discoverConnectionOAuth2,hk as discoverConnectionOAuth2Resource,hc as discoverConnectorAuth,PF as discoverLocalSandbox,ON as downloadAccountAudit,Tj as dropClientForUrl,Mj as dropPublicClientForUrl,K_ as editQueued,Al as editSessionPrompt,D_ as enqueue,BO as ensurePmSession,yw as ensurePreviewSessionCookie,gk as ensureProjectConnectorConnection,ZS as ensureSandbox,hl as ensureWarmProjectSession,hb as env,To as exchangeCode,ld as exportAccountAudit,ge as extractGatewayErrorDetails,on as extractInstanceRoute,uS as extractSkillBaseDir,UL as extractSkillContent,aS as extractSkillFiles,fL as extractWorkerPreview,L_ as failInFlight,FU as fallbackBusyRowAfterTurnId,ds as familyForTool,Bs as featureDisabledKey,Yd as featureFlags,YR as fetchAccountStateWithToken,_A as fetchAccountsWithToken,rK as fetchAttachmentPart,aI as fetchCostExportCsv,sy as fetchKortixAppViewer,Fc as fetchProjectArchive,MA as fetchProjectsForAccountWithToken,Vd as fetchSessionAttachment,_L as filePhase,bL as fileVerb,s_ as files,mo as finalizeAppArtifact,vN as finalizeConnectorSetupLink,uR as findActiveTranscriptShare,rr as findFiles,v0 as findLastTextPart,GE as findSessionAttachments,or as findText,Gl as fireProjectTrigger,Cc as fixSandboxWithAgent,Av as flattenModels,xU as flattenThought,Hs as formatBillingErrorForUI,iL as formatCost,rL as formatDuration,D0 as formatJsonFailureOutput,vU as formatMessageDay,AU as formatMessageExact,oF as formatOpenCodeRuntimeError,X0 as formatRawOutput,JS as formatRuntimeError,aL as formatTokens,z_ as formatTranscript,qU as freshSendHint,O_ as generateSessionId,ui as getAccount,di as getAccountBranding,_C as getAccountDeletionStatus,ou as getAccountState,su as getAccountStateMinimal,HS as getActiveInstanceIdFromCookie,CC as getAdminProviderAnalytics,RC as getAdminProviderDistribution,MC as getAdminProviderFallback,wC as getAdminRole,RP as getAgentCardLabel,qR as getAgentConfig,YO as getAgentPersona,QF as getAllVersions,k0 as getAnsweredQuestionParts,kd as getApp,Td as getAppAccess,$d as getAppDeployment,Ud as getAppDeploymentLogs,gE as getApprovalLink,wt as getAuthToken,sk as getAuthTokenWithRetry,Pu as getAutoTopupSettings,QR as getAutoTopupSetupStatus,cu as getBillingCreditBreakdown,uu as getBillingTierConfigurations,au as getBillingTransactionsSummary,lu as getBillingUsageHistory,Zc as getChangeRequest,el as getChangeRequestDiff,tl as getChangeRequestMergePreview,Z$ as getChildSessionError,zm as getChildSessionId,e0 as getChildSessionToolParts,Ke as getClient,xe as getClientForUrl,Sc as getConnectStatus,fk as getConnectionOAuth2Application,Sk as getConnectionOAuth2Status,wk as getConnectionPolicies,In as getConnectorCatalog,gc as getConnectorConfig,pc as getConnectorPolicies,SN as getConnectorSetupLink,iI as getCostSummary,WS as getCurrentInstanceIdFromPathname,zL as getCurrentInstanceIdFromWindow,Wg as getCurrentProject,tu as getDefaultAccountState,r0 as getDiagnostics,kP as getDirectory,Zr as getDiscoverConnector,Tk as getDiscoverIntegration,Uu as getEmailInstallation,Lu as getEmailMode,iC as getEnterpriseDemo,nr as getFileStatus,Hm as getFileWithDir,AP as getFilename,tw as getFullChangelog,Qu as getGatewayBreakdown,Zu as getGatewayBudgets,Ju as getGatewayErrors,np as getGatewayKeys,Vu as getGatewayLog,zu as getGatewayOverview,qu as getGatewayRoutingPolicy,Yu as getGatewaySeries,Xu as getGatewaySessions,BN as getGitHubAppStatus,Bi as getGitHubInstallation,$C as getGoogleAuthUrl,ap as getGroup,X$ as getHiddenToolParts,$y as getImpersonationSession,jF as getInvite,nN as getJustavpsServerTypes,JO as getKortixProject,ZO as getKortixProjectBySession,Cg as getKortixPtyWebSocketUrl,YF as getLatestSandboxVersion,TN as getMaintenanceConfig,Zi as getManagedGitBackend,IA as getManagedGitStatus,_d as getMarketplaceCatalogItem,Pd as getMarketplaceCatalogItemFile,gT as getMfaRequired,oj as getMilestone,Yl as getModelDefaults,kp as getOAuthClient,PN as getOAuthConsentRequest,eF as getOpenCodeConfigInvalidError,z$ as getPartText,$T as getPatPolicy,o0 as getPermissionForTool,xn as getProject,QO as getProjectActivity,zc as getProjectCommit,Yc as getProjectCommitDiff,Sn as getProjectDetail,Qc as getProjectFileHistory,ji as getProjectGitToken,wn as getProjectLlmCatalog,kA as getProjectLlmCatalogProviders,Bn as getProjectModelAccess,vn as getProjectModelPicker,Tn as getProjectSandboxHealth,TA as getProjectSandboxProviderTransition,Dn as getProjectSession,Cl as getProjectSessionConfigState,Ol as getProjectSessionScope,bu as getProrationPreview,mF as getProviders,gD as getProxyBaseUrl,Ej as getPublicClientForUrl,fN as getPublicMarketplaceItem,yN as getPublicMarketplaceItemFile,XC as getPublicSessionShare,JC as getPublicSessionShareMessages,RN as getPublicShareByToken,$N as getPublicTemplate,s0 as getQuestionForTool,wI as getReferralCode,kI as getReferralStats,cL as getRetryInfo,lL as getRetryMessage,Up as getReviewItem,hp as getRolePermissions,bp as getRoleUsage,hs as getRuntimeConfigInvalidError,BF as getSSHConnection,fF as getSandbox,hF as getSandboxById,cF as getSandboxPortUrl,aN as getSandboxProvisionStatus,cN as getSandboxProvisionStreamUrl,zF as getSandboxUpdateStatus,Ff as getSandboxUrl,AN as getSecretSetupLink,Qo as getServerHealth,bj as getServiceLogs,_l as getSessionAudit,sL as getSessionCost,qn as getSessionCostRecord,Jg as getSessionHealth,Ul as getSessionMessageAuthors,pR as getSessionOpenBundle,yT as getSessionOversight,dl as getSessionParticipants,MT as getSessionPolicy,gl as getSessionPreviewCandidates,Fa as getSessionProviderSecretPool,Pl as getSessionTranscript,xl as getSessionTranscriptSync,Sl as getSessionTurn,HU as getShellModePart,Du as getSlackChannelFile,Ru as getSlackInstallation,Ou as getSlackManifest,Tu as getSlackMode,xT as getSsoProvider,A_ as getStaticFileHealthPath,Yr as getSupabaseAccessToken,St as getSupabaseAccessTokenWithRetry,PO as getTask,SO as getTaskStatus,PE as getTemplate,TO as getTicket,t0 as getToolInfo,os as getToolPrimaryArg,Y_ as getTranscriptFilename,oL as getTurnCost,ZU as getTurnError,tL as getTurnErrorDetails,eL as getTurnErrorRawText,nL as getTurnStatus,Su as getUsageRollup,EN as getUserRolesWithToken,Xc as getVersionDiff,XU as getWorkingState,$a as grantAccountSecretResource,CF as grantSandboxProjectAccess,BR as grantSecretToAgent,S0 as groupMessagesIntoTurns,OU as groupShowSegments,hf as groupSteps,uL as hasDiffs,lD as hasLocalhostUrls,w_ as hasPreviewTarget,C0 as hasRetryingAssistantTurn,Ib as heartbeatGapEvent,Rl as holdSessionPrompts,qp as humanizeReviewActionPath,mr as humanizeSearchQuery,Qm as humanizeToolName,ri as impersonationHeaders,wT as importSsoProviderFromMetadata,KK as inboxObservationSupersedes,Zf as initialWakeEscalationState,Oe as inputPath,xE as installTemplate,Qr as invalidateTokenCache,bi as inviteAccountMember,aa as inviteProjectMember,Mi as inviteRepoCollaborator,vr as isAbortError,Ny as isAdminBypassEnabled,G$ as isAgentPart,h_ as isAppRouteUrl,Y$ as isAttachment,lw as isAttachmentPartRef,Ws as isBillingError,B$ as isCompactionPart,$r as isConfigured,$$ as isContextTool,VF as isDestructivePhase,Zw as isEmptyConversation,yo as isEmptyShowPart,O0 as isErrorOutput,PD as isExternalUrl,Gs as isFeatureDisabledError,Vm as isFilePart,jy as isImpersonationSessionLive,HL as isInstanceDetailPath,GS as isInstanceScopedAppPath,yD as isInternalLocalhostUrl,Bd as isInvisibleActivityPart,BA as isInviteSent,QU as isLastUserMessage,Ew as isLegacyMigratedSession,AA as isManagedGithubProject,Gd as isNoGroupActivityTool,Us as isOfferedModel,tF as isOpenCodeConfigInvalidError,ny as isPaintableSavedCopy,H$ as isPatchPart,XN as isPersistableQueryKey,fD as isPreviewUrl,k_ as isProxiableLocalhostUrl,OE as isQuestionTool,ve as isReasoningPart,sx as isRetryableTurnError,VS as isRuntimeConfigInvalidError,QS as isRuntimeNotReadyResponse,Xg as isRuntimeReady,rF as isRuntimeStartingError,an as isSandboxNotReadyError,xo as isSelectableAgent,Hg as isServerReachable,qE as isSessionAttachmentRef,cl as isSessionFresh,vR as isSessionStartError,ME as isShellActivityTool,sS as isShellMode,mL as isShortOutput,TE as isShowContentUnavailable,Hn as isShowPayloadEmpty,W$ as isSnapshotPart,Wd as isStandaloneActivityTool,V$ as isStepPart,Ir as isSubdomainPreviewUrl,we as isTextPart,X as isToolPart,J$ as isToolPartHidden,tO as isTurnErrorCode,Fg as isUnderSandboxRoot,_D as isWebProxyUrl,gb as isWireIdAheadOf,nv as kortixAppViewerToken,wb as kortixPty,Ii as leaveAccount,Qi as linkGitHubInstallation,qi as linkRepository,ad as listAccountAudit,ud as listAccountAuditWebhooks,_i as listAccountInvites,hi as listAccountMembers,qI as listAccountResourceGrants,Ma as listAccountSecretResources,jT as listAccountSessions,Zp as listAccountTokens,ci as listAccounts,nT as listActions,IC as listAdminSandboxes,fp as listAgentIdentities,za as listAllConnections,Cd as listAppAgents,Dd as listAppDeployments,vd as listApps,Ep as listAssignments,ZT as listAuditEvents,YT as listAuditWebhooks,LF as listBackups,iu as listBillingTransactions,Jc as listChangeRequests,fI as listChannelBindings,LO as listColumns,Rk as listConnectSections,kk as listConnectToolkits,Va as listConnections,Wa as listConnectorAccounts,Xr as listConnectorTools,ic as listConnectors,sI as listCostByProject,dj as listCredentialEvents,pj as listCredentials,Jr as listDiscoverConnectors,Ik as listDiscoverIntegrations,xc as listDiscoverSections,wg as listEnv,bd as listFeaturedMarketplaces,NO as listFields,Bt as listFiles,Hu as listGatewayLogs,Wi as listGitHubInstallations,Vi as listGitHubRepositories,zi as listGitHubRepositoryBranches,pp as listGroupMembers,DI as listGroupProjectGrants,ip as listGroups,ej as listKortixProjectSessions,XO as listKortixProjects,kg as listKortixPty,Hi as listLinkableGitHubInstallations,ea as listManagedGitRepositories,yd as listMarketplaceCatalogItems,xd as listMarketplaceSources,hd as listMarketplaces,$I as listMemberGroups,UI as listMemberProjectAccess,sj as listMilestoneEvents,rj as listMilestones,Si as listMyAccountInvites,Ap as listOAuthClients,nd as listOAuthGrants,ba as listPendingApprovals,ca as listPendingProjectInvites,jp as listPermissions,_c as listPipedreamApps,Pc as listPipedreamSections,VI as listPolicies,oa as listProjectAccess,ta as listProjectAccessRequests,yp as listProjectAgentIdentities,WO as listProjectAgents,cd as listProjectAudit,Hc as listProjectBranches,od as listProjectCliTokens,Vc as listProjectCommits,$c as listProjectFiles,pa as listProjectGroupGrants,Ac as listProjectPolicies,Aa as listProjectProviderOAuth,Jp as listProjectReminders,fa as listProjectResourceGrants,Rc as listProjectSandboxTemplates,Dc as listProjectSandboxes,xa as listProjectSecrets,Ze as listProjectSessions,ul as listProjectSessionsPage,Ic as listProjectSnapshots,Ll as listProjectTriggers,Je as listProjects,Ei as listProjectsForAccount,gN as listPublicMarketplaceItems,mN as listPublicMarketplaces,RI as listReferrals,$p as listReviewItems,mp as listRoles,TF as listSandboxProjectMembers,Gp as listSandboxShares,_F as listSandboxes,aT as listScimTokens,KT as listServiceAccountsApi,hj as listServiceTemplates,yj as listServices,Ak as listSessionConnectRequests,vu as listSessionCosts,wl as listSessionPrompts,Na as listSessionProviderSecretPools,ml as listSessionPublicShares,zp as listSessionReminders,_a as listSessionsNeedingInput,kT as listSsoGroupMappings,xO as listTaskEvents,_O as listTasks,qO as listTemplates,CO as listTicketEvents,IO as listTickets,Nw as loadHttpSessionHistory,sf as looksLikeError,sU as looksLikeHtml,Q0 as looksLikeJsonPayload,WC as mapApiReviewItem,sN as markInstanceError,jn as markSessionFresh,_g as maxWireIdClock,wL as memoryRelPath,PU as mergeBurstSteps,rl as mergeChangeRequest,wU as messageCreatedAt,Yx as messageTime,EC as migrateAdminSandboxProvider,qo as mintWireMessageId,xg as mintWireMessageIdAbove,zt as mkdir,Mv as modelInDefaultView,iv as modelRefToKey,ff as narrateFailedStep,mf as narrateStep,xr as narrationToolName,Tb as narrowChatEvent,mb as newestWireIdClock,NN as nextConnectorPollDelay,ae as normalizeActivityToolName,XL as normalizeAppPathname,xD as normalizeExternalInput,H as normalizeName,Ym as normalizeToolName,jw as notifyHostSignal,nl as openChangeRequest,Ho as openEventStream,jN as openStressTestStream,mn as parseBillingError,Z0 as parseEmbeddedFailure,zE as parseFlagOverride,ux as parseJsonFailure,ur as parseLocalhostUrl,vL as parseMemoryView,ZL as parseOpenCodeErrorPayload,TL as parsePresentationOutput,Qg as parseProxyHop,EL as parseQuestionAnswersFromOutput,jL as parseReadOutput,Lf as parseRuntimeErrorPayload,fx as parseScrapeInputUrls,hx as parseScrapeOutput,am as parseSubdomainUrl,yL as parseTaskRows,bD as parseWebProxyUrl,uf as parseWebSearchOutput,af as partOutcome,nj as patchKortixProject,RL as patchVerb,wv as pickerProviderList,fc as pipedreamConnect,oc as pipedreamConnectConnection,vc as pipedreamFinalize,sc as pipedreamFinalizeConnection,R as platformConfig,xk as pollConnectionOAuth2DeviceAuthorization,Vr as pollProjectProviderOAuth,Wu as previewGatewayRoute,mT as previewMfaRequired,gI as previewSlackIdentity,mI as previewTeamsIdentity,wp as probeEffectivePermission,vp as probeEffectivePermissions,hK as probePreviewPort,JK as projectCompacting,sv as projectConfigAgentsToOpenCodeAgents,iy as projectConfigAgentsToRuntimeAgents,AK as projectSessionConnection,hq as projectSessionForRuntimeId,wR as projectSessionStartSeed,BK as projectWorking,Ui as provisionProject,RA as provisionProjectStream,OA as provisionProjectWithToken,sm as proxyLocalhostUrl,mD as proxyUrlToInternal,_u as purchaseCredits,mk as putConnectionOAuth2Application,Tm as rawErrorText,vF as reactivateSandbox,fu as reactivateSubscription,Ht as readBlob,Wt as readFile,Lc as readProjectFile,Hx as reasoningIsRunning,Tc as rebuildProjectSnapshot,Ya as reconcileConnection,Qa as reconcileMemberConnection,Pj as reconcileServices,_N as recordPlatformLogout,us as recoverLinkResults,vI as refreshReferralCode,Mt as refreshSession,go as registerAppArtifact,bk as registerConnectionOAuth2Client,xj as registerService,ra as rejectProjectAccessRequest,n0 as relativizePath,El as reloadProjectSessionConfig,Ml as reloadProjectSessionConfigStream,gd as removeAccountAuditWebhook,fi as removeAccountBrandingAsset,ki as removeAccountMember,gp as removeGroupMember,Tg as removeKortixPty,wd as removeMarketplaceSource,N_ as removeQueued,tc as renameConnection,cr as renameFile,bF as renameSandbox,sl as reopenChangeRequest,lj as reopenMilestone,q_ as reorderQueued,FO as replaceColumns,KO as replaceFields,Gi as replaceProjectRepository,GO as replaceTemplates,PC as requestAccountDeletion,il as requestChangesOnChangeRequest,GA as requestProjectAccess,fd as requestProjectConnector,md as requestProjectSecret,xi as resendAccountInvite,ua as resendPendingProjectInvite,yi as resetAccountBranding,Cj as resetClient,Bu as resetGatewayRoutingPolicy,Co as resetPassword,Oj as resetPublicClient,JF as resetSandboxUpdateStatus,Pa as resolveApproval,ov as resolveComposerAgent,jv as resolveComposerModel,FN as resolveConnectorStart,Ov as resolveModelDefault,lR as resolvePublicShareUrl,iU as resolveScrapeResults,GU as resolveWorkingTurn,zR as resolvedPlan,Un as restartProjectSession,xF as restartSandbox,NF as restoreBackup,F_ as retryFailed,kl as retrySessionPrompt,mj as revealCredential,qC as reviewItemTarget,Ch as reviewSegmentForStatus,BC as reviewVerdictForStatus,Ua as revokeAccountSecretResourceGrant,DT as revokeAccountSession,td as revokeAccountToken,Op as revokeAssignment,Ja as revokeConnection,op as revokeGatewayKey,rd as revokeOAuthGrant,la as revokePendingProjectInvite,ia as revokeProjectAccess,id as revokeProjectCliToken,EF as revokeSandboxProjectAccess,Wp as revokeSandboxShare,lT as revokeScimToken,yl as revokeSessionPublicShare,qe as rewriteLocalhostUrl,Kd as rollbackApp,Mw as rootRuntimeSession,ja as rotateAccountSecretResource,Tp as rotateOAuthClientSecret,sp as runGatewayPlayground,zA as runProjectProviderOAuthFlow,ks as runtimeSessionsOf,a_ as runtimeSupports,Sb as sanitizePtyChunk,Yi as saveGitHubInstallation,Jw as savedCopyEmptyRoot,yu as scheduleDowngrade,qa as searchConnectorTools,Uc as searchProjectFiles,TU as segmentTurn,XE as selectableProjectAgents,ko as sendMagicLink,II as sendReferralEmails,eq as serverCompactionRevalidateAtMs,_j as serviceAction,dq as sessionConnectionLabel,pq as sessionListStatus,$l as sessionModelPin,iR as sessionParentId,AR as sessionStartKey,La as setAccountSecretResourceAccess,YL as setActiveInstanceCookie,Fy as setAdminBypass,TC as setAdminProviderDistribution,OC as setAdminProviderFallback,Zl as setAgentScope,ok as setBootstrapAuthToken,rk as setCachedAuthToken,vk as setConnectionPolicies,lc as setConnectorAuthorizationStrategy,wc as setConnectorCredential,cc as setConnectorCredentialMode,mc as setConnectorName,dc as setConnectorPolicies,Ck as setConnectorSecretBinding,uc as setConnectorSensitive,ec as setDefaultConnection,aC as setEnterpriseDemo,vg as setEnv,ep as setGatewayBudget,Gu as setGatewayRoutingPolicy,HN as setGitHubAppFromExisting,VN as setGitHubAppPat,Hv as setImpersonationSession,CN as setMaintenanceConfig,rT as setMemberSuperAdmin,fT as setMfaRequired,Ql as setModelDefault,Ta as setPersonalProjectSecret,Wn as setProjectModelAccess,MR as setProjectModelEnablement,Ki as setProjectOnboardingComplete,EA as setProjectOnboardingProfile,kc as setProjectPolicies,wa as setProjectSecretStrategy,Dl as setProjectSessionModel,jl as setProjectSessionScope,pl as setProjectSessionSharing,ql as setProjectTriggersActivation,Nq as setSavedCopyStore,hT as setSessionOversight,Ka as setSessionProviderSecretPool,TK as settleSessionConnection,GF as setupSSH,rc as shareConnection,jE as shellActivityGroupLabel,Df as shellExitCode,Ly as shouldAttachImpersonation,JU as shouldHideResponsePart,xP as shouldShowToolPart,LU as shouldSuppressWorkingTurnBusy,jU as showGroupItems,vf as showTurnBusyIndicator,Ao as signInWithPassword,Io as signInWithProvider,jo as signInWithSso,$o as signOut,vo as signUp,FL as skillDocumentPath,LL as skillInputDir,I0 as sortSessions,Q$ as splitUserParts,Ld as startApp,_k as startConnectionOAuth2Authorization,Pk as startConnectionOAuth2DeviceAuthorization,wN as startConnectorSetupLink,WN as startGitHubAppManifest,Hr as startProjectProviderOAuth,Ue as startProjectSession,IN as startSessionWithToken,AO as startTask,cf as stepLabel,Fd as stopApp,Ln as stopProjectSession,SF as stopSandbox,Xi as storeGitHubUserToken,i0 as stripAnsi,VL as stripInstancePrefix,de as stripTrailingSlashes,bN as submitAccessRequest,MN as submitDemoRequest,xN as submitOAuthConsent,Lp as submitReviewItem,kN as submitSecretSetupLink,Vv as subscribeToImpersonation,dA as supabaseClient,ac as syncConnectors,ZR as syncSubscription,jj as systemReload,pt as toDaemonPath,QL as toInstanceAwarePath,R_ as toInternalUrl,Gt as toSandboxAbsolutePath,m0 as toToolView,Ng as toWorkspaceRelative,ss as toolInfo,re as toolKind,$S as toolViewModel,XF as triggerSandboxUpdate,bb as triggersRequest,Aw as turnEndCause,YK as turnEndNotice,A0 as turnHasSteps,NU as turnIsConfirmedActive,mq as turnRetryLabel,DO as unassignTicket,ce as unwrapError,dd as updateAccountAuditWebhook,gi as updateAccountBranding,Ri as updateAccountMemberRole,pi as updateAccountName,GR as updateAgentConfig,Rd as updateApp,Ed as updateAppAccess,XT as updateAuditWebhook,yI as updateChannelBinding,Xa as updateConnectionCredential,Ku as updateEmailPolicy,Fi as updateExperimentalFeature,Li as updateFeatureFlag,lp as updateGroup,Ig as updateKortixPty,aj as updateMilestone,Ip as updateOAuthClient,Eo as updatePassword,UT as updatePatPolicy,YI as updatePolicy,An as updateProject,sa as updateProjectAccess,VO as updateProjectAgent,eu as updateProjectDefaultAgent,ga as updateProjectGroupGrant,Ni as updateProjectSandboxProvider,Il as updateProjectSession,Nl as updateProjectTrigger,Pp as updateRole,xp as updateRolePermissions,Mc as updateSandboxTemplate,OT as updateSessionPolicy,Qp as updateSessionReminder,vO as updateTask,CA as updateTemplateWarmPool,MO as updateTicket,OO as updateTicketStatus,Oo as updateUserMetadata,mi as uploadAccountBrandingAsset,Od as uploadAppArtifactArchive,Ha as uploadConnectorAttachment,Vt as uploadFile,On as uploadPromptAttachment,Hd as uploadSessionAttachment,$u as uploadSlackChannelFile,Kt as uploadTimeoutMsForBytes,gj as upsertCredential,Ra as upsertProjectGitCredential,Sa as upsertProjectSecret,ST as upsertSsoProvider,Oi as validateProjectManifest,AI as validateReferralCode,Ti as validateToken,PI as verifyGatewayProvider,Ro as verifyOtp,vT as verifySsoDomain,cq as wakeEscalationAttemptSummary,aq as wakeEscalationNote,sq as wakeProgressFingerprint,at as wireIdClock,Ut as wireIdClockAt,ct as wireIdClockDelta,WK as workingExpiryAtMs,KU as workingTurnDrawsBusyRow,DE as writeActivityGroupLabel,ar as writeFile,ps as wsDomain,oU as wsFavicon,rU as wsRootDomain};
98
+ `:"")+E.slice(5))}}catch(j){if(g||j instanceof DOMException&&j.name==="AbortError")return;a?.(j instanceof Error?j:new Error(String(j)))}}function h(){g=!0,d?.abort(),d=null,p.clear()}function w(O,j){let y=p.get(O)??new Set;y.add(j),p.set(O,y)}function L(O,j){p.get(O)?.delete(j)}return{connect:f,close:h,addEventListener:w,removeEventListener:L}}function Qq(e,t){throw F("createTunnelEventStream")}var sy="/_kortix/viewer";var ht=new Map;function tv(){ht.clear()}async function nv(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 iy(e={}){let t=e.path??sy,n=e.fetch??((s,i)=>fetch(s,i)),r=ht.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let o=nv(t,n).then(s=>{let i=s?.expires_at?Date.parse(s.expires_at):Number.NaN,a=Number.isFinite(i)?i-6e4:Date.now()+6e4;return ht.set(t,{session:s,expiresAt:a}),s});return ht.set(t,{session:r?.session??null,expiresAt:0,inflight:o}),o}function rv(e={}){let t=e.path??sy;return Object.assign(async()=>(await iy(e))?.access_token??null,{invalidate:n=>{let r=ht.get(t);r&&!r.inflight&&r.session?.access_token===n&&ht.delete(t)}})}function ay(e){let t=e.agents.map(ov),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function ov(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.enabled===!1}}function cy(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>xo(n?{...r,mode:null}:r))}function sv(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let s=e.selectedAgent?.trim();return s?{selected:s,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=cy(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(s=>s.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let o=e.defaultAgent?.trim();return o&&n.some(s=>s.name===o)?{selected:o,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var iv=ay;function ly(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Ts(e){return{providerID:"kortix",modelID:e}}function av(e,t){let n=e.startsWith("kortix/")?e.slice(7):e;if(!t){let r=n.indexOf("/");if(r>0&&r<n.length-1)return{providerID:n.slice(0,r),modelID:n.slice(r+1)}}return Ts(n)}var Cs=[{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"crof",env:["CROF_API_KEY"]},{id:"v0",env:["V0_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"kimi-for-coding",env:["KIMI_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]}];function Es(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function lv(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function uy(e,t){let n=new Map;for(let r of e){let o=t(r),s=n.get(o);s?s.push(r):n.set(o,[r])}return n}function se(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function py(e){return e.reduce((t,n)=>{let r=Es(n)??0,o=Es(t)??0;return r!==o?r>o?n:t:se(n.id)>se(t.id)?n:t})}function Ms(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,o=new Set;for(let[,s]of uy(e,lv)){let a=[...uy(s,p=>p.family||p.id).values()].map(py),c=a.filter(p=>{let d=Es(p);return d!==null&&Math.abs(n-d)<r});for(let p of c.length>0?c:[py(a)])o.add(p.id)}return o}function Er(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>se(r.id)>0)?n.filter(r=>se(r.id)>0):n}function ln(e){let t;for(let n of Er(e)){if(!t){t=n;continue}let r=(n.released??"").localeCompare(t.released??"");(r>0||r===0&&se(n.id)>se(t.id))&&(t=n)}return t}var uv={"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 dy(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var pv=(()=>{let e=new Map;for(let{id:n,env:r}of Cs)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let o=[...r].sort((s,i)=>s.length-i.length||s.localeCompare(i));t.set(n,r.find(s=>dy(s)===n)??o[0])}return t})();function gy(e){let t=uv[e.id];if(t)return t;let n=e.env??[],r=n.length===1?pv.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[dy(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}function js(e,t){return e.methods.some(n=>n.envVars.length>0&&n.envVars.every(t))}var dv=["low","medium","high"];function my(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:[...dv]}:void 0,o=e.temperature===!0,s=e.limit?.output,i=typeof s=="number"&&s>0?{ceiling:s}:void 0;return{reasoningEffort:r,temperature:o,topP:o,maxOutputTokens:i}}var fy=Cs;var Os={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var Mr=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash",transport:"openrouter",morphModelId:"morph-dsv41flash",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"coreweave/fp8":{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["coreweave/fp8"],...Os,max_price:{prompt:.3,completion:1.2}}},{id:"glm-5.3-flash",name:"GLM 5.3 Flash",upstreamModelId:"z-ai/glm-5.3-flash",transport:"openrouter",morphModelId:"morph-glm53flash",morphPricing:{inputPerMillion:.1,cachedInputPerMillion:.02,outputPerMillion:.35},pricingRef:"openrouter/z-ai/glm-5.3-flash",pricing:{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5},openrouterEndpointPricing:{"decart/fp4":{inputPerMillion:.1275,cachedInputPerMillion:.0255,outputPerMillion:.425},"coreweave/nvfp4":{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5}},tier:"fast",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["low","high","max"]}],openrouterProvider:{only:["decart/fp4","coreweave/nvfp4"],...Os,max_price:{prompt:.15,completion:.5}}},{id:"kimi-k3",name:"Kimi K3 2.8T",upstreamModelId:"moonshotai/kimi-k3",transport:"openrouter",morphModelId:"morph-kimik3",morphPricing:{inputPerMillion:2.5,cachedInputPerMillion:.29,outputPerMillion:14},pricingRef:"openrouter/moonshotai/kimi-k3",pricing:{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5},openrouterEndpointPricing:{"fireworks/us":{inputPerMillion:3.3,cachedInputPerMillion:.33,outputPerMillion:16.5}},tier:"flagship",vision:!0,limit:{context:1e6,output:65536},openrouterProvider:{only:["fireworks/us"],...Os,max_price:{prompt:3.3,completion:16.5}}}],iG=new Map(Mr.map(e=>[e.id,e]));var yy=Mr.map(e=>e.id),hy=(Mr.find(e=>e.tier==="flagship")??Mr[0]).id;var _y=fy.map(e=>({id:e.id,authRequirement:gy(e)})),un=new Set(["kortix"]),Ds=new Set(["kortix"]);function bt(e){let t=Array.isArray(e.all)?e.all:[],n=Array.isArray(e.connected)?e.connected:[];if(t.length>0||n.length>0)return{...e,all:t,connected:n};let r=e.providers,o=Array.isArray(r)?r:[];return o.length===0?{...e,all:[],connected:[]}:{...e,all:o,connected:o.map(s=>s.id)}}function gv(e){if(!e)return!1;let t=bt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return r.length===0?!1:n.some(o=>r.includes(o.id)&&o.models&&Object.keys(o.models).length>0)}function mv(e){let t=bt(e),n=Array.isArray(t.all)?t.all:[],r=Array.isArray(t.connected)?t.connected:[];return{...t,all:n.filter(o=>!Ds.has(o.id)),connected:r.filter(o=>!Ds.has(o))}}function fv(e,t,n){let r=bt(e),o=Array.isArray(r.all)?r.all:[],s=new Set(o.map(a=>a.id)),i=new Set(Array.isArray(r.connected)?r.connected:[]);for(let a of n)s.has(a.id)&&js(a.authRequirement,c=>t.has(c))&&i.add(a.id);return s.has("codex")&&(t.has("CODEX_AUTH_JSON")||t.has("OPENCODE_AUTH_JSON"))&&i.add("codex"),{...r,connected:[...i]}}var yv=new Map(["anthropic","openai","google","x-ai","xai","deepseek","mistral","groq","perplexity","openrouter"].map((e,t)=>[e,t]));function hv(e){let t=e.reasoning_options??[],n=t.find(r=>r.type==="effort");return n?(n.values??[]).flatMap(r=>r===null?["none"]:typeof r=="string"?[r]:[]):t.some(r=>r.type==="budget_tokens")?["high","max"]:[]}var $s="opencode";function bv(e){return e.cost?.input===0&&e.cost?.output===0}function by(e){return e===$s?Number.MAX_SAFE_INTEGER:yv.get(e)??Number.MAX_SAFE_INTEGER-1}function _v(e,t){let n=xv(t),r={},o=(e.providers??[]).map(s=>{let i=(s.models??[]).filter(a=>a.status!=="deprecated");return s.id===$s&&!n.has($s)?{...s,models:i.filter(bv),keyless:!0}:{...s,models:i,keyless:!1}}).filter(s=>(s.keyless||n.has(s.id))&&!Ds.has(s.id)&&(s.models?.length??0)>0).sort((s,i)=>by(s.id)-by(i.id)).map(s=>{let i=[...s.models].sort((c,p)=>(p.released??"").localeCompare(c.released??"")||se(p.id)-se(c.id)),a=ln(i)?.id??i[0]?.id;return a&&(r[s.id]=a),{id:s.id,name:s.name,source:s.keyless?"api":"env",models:Object.fromEntries(i.map(c=>{let p=hv(c);return[c.id,{id:c.id,name:c.name,...c.released?{release_date:c.released}:{},...c.family?{family:c.family}:{},...c.reasoning!==void 0?{reasoning:c.reasoning}:{},...c.reasoning_options?{reasoning_options:c.reasoning_options}:{},...c.tool_call!==void 0?{tool_call:c.tool_call}:{},...c.attachment!==void 0?{attachment:c.attachment}:{},...c.modalities?{modalities:c.modalities}:{},...c.limit?{limit:c.limit}:{},...c.cost?{cost:c.cost}:{},...c.description?{description:c.description}:{},...c.open_weights!==void 0?{open_weights:c.open_weights}:{},...c.last_updated?{last_updated:c.last_updated}:{},...p.length>0?{variants:Object.fromEntries(p.map(d=>[d,{}]))}:{}}]}))}});return{all:o,connected:o.map(s=>s.id),default:r}}function Pv(e,t){if(!e)return t;if(!t)return e;let n=bt(e),r=bt(t),o=new Map;for(let d of Array.isArray(r.all)?r.all:[])o.set(d.id,d);let s=[],i=new Set;for(let d of Array.isArray(n.all)?n.all:[])s.push(o.get(d.id)??d),i.add(d.id);for(let d of Array.isArray(r.all)?r.all:[])i.has(d.id)||(s.push(d),i.add(d.id));let a=[],c=new Set;for(let d of[...Array.isArray(n.connected)?n.connected:[],...Array.isArray(r.connected)?r.connected:[]])c.has(d)||(a.push(d),c.add(d));let p={...r.default??{}};for(let[d,g]of Object.entries(n.default??{})){let m=o.get(d);(!m||m.models&&g in m.models)&&(p[d]=g)}return{...r,all:s,connected:a,default:p}}function xv(e){let t=new Set;for(let n of _y)js(n.authRequirement,r=>e.has(r))&&t.add(n.id);return(e.has("CODEX_AUTH_JSON")||e.has("OPENCODE_AUTH_JSON"))&&t.add("codex"),t}function Sv(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,o])=>{if(o.variants&&Object.keys(o.variants).length>0)return[r,o];let s=my({id:r,name:o.name,reasoning:o.reasoning,reasoning_options:o.reasoning_options}).reasoningEffort?.values;return s?.length?[r,{...o,variants:Object.fromEntries(s.map(i=>[i,{}]))}]:[r,o]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function wv(e,t){return mv(fv(bt(e),t,_y))}function vv(e){if(e.gatewayEnabled)return e.modelPicker?Sv(e.modelPicker):void 0;let t=e.secretNames??new Set,n=e.runtimeProviders?wv(e.runtimeProviders,t):void 0;return Pv(e.llmCatalogProviders?_v(e.llmCatalogProviders,t):void 0,gv(n)?n:void 0)}function Av(e){return"capabilities"in e&&e.capabilities!=null}function Us(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function kv(e,t){if(!e)return[];let n=t?.providerMode??"gateway",r=Array.isArray(e.all)?e.all:[],o=Array.isArray(e.connected)?e.connected:[],s=[];for(let i of r)if(o.includes(i.id)&&!(n==="gateway"?!un.has(i.id):un.has(i.id)))for(let[a,c]of Object.entries(i.models)){if(a==="auto"||a==="kortix/auto")continue;let p;if(Av(c)){let d=c.capabilities;p={reasoning:d.reasoning??!1,vision:d.input?d.input.image??!1:void 0,toolcall:d.toolcall??!1}}else{let d=c.modalities?.input;p={reasoning:c.reasoning??!1,vision:d?d.includes("image"):c.attachment,toolcall:c.tool_call??!1}}s.push({id:ly({providerID:i.id,modelID:a}),providerID:i.id,providerName:c.provider_name??i.name,modelID:a,modelName:(c.name||a).replace("(latest)","").trim(),variants:c.variants,capabilities:p,contextWindow:c.limit?.context,releaseDate:c.release_date,family:c.family,cost:c.cost?{input:c.cost.input??0,output:c.cost.output??0}:void 0,providerSource:i.source,provider:c.provider,reasoningOptions:c.reasoning_options,description:c.description,openWeights:c.open_weights,lastUpdated:c.last_updated,enabled:c.enabled,free:c.free===!0})}return s}function Py(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var Rv=new Set([hy]),Iv="kortix",xy="codex",Tv=new Set(yy);function Cv(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function _t(e){return Rv.has(e.modelID)}function Ev(e){return Ms(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function Mv(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=Ev(e.catalogModels),o=Py(e.catalogModels),s=new Map;for(let i of e.pins??[])s.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,c=s.get(a);if(c==="hide")return!1;if(i.providerID===Iv){let d=Cv(i.modelID,i.provider),g=d===xy?t?.has(xy)??!1:t?.has(d)??!1;if(Tv.has(i.modelID))return!n;if(!g)return!1;if(c==="show"||r.has(a))return!0;let m=o.get(a);if(!m?.releaseDate)return _t(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return _t(i)}catch{return _t(i)}return!1}if(c==="show"||r.has(a))return!0;let p=o.get(a);if(!p?.releaseDate)return _t(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return _t(i)}catch{return _t(i)}return!1}}function Ov(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 Sy(e,t){if(!e||un.has(e.providerID)||se(e.modelID)>0)return e;let n=t.filter(i=>i.providerID===e.providerID&&i.enabled!==!1);if(!n.some(i=>se(i.modelID)>0))return e;let r=i=>se(i)===1&&i.slice(i.indexOf(".")+1)===e.modelID,s=(n.find(i=>i.modelID===`global.${e.modelID}`)??n.find(i=>r(i.modelID)))?.modelID??ln(n.map(i=>({id:i.modelID,released:i.releaseDate})))?.id;return!s||s===e.modelID?e:{...e,modelID:s}}function jv(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??(e?.freeTier?void 0:e?.platformDefault);return n?Ts(n):void 0}function Dv(e){let{models:t,providers:n}=e,r=c=>Us(t,c),o=c=>c.find(p=>!!p&&r(p)),s=(()=>{if(e.configModel){let c=e.configModel.split("/");if(c.length>=2){let[p,...d]=c,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let c of e.recent??[])if(r(c))return c;if(n){let c=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=c[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of Er(Object.keys(m.models).map(w=>({id:w})))){let w={providerID:m.id,modelID:h.id};if(r(w))return w}}}})(),i=o(e.picks??[]),a=i??o([e.serverDefault,e.globalDefault,e.agentModel,s]);return{model:Sy(a,t),explicit:i,fallback:s}}export{qS as ABORT_REASONS,HL as ABORT_REASONS_NOT_YET_EMITTED,ei as ACCOUNTS_LIST_UNAVAILABLE_CODE,Ar as ACTIVE_INSTANCE_COOKIE,Zs as ANALYTICS_UNAVAILABLE_CODE,lw as ATTACHMENT_PART_REF_PREFIX,b as ApiError,te as AuthError,De as BillingError,xw as CONNECTION_FAULT_GRACE_MS,sw as CONNECTOR_POLL_FIRST_DELAY_MS,iw as CONNECTOR_POLL_INTERVAL_MS,aw as CONNECTOR_POLL_WINDOW_MS,_P as CONTEXT_TOOLS,Rf as COST_MARKUP,PP as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,Am as DEFAULT_TRANSCRIPT_OPTIONS,tw as DESTRUCTIVE_PHASES,Lr as FEATURE_DISABLED_CODE,AA as FEATURE_FLAG_KEYS,Qs as FEATURE_NOT_SUPPORTED_CODE,Be as FILE_VERBS,qt as FileExistsError,Et as HeadlessAuthError,Rr as HostBoundaryError,jy as IMPERSONATION_HEADER,ws as INBOX_OBSERVATION_MAX_MS,EK as INITIAL_SETTLED_CONNECTION,GS as INSTANCE_SCOPED_ROUTES,rO as KORTIX_TRANSCRIPT_SCHEMA,ch as MAX_PROMPT_ATTACHMENTS_BYTES,eo as MAX_PROMPT_ATTACHMENT_BYTES,Nc as MAX_PROMPT_ATTACHMENT_FILES,AL as MEMORY_VERBS,Xs as MODEL_NOT_SERVABLE_CODE,Bh as NO_GROUP_ACTIVITY_TOOLS,vs as OPTIMISTIC_ABORT_MAX_MS,eq as OPTIMISTIC_COMPACTION_MAX_MS,xs as OPTIMISTIC_RECEIPT_MAX_MS,ZN as PERSISTED_QUERY_CACHE_VERSION,dx as PLUMBING_TOOLS,_K as PREVIEW_PROBE_TIMEOUT_MS,lR as PROJECT_SESSION_NAME_LOOKUP_LIMIT,cR as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,xh as PROJECT_SESSION_PAGE_MAX_LIMIT,Js as PROVISION_IN_FLIGHT_CODE,uo as PublicSessionShareError,sF as RUNTIME_NOT_READY_MARKERS,iO as RUNTIME_PERMISSION_CAPABILITIES,sO as RUNTIME_PERMISSION_REPLIES,Ye as RequestTooLargeError,Ft as RuntimeNotReadyError,Yo as SANDBOX_FS_ROOTS,Ie as SANDBOX_PORTS,Iw as SERVER_COMPACTION_REVALIDATE_MS,Ss as SERVER_OBSERVATION_MAX_MS,gq as SESSION_LIST_STATUS,yq as SESSION_NOTICE,Wh as STANDALONE_TOOLS,cn as STREAM_OBSERVATION_MAX_MS,kr as SandboxNotReadyError,st as SessionNotReadyError,oo as SessionStartError,GK as TURN_END_LEDGER_LAG_MS,hb as TURN_ERROR_CODES,aq as WAKE_ESCALATION_COOLDOWN_MS,iq as WAKE_MAX_RESTARTS,sq as WAKE_NO_PROGRESS_MS,Ko as WIRE_ID_BACKDATE_MS,Ne as WIRE_ID_CLOCK_TOLERANCE,Ce as WIRE_ID_TIME_MASK,$t as WIRE_ID_TIME_SCALE,db as WIRE_MESSAGE_ID,Uv as __getConfigResolver,$v as __setConfigResolver,VL as abortErrorReason,vi as acceptAccountInvite,LF as acceptInvite,Np as actReviewItem,Za as activateConnection,nc as addComputerToProject,gp as addGroupMembers,wd as addMarketplaceSource,lq as advanceWakeEscalation,sx as allDescendantIds,Yf as appendPreviewToken,na as approveProjectAccessRequest,TO as approveTask,kn as archiveProject,UO as assignTicket,da as attachGroupToProject,Do as authMfa,Mo as authUser,D as authenticatedFetch,hK as authorizePreviewUrl,l as backendApi,dI as bindSlackIdentity,gI as bindTeamsIdentity,va as brokerProjectSecretRequest,nK as browserKeyValueStorage,WS as buildInstancePath,vK as buildPresentationTemplateImageUrl,wK as buildPresentationTemplatePdfUrl,zf as buildPreviewAuthEndpoint,LN as buildPublicTemplateUrl,Pw as buildRuntimePresentationConversionUrl,jc as buildSandboxTemplate,hx as buildScrapeFailureResults,fD as buildStaticFileHealthPreviewUrl,mD as buildStaticFileLocalUrl,gD as buildStaticFilePreviewUrl,A_ as buildStaticFileServicePath,zq as buildTunnelEventStreamUrl,PD as buildWebProxyUrl,Kp as bulkActReviewItems,JI as bulkDeletePolicies,ZI as bulkImportPolicies,V0 as burstSummary,z0 as burstSummaryLabel,Ba as callConnector,SC as cancelAccountDeletion,Pi as cancelAccountInvite,kF as cancelSandbox,nN as cancelSandboxUpdate,bu as cancelScheduledChange,fu as cancelSubscription,PN as checkAccessEmail,C0 as childMapByParent,lN as claimComputer,U_ as claimNext,ZR as claimPerSeatBilling,bl as claimWarmProjectSession,Zm as classifyPart,bw as classifyPreviewProbeStatus,Pb as classifyPtyClose,tx as classifyTurn,U0 as cleanErrorMessage,tU as cleanResultSnippet,yL as cleanWorkerOutput,ni as clearImpersonationSession,tv as clearKortixAppViewerCache,Jl as clearModelDefault,nR as clearSessionFresh,ol as closeChangeRequest,pj as closeMilestone,k0 as collectTurnParts,FO as commentTicket,al as commitSessionChanges,nq as compactionExpiryAtMs,Q0 as compactionTurnInfo,v0 as compareMessagesForDisplay,L_ as completeInFlight,Mu as completeSlackInstall,Ou as completeTeamsInstall,cy as composerSelectableAgents,kf as computeStatusFromPart,Su as configureAutoTopup,Dr as configureKortix,gu as confirmCheckoutSession,Nu as connectEmail,Tu as connectSlack,CK as connectionFromHealth,TK as connectionIsFaulted,gk as connectionSharedWithEveryone,ih as connectorConnect,ah as connectorFinalize,BN as connectorHeadline,fU as contextLabelForTool,N$ as contextToolSummary,K$ as contextToolTrigger,LC as convertPresentationToGoogleSlides,AK as convertRuntimePresentation,ir as copyFile,vu as costExportUrl,WK as countLiveInboxPrompts,BC as countReviewItemsBySegment,li as createAccount,dd as createAccountAuditWebhook,Oa as createAccountSecretResource,td as createAccountToken,kd as createApp,Od as createAppAccessSession,Dd as createAppDeployment,yU as createArtifactKind,Op as createAssignment,XT as createAuditWebhook,qF as createBackup,du as createCheckoutSession,yc as createConnector,KN as createConnectorLinkInfoCache,sr as createFile,op as createGatewayKey,lp as createGroup,qw as createHttpSessionSyncController,iN as createInstance,O_ as createKortix,Ig as createKortixPty,Uo as createKortixSession,PE as createMarketplaceInstallSession,lj as createMilestone,Mv as createModelVisibility,Ip as createOAuthClient,JR as createPerSeatCheckout,tK as createPersistedQueryCache,YI as createPolicy,mu as createPortalSession,Di as createProject,YO as createProjectAgent,id as createProjectCliToken,$i as createProjectRepo,ya as createProjectResourceGrant,et as createProjectSession,Nl as createProjectTrigger,ym as createPromptAttachmentController,Pp as createRole,Yq as createSSEStream,_F as createSandbox,Wp as createSandboxShare,Ec as createSandboxTemplate,qq as createSavedCopyStore,lT as createScimToken,GT as createServiceAccountApi,$n as createSessionPrompt,fl as createSessionPublicShare,D_ as createSessionQueue,Qp as createSessionReminder,IT as createSsoGroupMapping,kO as createTask,jO as createTicket,Qq as createTunnelEventStream,Bq as currentSavedCopyStore,Ai as declineAccountInvite,FF as declineInvite,wC as deleteAccountImmediately,Da as deleteAccountSecretResource,Td as deleteApp,Kd as deleteAppDeployment,ZT as deleteAuditWebhook,BF as deleteBackup,bc as deleteConnector,bj as deleteCredential,kg as deleteEnv,dt as deleteFile,np as deleteGatewayBudget,Ji as deleteGitHubInstallation,pp as deleteGroup,aN as deleteInstance,oj as deleteKortixProject,gj as deleteMilestone,Ep as deleteOAuthClient,Ca as deletePersonalProjectSecret,XI as deletePolicy,XO as deleteProjectAgent,ka as deleteProjectProviderOAuth,ha as deleteProjectResourceGrant,Ia as deleteProjectSecret,Tl as deleteProjectSession,ql as deleteProjectTrigger,kt as deletePromptAttachment,wp as deleteRole,Oc as deleteSandboxTemplate,WT as deleteServiceAccountApi,vl as deleteSessionPrompt,Jp as deleteSessionReminder,TT as deleteSsoGroupMapping,kT as deleteSsoProvider,CO as deleteTask,NO as deleteTicket,wi as describeAccountInvite,Ga as describeConnectorTool,ma as detachGroupFromProject,x_ as detectLocalhostUrls,_q as directSubsessions,BT as disableServiceAccountApi,Ku as disconnectEmail,XN as disconnectGitHubApp,Du as disconnectSlack,hk as discoverConnectionOAuth2,bk as discoverConnectionOAuth2Resource,hc as discoverConnectorAuth,wF as discoverLocalSandbox,$N as downloadAccountAudit,Mj as dropClientForUrl,Dj as dropPublicClientForUrl,q_ as editQueued,Al as editSessionPrompt,$_ as enqueue,VO as ensurePmSession,hw as ensurePreviewSessionCookie,mk as ensureProjectConnectorConnection,ew as ensureSandbox,hl as ensureWarmProjectSession,bb as env,To as exchangeCode,ud as exportAccountAudit,ge as extractGatewayErrorDetails,on as extractInstanceRoute,pS as extractSkillBaseDir,NL as extractSkillContent,cS as extractSkillFiles,bL as extractWorkerPreview,F_ as failInFlight,qU as fallbackBusyRowAfterTurnId,ds as familyForTool,Bs as featureDisabledKey,Qd as featureFlags,QR as fetchAccountStateWithToken,PA as fetchAccountsWithToken,iK as fetchAttachmentPart,cI as fetchCostExportCsv,iy as fetchKortixAppViewer,Fc as fetchProjectArchive,OA as fetchProjectsForAccountWithToken,zd as fetchSessionAttachment,SL as filePhase,xL as fileVerb,i_ as files,mo as finalizeAppArtifact,RN as finalizeConnectorSetupLink,pR as findActiveTranscriptShare,rr as findFiles,R0 as findLastTextPart,HE as findSessionAttachments,or as findText,Bl as fireProjectTrigger,Cc as fixSandboxWithAgent,kv as flattenModels,vU as flattenThought,Hs as formatBillingErrorForUI,lL as formatCost,iL as formatDuration,L0 as formatJsonFailureOutput,RU as formatMessageDay,IU as formatMessageExact,aF as formatOpenCodeRuntimeError,eU as formatRawOutput,ZS as formatRuntimeError,uL as formatTokens,Y_ as formatTranscript,WU as freshSendHint,j_ as generateSessionId,ui as getAccount,di as getAccountBranding,PC as getAccountDeletionStatus,su as getAccountState,iu as getAccountStateMinimal,VS as getActiveInstanceIdFromCookie,EC as getAdminProviderAnalytics,IC as getAdminProviderDistribution,OC as getAdminProviderFallback,vC as getAdminRole,IP as getAgentCardLabel,GR as getAgentConfig,JO as getAgentPersona,ZF as getAllVersions,T0 as getAnsweredQuestionParts,Rd as getApp,Cd as getAppAccess,Ud as getAppDeployment,Ld as getAppDeploymentLogs,yE as getApprovalLink,wt as getAuthToken,ik as getAuthTokenWithRetry,xu as getAutoTopupSettings,XR as getAutoTopupSetupStatus,lu as getBillingCreditBreakdown,pu as getBillingTierConfigurations,cu as getBillingTransactionsSummary,uu as getBillingUsageHistory,Zc as getChangeRequest,el as getChangeRequestDiff,tl as getChangeRequestMergePreview,n0 as getChildSessionError,Ym as getChildSessionId,r0 as getChildSessionToolParts,Ke as getClient,xe as getClientForUrl,Sc as getConnectStatus,yk as getConnectionOAuth2Application,wk as getConnectionOAuth2Status,vk as getConnectionPolicies,In as getConnectorCatalog,gc as getConnectorConfig,pc as getConnectorPolicies,AN as getConnectorSetupLink,aI as getCostSummary,HS as getCurrentInstanceIdFromPathname,XL as getCurrentInstanceIdFromWindow,Hg as getCurrentProject,nu as getDefaultAccountState,i0 as getDiagnostics,RP as getDirectory,Zr as getDiscoverConnector,Ck as getDiscoverIntegration,Lu as getEmailInstallation,Fu as getEmailMode,aC as getEnterpriseDemo,nr as getFileStatus,Vm as getFileWithDir,kP as getFilename,nw as getFullChangelog,Xu as getGatewayBreakdown,ep as getGatewayBudgets,Zu as getGatewayErrors,rp as getGatewayKeys,zu as getGatewayLog,Yu as getGatewayOverview,Gu as getGatewayRoutingPolicy,Qu as getGatewaySeries,Ju as getGatewaySessions,VN as getGitHubAppStatus,Bi as getGitHubInstallation,UC as getGoogleAuthUrl,cp as getGroup,e0 as getHiddenToolParts,Uy as getImpersonationSession,UF as getInvite,sN as getJustavpsServerTypes,tj as getKortixProject,nj as getKortixProjectBySession,Eg as getKortixPtyWebSocketUrl,JF as getLatestSandboxVersion,MN as getMaintenanceConfig,Zi as getManagedGitBackend,TA as getManagedGitStatus,Pd as getMarketplaceCatalogItem,xd as getMarketplaceCatalogItemFile,mT as getMfaRequired,aj as getMilestone,Ql as getModelDefaults,Rp as getOAuthClient,wN as getOAuthConsentRequest,rF as getOpenCodeConfigInvalidError,X$ as getPartText,UT as getPatPolicy,a0 as getPermissionForTool,xn as getProject,ZO as getProjectActivity,zc as getProjectCommit,Yc as getProjectCommitDiff,Sn as getProjectDetail,Qc as getProjectFileHistory,ji as getProjectGitToken,wn as getProjectLlmCatalog,RA as getProjectLlmCatalogProviders,Bn as getProjectModelAccess,vn as getProjectModelPicker,Tn as getProjectSandboxHealth,CA as getProjectSandboxProviderTransition,Dn as getProjectSession,Cl as getProjectSessionConfigState,Ol as getProjectSessionScope,_u as getProrationPreview,hF as getProviders,yD as getProxyBaseUrl,jj as getPublicClientForUrl,bN as getPublicMarketplaceItem,_N as getPublicMarketplaceItemFile,JC as getPublicSessionShare,ZC as getPublicSessionShareMessages,CN as getPublicShareByToken,FN as getPublicTemplate,c0 as getQuestionForTool,vI as getReferralCode,RI as getReferralStats,pL as getRetryInfo,dL as getRetryMessage,Lp as getReviewItem,bp as getRolePermissions,_p as getRoleUsage,hs as getRuntimeConfigInvalidError,VF as getSSHConnection,bF as getSandbox,PF as getSandboxById,pF as getSandboxPortUrl,uN as getSandboxProvisionStatus,pN as getSandboxProvisionStreamUrl,XF as getSandboxUpdateStatus,Nf as getSandboxUrl,IN as getSecretSetupLink,Qo as getServerHealth,xj as getServiceLogs,_l as getSessionAudit,cL as getSessionCost,qn as getSessionCostRecord,Zg as getSessionHealth,Ul as getSessionMessageAuthors,Ll as getSessionModelUsage,dR as getSessionOpenBundle,hT as getSessionOversight,dl as getSessionParticipants,OT as getSessionPolicy,gl as getSessionPreviewCandidates,Fa as getSessionProviderSecretPool,Pl as getSessionTranscript,xl as getSessionTranscriptSync,Sl as getSessionTurn,YU as getShellModePart,$u as getSlackChannelFile,Iu as getSlackInstallation,ju as getSlackManifest,Cu as getSlackMode,ST as getSsoProvider,k_ as getStaticFileHealthPath,Yr as getSupabaseAccessToken,St as getSupabaseAccessTokenWithRetry,wO as getTask,AO as getTaskStatus,wE as getTemplate,MO as getTicket,o0 as getToolInfo,os as getToolPrimaryArg,Q_ as getTranscriptFilename,aL as getTurnCost,nL as getTurnError,oL as getTurnErrorDetails,rL as getTurnErrorRawText,sL as getTurnStatus,wu as getUsageRollup,jN as getUserRolesWithToken,Xc as getVersionDiff,eL as getWorkingState,$a as grantAccountSecretResource,OF as grantSandboxProjectAccess,WR as grantSecretToAgent,A0 as groupMessagesIntoTurns,$U as groupShowSegments,bf as groupSteps,gL as hasDiffs,dD as hasLocalhostUrls,v_ as hasPreviewTarget,O0 as hasRetryingAssistantTurn,Tb as heartbeatGapEvent,Rl as holdSessionPrompts,Gp as humanizeReviewActionPath,mr as humanizeSearchQuery,Xm as humanizeToolName,ri as impersonationHeaders,vT as importSsoProviderFromMetadata,BK as inboxObservationSupersedes,ey as initialWakeEscalationState,Oe as inputPath,vE as installTemplate,Qr as invalidateTokenCache,bi as inviteAccountMember,aa as inviteProjectMember,Mi as inviteRepoCollaborator,vr as isAbortError,Ky as isAdminBypassEnabled,H$ as isAgentPart,b_ as isAppRouteUrl,J$ as isAttachment,uw as isAttachmentPartRef,Ws as isBillingError,V$ as isCompactionPart,$r as isConfigured,F$ as isContextTool,QF as isDestructivePhase,ev as isEmptyConversation,yo as isEmptyShowPart,$0 as isErrorOutput,wD as isExternalUrl,Gs as isFeatureDisabledError,zm as isFilePart,Dy as isImpersonationSessionLive,YL as isInstanceDetailPath,BS as isInstanceScopedAppPath,_D as isInternalLocalhostUrl,Wd as isInvisibleActivityPart,WA as isInviteSent,ZU as isLastUserMessage,Mw as isLegacyMigratedSession,kA as isManagedGithubProject,Bd as isNoGroupActivityTool,Us as isOfferedModel,oF as isOpenCodeConfigInvalidError,ry as isPaintableSavedCopy,Y$ as isPatchPart,eK as isPersistableQueryKey,bD as isPreviewUrl,R_ as isProxiableLocalhostUrl,$E as isQuestionTool,ve as isReasoningPart,ix as isRetryableTurnError,zS as isRuntimeConfigInvalidError,XS as isRuntimeNotReadyResponse,Jg as isRuntimeReady,iF as isRuntimeStartingError,an as isSandboxNotReadyError,xo as isSelectableAgent,Vg as isServerReachable,WE as isSessionAttachmentRef,cl as isSessionFresh,AR as isSessionStartError,DE as isShellActivityTool,iS as isShellMode,hL as isShortOutput,ME as isShowContentUnavailable,Hn as isShowPayloadEmpty,z$ as isSnapshotPart,Hd as isStandaloneActivityTool,Q$ as isStepPart,Ir as isSubdomainPreviewUrl,we as isTextPart,X as isToolPart,t0 as isToolPartHidden,oO as isTurnErrorCode,Ng as isUnderSandboxRoot,SD as isWebProxyUrl,mb as isWireIdAheadOf,rv as kortixAppViewerToken,vb as kortixPty,Ii as leaveAccount,Qi as linkGitHubInstallation,qi as linkRepository,cd as listAccountAudit,pd as listAccountAuditWebhooks,_i as listAccountInvites,hi as listAccountMembers,GI as listAccountResourceGrants,Ma as listAccountSecretResources,DT as listAccountSessions,ed as listAccountTokens,ci as listAccounts,rT as listActions,TC as listAdminSandboxes,yp as listAgentIdentities,za as listAllConnections,Ed as listAppAgents,$d as listAppDeployments,Ad as listApps,Mp as listAssignments,eC as listAuditEvents,QT as listAuditWebhooks,KF as listBackups,au as listBillingTransactions,Jc as listChangeRequests,yI as listChannelBindings,KO as listColumns,Ik as listConnectSections,Rk as listConnectToolkits,Va as listConnections,Wa as listConnectorAccounts,Xr as listConnectorTools,ic as listConnectors,iI as listCostByProject,fj as listCredentialEvents,mj as listCredentials,Jr as listDiscoverConnectors,Tk as listDiscoverIntegrations,xc as listDiscoverSections,vg as listEnv,_d as listFeaturedMarketplaces,GO as listFields,Bt as listFiles,Vu as listGatewayLogs,Wi as listGitHubInstallations,Vi as listGitHubRepositories,zi as listGitHubRepositoryBranches,dp as listGroupMembers,$I as listGroupProjectGrants,ap as listGroups,rj as listKortixProjectSessions,ej as listKortixProjects,Rg as listKortixPty,Hi as listLinkableGitHubInstallations,ea as listManagedGitRepositories,hd as listMarketplaceCatalogItems,Sd as listMarketplaceSources,bd as listMarketplaces,UI as listMemberGroups,LI as listMemberProjectAccess,cj as listMilestoneEvents,ij as listMilestones,Si as listMyAccountInvites,kp as listOAuthClients,rd as listOAuthGrants,ba as listPendingApprovals,ca as listPendingProjectInvites,Dp as listPermissions,_c as listPipedreamApps,Pc as listPipedreamSections,zI as listPolicies,oa as listProjectAccess,ta as listProjectAccessRequests,hp as listProjectAgentIdentities,zO as listProjectAgents,ld as listProjectAudit,Hc as listProjectBranches,sd as listProjectCliTokens,Vc as listProjectCommits,$c as listProjectFiles,pa as listProjectGroupGrants,Ac as listProjectPolicies,Aa as listProjectProviderOAuth,Zp as listProjectReminders,fa as listProjectResourceGrants,Rc as listProjectSandboxTemplates,Dc as listProjectSandboxes,xa as listProjectSecrets,Ze as listProjectSessions,ul as listProjectSessionsPage,Ic as listProjectSnapshots,Fl as listProjectTriggers,Je as listProjects,Ei as listProjectsForAccount,yN as listPublicMarketplaceItems,hN as listPublicMarketplaces,II as listReferrals,Up as listReviewItems,fp as listRoles,MF as listSandboxProjectMembers,Bp as listSandboxShares,SF as listSandboxes,cT as listScimTokens,qT as listServiceAccountsApi,Pj as listServiceTemplates,_j as listServices,kk as listSessionConnectRequests,Au as listSessionCosts,wl as listSessionPrompts,Na as listSessionProviderSecretPools,ml as listSessionPublicShares,Yp as listSessionReminders,_a as listSessionsNeedingInput,iE as listSignedInDevices,RT as listSsoGroupMappings,vO as listTaskEvents,SO as listTasks,WO as listTemplates,OO as listTicketEvents,EO as listTickets,Kw as loadHttpSessionHistory,af as looksLikeError,cU as looksLikeHtml,Z0 as looksLikeJsonPayload,HC as mapApiReviewItem,cN as markInstanceError,jn as markSessionFresh,Pg as maxWireIdClock,kL as memoryRelPath,wU as mergeBurstSteps,rl as mergeChangeRequest,kU as messageCreatedAt,Qx as messageTime,MC as migrateAdminSandboxProvider,qo as mintWireMessageId,Sg as mintWireMessageIdAbove,zt as mkdir,Ov as modelInDefaultView,av as modelRefToKey,yf as narrateFailedStep,ff as narrateStep,xr as narrationToolName,Cb as narrowChatEvent,fb as newestWireIdClock,GN as nextConnectorPollDelay,ae as normalizeActivityToolName,eF as normalizeAppPathname,vD as normalizeExternalInput,H as normalizeName,Qm as normalizeToolName,Dw as notifyHostSignal,nl as openChangeRequest,Ho as openEventStream,UN as openStressTestStream,mn as parseBillingError,nU as parseEmbeddedFailure,XE as parseFlagOverride,px as parseJsonFailure,ur as parseLocalhostUrl,RL as parseMemoryView,nF as parseOpenCodeErrorPayload,ML as parsePresentationOutput,Xg as parseProxyHop,jL as parseQuestionAnswersFromOutput,UL as parseReadOutput,Ff as parseRuntimeErrorPayload,yx as parseScrapeInputUrls,bx as parseScrapeOutput,cm as parseSubdomainUrl,_L as parseTaskRows,xD as parseWebProxyUrl,pf as parseWebSearchOutput,cf as partOutcome,sj as patchKortixProject,CL as patchVerb,vv as pickerProviderList,fc as pipedreamConnect,oc as pipedreamConnectConnection,vc as pipedreamFinalize,sc as pipedreamFinalizeConnection,R as platformConfig,Sk as pollConnectionOAuth2DeviceAuthorization,Vr as pollProjectProviderOAuth,Hu as previewGatewayRoute,fT as previewMfaRequired,mI as previewSlackIdentity,fI as previewTeamsIdentity,vp as probeEffectivePermission,Ap as probeEffectivePermissions,PK as probePreviewPort,tq as projectCompacting,iv as projectConfigAgentsToOpenCodeAgents,ay as projectConfigAgentsToRuntimeAgents,IK as projectSessionConnection,Pq as projectSessionForRuntimeId,vR as projectSessionStartSeed,VK as projectWorking,Ui as provisionProject,IA as provisionProjectStream,jA as provisionProjectWithToken,im as proxyLocalhostUrl,hD as proxyUrlToInternal,Pu as purchaseCredits,fk as putConnectionOAuth2Application,Cm as rawErrorText,RF as reactivateSandbox,yu as reactivateSubscription,Ht as readBlob,Wt as readFile,Lc as readProjectFile,Vx as reasoningIsRunning,Tc as rebuildProjectSnapshot,Ya as reconcileConnection,Qa as reconcileMemberConnection,wj as reconcileServices,SN as recordPlatformLogout,us as recoverLinkResults,AI as refreshReferralCode,Mt as refreshSession,go as registerAppArtifact,_k as registerConnectionOAuth2Client,vj as registerService,ra as rejectProjectAccessRequest,s0 as relativizePath,El as reloadProjectSessionConfig,Ml as reloadProjectSessionConfigStream,md as removeAccountAuditWebhook,fi as removeAccountBrandingAsset,ki as removeAccountMember,mp as removeGroupMember,Cg as removeKortixPty,vd as removeMarketplaceSource,K_ as removeQueued,tc as renameConnection,cr as renameFile,xF as renameSandbox,sl as reopenChangeRequest,dj as reopenMilestone,G_ as reorderQueued,qO as replaceColumns,BO as replaceFields,Gi as replaceProjectRepository,HO as replaceTemplates,xC as requestAccountDeletion,il as requestChangesOnChangeRequest,BA as requestProjectAccess,yd as requestProjectConnector,fd as requestProjectSecret,xi as resendAccountInvite,ua as resendPendingProjectInvite,yi as resetAccountBranding,Oj as resetClient,Wu as resetGatewayRoutingPolicy,Co as resetPassword,$j as resetPublicClient,tN as resetSandboxUpdateStatus,Pa as resolveApproval,sv as resolveComposerAgent,Dv as resolveComposerModel,qN as resolveConnectorStart,jv as resolveModelDefault,uR as resolvePublicShareUrl,lU as resolveScrapeResults,HU as resolveWorkingTurn,YR as resolvedPlan,Un as restartProjectSession,vF as restartSandbox,GF as restoreBackup,N_ as retryFailed,kl as retrySessionPrompt,hj as revealCredential,GC as reviewItemTarget,Eh as reviewSegmentForStatus,WC as reviewVerdictForStatus,Ua as revokeAccountSecretResourceGrant,$T as revokeAccountSession,nd as revokeAccountToken,jp as revokeAssignment,Ja as revokeConnection,sp as revokeGatewayKey,od as revokeOAuthGrant,la as revokePendingProjectInvite,ia as revokeProjectAccess,ad as revokeProjectCliToken,jF as revokeSandboxProjectAccess,Hp as revokeSandboxShare,uT as revokeScimToken,yl as revokeSessionPublicShare,qe as rewriteLocalhostUrl,qd as rollbackApp,Ow as rootRuntimeSession,ja as rotateAccountSecretResource,Cp as rotateOAuthClientSecret,ip as runGatewayPlayground,YA as runProjectProviderOAuthFlow,ks as runtimeSessionsOf,c_ as runtimeSupports,wb as sanitizePtyChunk,Yi as saveGitHubInstallation,Zw as savedCopyEmptyRoot,hu as scheduleDowngrade,qa as searchConnectorTools,Uc as searchProjectFiles,MU as segmentTurn,eM as selectableProjectAgents,ko as sendMagicLink,TI as sendReferralEmails,rq as serverCompactionRevalidateAtMs,Sj as serviceAction,fq as sessionConnectionLabel,mq as sessionListStatus,$l as sessionModelPin,aR as sessionParentId,kR as sessionStartKey,La as setAccountSecretResourceAccess,JL as setActiveInstanceCookie,Ny as setAdminBypass,CC as setAdminProviderDistribution,jC as setAdminProviderFallback,eu as setAgentScope,sk as setBootstrapAuthToken,ok as setCachedAuthToken,Ak as setConnectionPolicies,lc as setConnectorAuthorizationStrategy,wc as setConnectorCredential,cc as setConnectorCredentialMode,mc as setConnectorName,dc as setConnectorPolicies,Ek as setConnectorSecretBinding,uc as setConnectorSensitive,ec as setDefaultConnection,cC as setEnterpriseDemo,Ag as setEnv,tp as setGatewayBudget,Bu as setGatewayRoutingPolicy,YN as setGitHubAppFromExisting,QN as setGitHubAppPat,Vv as setImpersonationSession,ON as setMaintenanceConfig,oT as setMemberSuperAdmin,yT as setMfaRequired,Xl as setModelDefault,Ta as setPersonalProjectSecret,Wn as setProjectModelAccess,OR as setProjectModelEnablement,Ki as setProjectOnboardingComplete,MA as setProjectOnboardingProfile,kc as setProjectPolicies,wa as setProjectSecretStrategy,Dl as setProjectSessionModel,jl as setProjectSessionScope,pl as setProjectSessionSharing,Gl as setProjectTriggersActivation,Gq as setSavedCopyStore,bT as setSessionOversight,Ka as setSessionProviderSecretPool,MK as settleSessionConnection,HF as setupSSH,rc as shareConnection,UE as shellActivityGroupLabel,$f as shellExitCode,Fy as shouldAttachImpersonation,tL as shouldHideResponsePart,SP as shouldShowToolPart,KU as shouldSuppressWorkingTurnBusy,UU as showGroupItems,Af as showTurnBusyIndicator,Ao as signInWithPassword,Io as signInWithProvider,jo as signInWithSso,$o as signOut,aE as signOutDevice,vo as signUp,qL as skillDocumentPath,KL as skillInputDir,E0 as sortSessions,Z$ as splitUserParts,Fd as startApp,Pk as startConnectionOAuth2Authorization,xk as startConnectionOAuth2DeviceAuthorization,kN as startConnectorSetupLink,zN as startGitHubAppManifest,Hr as startProjectProviderOAuth,Ue as startProjectSession,EN as startSessionWithToken,IO as startTask,lf as stepLabel,Nd as stopApp,Ln as stopProjectSession,AF as stopSandbox,Xi as storeGitHubUserToken,l0 as stripAnsi,QL as stripInstancePrefix,de as stripTrailingSlashes,xN as submitAccessRequest,DN as submitDemoRequest,vN as submitOAuthConsent,Fp as submitReviewItem,TN as submitSecretSetupLink,zv as subscribeToImpersonation,gA as supabaseClient,ac as syncConnectors,eI as syncSubscription,Uj as systemReload,pt as toDaemonPath,ZL as toInstanceAwarePath,I_ as toInternalUrl,Gt as toSandboxAbsolutePath,h0 as toToolView,Kg as toWorkspaceRelative,ss as toolInfo,re as toolKind,US as toolViewModel,eN as triggerSandboxUpdate,_b as triggersRequest,kw as turnEndCause,JK as turnEndNotice,I0 as turnHasSteps,GU as turnIsConfirmedActive,hq as turnRetryLabel,LO as unassignTicket,ce as unwrapError,gd as updateAccountAuditWebhook,gi as updateAccountBranding,Ri as updateAccountMemberRole,pi as updateAccountName,BR as updateAgentConfig,Id as updateApp,Md as updateAppAccess,JT as updateAuditWebhook,hI as updateChannelBinding,Xa as updateConnectionCredential,qu as updateEmailPolicy,Fi as updateExperimentalFeature,Li as updateFeatureFlag,up as updateGroup,Tg as updateKortixPty,uj as updateMilestone,Tp as updateOAuthClient,Eo as updatePassword,LT as updatePatPolicy,QI as updatePolicy,An as updateProject,sa as updateProjectAccess,QO as updateProjectAgent,tu as updateProjectDefaultAgent,ga as updateProjectGroupGrant,Ni as updateProjectSandboxProvider,Il as updateProjectSession,Kl as updateProjectTrigger,xp as updateRole,Sp as updateRolePermissions,Mc as updateSandboxTemplate,jT as updateSessionPolicy,Xp as updateSessionReminder,RO as updateTask,EA as updateTemplateWarmPool,DO as updateTicket,$O as updateTicketStatus,Oo as updateUserMetadata,mi as uploadAccountBrandingAsset,jd as uploadAppArtifactArchive,Ha as uploadConnectorAttachment,Vt as uploadFile,On as uploadPromptAttachment,Vd as uploadSessionAttachment,Uu as uploadSlackChannelFile,Kt as uploadTimeoutMsForBytes,yj as upsertCredential,Ra as upsertProjectGitCredential,Sa as upsertProjectSecret,wT as upsertSsoProvider,Oi as validateProjectManifest,kI as validateReferralCode,Ti as validateToken,xI as verifyGatewayProvider,Ro as verifyOtp,AT as verifySsoDomain,pq as wakeEscalationAttemptSummary,uq as wakeEscalationNote,cq as wakeProgressFingerprint,at as wireIdClock,Ut as wireIdClockAt,ct as wireIdClockDelta,zK as workingExpiryAtMs,BU as workingTurnDrawsBusyRow,LE as writeActivityGroupLabel,ar as writeFile,ps as wsDomain,aU as wsFavicon,iU as wsRootDomain};