@kortix/sdk 0.13.21 → 0.13.23

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 (39) hide show
  1. package/README.md +54 -10
  2. package/dist/core/client/kortix.d.ts +8 -3
  3. package/dist/core/client/kortix.d.ts.map +1 -1
  4. package/dist/core/client/kortix.js +3 -0
  5. package/dist/core/client/kortix.js.map +1 -1
  6. package/dist/core/rest/projects-client/account-secret-resources.d.ts +9 -1
  7. package/dist/core/rest/projects-client/account-secret-resources.d.ts.map +1 -1
  8. package/dist/core/rest/projects-client/account-secret-resources.js +6 -2
  9. package/dist/core/rest/projects-client/account-secret-resources.js.map +1 -1
  10. package/dist/core/rest/projects-client/connectors.d.ts +86 -3
  11. package/dist/core/rest/projects-client/connectors.d.ts.map +1 -1
  12. package/dist/core/rest/projects-client/connectors.js +27 -4
  13. package/dist/core/rest/projects-client/connectors.js.map +1 -1
  14. package/dist/core/rest/projects-client/sessions.d.ts +18 -5
  15. package/dist/core/rest/projects-client/sessions.d.ts.map +1 -1
  16. package/dist/core/rest/projects-client/sessions.js.map +1 -1
  17. package/dist/core/rest/projects-client/setup-links.d.ts +7 -0
  18. package/dist/core/rest/projects-client/setup-links.d.ts.map +1 -1
  19. package/dist/core/rest/projects-client/setup-links.js +3 -0
  20. package/dist/core/rest/projects-client/setup-links.js.map +1 -1
  21. package/dist/core/turns/open-turn.d.ts +3 -2
  22. package/dist/core/turns/open-turn.d.ts.map +1 -1
  23. package/dist/core/turns/open-turn.js +3 -2
  24. package/dist/core/turns/open-turn.js.map +1 -1
  25. package/dist/kortix.esm.min.js +22 -22
  26. package/dist/kortix.global.js +22 -22
  27. package/dist/react/teams-install-polling.d.ts +10 -0
  28. package/dist/react/teams-install-polling.d.ts.map +1 -0
  29. package/dist/react/teams-install-polling.js +11 -0
  30. package/dist/react/teams-install-polling.js.map +1 -0
  31. package/dist/react/use-provider-secrets.d.ts +1 -1
  32. package/dist/react/use-provider-secrets.d.ts.map +1 -1
  33. package/dist/react/use-provider-secrets.js +3 -3
  34. package/dist/react/use-provider-secrets.js.map +1 -1
  35. package/dist/react/use-teams-installations.d.ts +11 -0
  36. package/dist/react/use-teams-installations.d.ts.map +1 -1
  37. package/dist/react/use-teams-installations.js +4 -0
  38. package/dist/react/use-teams-installations.js.map +1 -1
  39. package/package.json +2 -2
@@ -1,23 +1,23 @@
1
- var eg={backendUrl:"",getToken:async()=>null},fn=null,mt=null;function Xh(e){mt=e}function Jh(){return mt}function yn(e,t){t?.global!==!1&&(fn=e)}function O(){return mt?.()??fn??eg}function hn(){return fn!==null||mt?.()!==void 0}var ii=({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:s,sseDefaultRetryDelay:o,sseMaxRetryAttempts:u,sseMaxRetryDelay:p,sseSleepFn:d,url:f,...m})=>{let h,P=d??(v=>new Promise(M=>setTimeout(M,v)));return{stream:async function*(){let v=o??3e3,M=0,$=m.signal??new AbortController().signal;for(;!$.aborted;){M++;let l=m.headers instanceof Headers?m.headers:new Headers(m.headers);h!==void 0&&l.set("Last-Event-ID",h);try{let y={redirect:"follow",...m,body:m.serializedBody,headers:l,signal:$},a=new Request(f,y);e&&(a=await e(f,y));let I=await(m.fetch??globalThis.fetch)(a);if(!I.ok)throw new Error(`SSE failed: ${I.status} ${I.statusText}`);if(!I.body)throw new Error("No body in SSE response");let R=I.body.pipeThrough(new TextDecoderStream).getReader(),k="",F=()=>{try{R.cancel()}catch{}};$.addEventListener("abort",F);try{for(;;){let{done:j,value:K}=await R.read();if(j)break;k+=K,k=k.replace(/\r\n/g,`
1
+ var ng={backendUrl:"",getToken:async()=>null},yn=null,ft=null;function Qh(e){ft=e}function Yh(){return ft}function hn(e,t){t?.global!==!1&&(yn=e)}function O(){return ft?.()??yn??ng}function bn(){return yn!==null||ft?.()!==void 0}var ii=({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:s,sseDefaultRetryDelay:o,sseMaxRetryAttempts:u,sseMaxRetryDelay:p,sseSleepFn:d,url:f,...m})=>{let h,P=d??(v=>new Promise(M=>setTimeout(M,v)));return{stream:async function*(){let v=o??3e3,M=0,$=m.signal??new AbortController().signal;for(;!$.aborted;){M++;let l=m.headers instanceof Headers?m.headers:new Headers(m.headers);h!==void 0&&l.set("Last-Event-ID",h);try{let y={redirect:"follow",...m,body:m.serializedBody,headers:l,signal:$},a=new Request(f,y);e&&(a=await e(f,y));let I=await(m.fetch??globalThis.fetch)(a);if(!I.ok)throw new Error(`SSE failed: ${I.status} ${I.statusText}`);if(!I.body)throw new Error("No body in SSE response");let R=I.body.pipeThrough(new TextDecoderStream).getReader(),w="",F=()=>{try{R.cancel()}catch{}};$.addEventListener("abort",F);try{for(;;){let{done:j,value:K}=await R.read();if(j)break;w+=K,w=w.replace(/\r\n/g,`
2
2
  `).replace(/\r/g,`
3
- `);let D=k.split(`
3
+ `);let D=w.split(`
4
4
 
5
- `);k=D.pop()??"";for(let b of D){let T=b.split(`
5
+ `);w=D.pop()??"";for(let b of D){let T=b.split(`
6
6
  `),q=[],N;for(let W of T)if(W.startsWith("data:"))q.push(W.replace(/^data:\s*/,""));else if(W.startsWith("event:"))N=W.replace(/^event:\s*/,"");else if(W.startsWith("id:"))h=W.replace(/^id:\s*/,"");else if(W.startsWith("retry:")){let Z=Number.parseInt(W.replace(/^retry:\s*/,""),10);Number.isNaN(Z)||(v=Z)}let B,Q=!1;if(q.length){let W=q.join(`
7
- `);try{B=JSON.parse(W),Q=!0}catch{B=W}}Q&&(s&&await s(B),r&&(B=await r(B))),n?.({data:B,event:N,id:h,retry:v}),q.length&&(yield B)}}}finally{$.removeEventListener("abort",F),R.releaseLock()}break}catch(y){if(t?.(y),u!==void 0&&M>=u)break;let a=Math.min(v*2**(M-1),p??3e4);await P(a)}}}()}};var tg=e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},ng=e=>{switch(e){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},rg=e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},ft=({allowReserved:e,explode:t,name:n,style:r,value:s})=>{if(!t){let p=(e?s:s.map(d=>encodeURIComponent(d))).join(ng(r));switch(r){case"label":return`.${p}`;case"matrix":return`;${n}=${p}`;case"simple":return p;default:return`${n}=${p}`}}let o=tg(r),u=s.map(p=>r==="label"||r==="simple"?e?p:encodeURIComponent(p):Ce({allowReserved:e,name:n,value:p})).join(o);return r==="label"||r==="matrix"?o+u:u},Ce=({allowReserved:e,name:t,value:n})=>{if(n==null)return"";if(typeof n=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},yt=({allowReserved:e,explode:t,name:n,style:r,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${n}=${s.toISOString()}`;if(r!=="deepObject"&&!t){let d=[];Object.entries(s).forEach(([m,h])=>{d=[...d,m,e?h:encodeURIComponent(h)]});let f=d.join(",");switch(r){case"form":return`${n}=${f}`;case"label":return`.${f}`;case"matrix":return`;${n}=${f}`;default:return f}}let u=rg(r),p=Object.entries(s).map(([d,f])=>Ce({allowReserved:e,name:r==="deepObject"?`${n}[${d}]`:d,value:f})).join(u);return r==="label"||r==="matrix"?u+p:p};var sg=/\{[^{}]+\}/g,ig=({path:e,url:t})=>{let n=t,r=t.match(sg);if(r)for(let s of r){let o=!1,u=s.substring(1,s.length-1),p="simple";u.endsWith("*")&&(o=!0,u=u.substring(0,u.length-1)),u.startsWith(".")?(u=u.substring(1),p="label"):u.startsWith(";")&&(u=u.substring(1),p="matrix");let d=e[u];if(d==null)continue;if(Array.isArray(d)){n=n.replace(s,ft({explode:o,name:u,style:p,value:d}));continue}if(typeof d=="object"){n=n.replace(s,yt({explode:o,name:u,style:p,value:d,valueOnly:!0}));continue}if(p==="matrix"){n=n.replace(s,`;${Ce({name:u,value:d})}`);continue}let f=encodeURIComponent(p==="label"?`.${d}`:d);n=n.replace(s,f)}return n},oi=({baseUrl:e,path:t,query:n,querySerializer:r,url:s})=>{let o=s.startsWith("/")?s:`/${s}`,u=(e??"")+o;t&&(u=ig({path:t,url:u}));let p=n?r(n):"";return p.startsWith("?")&&(p=p.substring(1)),p&&(u+=`?${p}`),u};function bn(e){let t=e.body!==void 0;if(t&&e.bodySerializer)return"serializedBody"in e?e.serializedBody!==void 0&&e.serializedBody!==""?e.serializedBody:null:e.body!==""?e.body:null;if(t)return e.body}var ai=async(e,t)=>{let n=typeof t=="function"?await t(e):t;if(n)return e.scheme==="bearer"?`Bearer ${n}`:e.scheme==="basic"?`Basic ${btoa(n)}`:n};var xn={bodySerializer:e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n)};var ci=({parameters:e={},...t}={})=>r=>{let s=[];if(r&&typeof r=="object")for(let o in r){let u=r[o];if(u==null)continue;let p=e[o]||t;if(Array.isArray(u)){let d=ft({allowReserved:p.allowReserved,explode:!0,name:o,style:"form",value:u,...p.array});d&&s.push(d)}else if(typeof u=="object"){let d=yt({allowReserved:p.allowReserved,explode:!0,name:o,style:"deepObject",value:u,...p.object});d&&s.push(d)}else{let d=Ce({allowReserved:p.allowReserved,name:o,value:u});d&&s.push(d)}}return s.join("&")},li=e=>{if(!e)return"stream";let t=e.split(";")[0]?.trim();if(t){if(t.startsWith("application/json")||t.endsWith("+json"))return"json";if(t==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(n=>t.startsWith(n)))return"blob";if(t.startsWith("text/"))return"text"}},og=(e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)):!1,ui=async({security:e,...t})=>{for(let n of e){if(og(t,n.name))continue;let r=await ai(n,t.auth);if(!r)continue;let s=n.name??"Authorization";switch(n.in){case"query":t.query||(t.query={}),t.query[s]=r;break;case"cookie":t.headers.append("Cookie",`${s}=${r}`);break;default:t.headers.set(s,r);break}}},_n=e=>oi({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer=="function"?e.querySerializer:ci(e.querySerializer),url:e.url}),Pn=(e,t)=>{let n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=ht(e.headers,t.headers),n},ag=e=>{let t=[];return e.forEach((n,r)=>{t.push([r,n])}),t},ht=(...e)=>{let t=new Headers;for(let n of e){if(!n)continue;let r=n instanceof Headers?ag(n):Object.entries(n);for(let[s,o]of r)if(o===null)t.delete(s);else if(Array.isArray(o))for(let u of o)t.append(s,u);else o!==void 0&&t.set(s,typeof o=="object"?JSON.stringify(o):o)}return t},Ne=class{fns=[];clear(){this.fns=[]}eject(t){let n=this.getInterceptorIndex(t);this.fns[n]&&(this.fns[n]=null)}exists(t){let n=this.getInterceptorIndex(t);return!!this.fns[n]}getInterceptorIndex(t){return typeof t=="number"?this.fns[t]?t:-1:this.fns.indexOf(t)}update(t,n){let r=this.getInterceptorIndex(t);return this.fns[r]?(this.fns[r]=n,t):!1}use(t){return this.fns.push(t),this.fns.length-1}},pi=()=>({error:new Ne,request:new Ne,response:new Ne}),cg=ci({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),lg={"Content-Type":"application/json"},Ke=(e={})=>({...xn,headers:lg,parseAs:"auto",querySerializer:cg,...e});var He=(e={})=>{let t=Pn(Ke(),e),n=()=>({...t}),r=f=>(t=Pn(t,f),n()),s=pi(),o=async f=>{let m={...t,...f,fetch:f.fetch??t.fetch??globalThis.fetch,headers:ht(t.headers,f.headers),serializedBody:void 0};m.security&&await ui({...m,security:m.security}),m.requestValidator&&await m.requestValidator(m),m.body!==void 0&&m.bodySerializer&&(m.serializedBody=m.bodySerializer(m.body)),(m.body===void 0||m.serializedBody==="")&&m.headers.delete("Content-Type");let h=_n(m);return{opts:m,url:h}},u=async f=>{let{opts:m,url:h}=await o(f),P={redirect:"follow",...m,body:bn(m)},x=new Request(h,P);for(let A of s.request.fns)A&&(x=await A(x,m));let _=m.fetch,v;try{v=await _(x)}catch(A){let I=A;for(let R of s.error.fns)R&&(I=await R(A,void 0,x,m));if(I=I||{},m.throwOnError)throw I;return m.responseStyle==="data"?void 0:{error:I,request:x,response:void 0}}for(let A of s.response.fns)A&&(v=await A(v,x,m));let M={request:x,response:v};if(v.ok){let A=(m.parseAs==="auto"?li(v.headers.get("Content-Type")):m.parseAs)??"json";if(v.status===204||v.headers.get("Content-Length")==="0"){let R;switch(A){case"arrayBuffer":case"blob":case"text":R=await v[A]();break;case"formData":R=new FormData;break;case"stream":R=v.body;break;default:R={};break}return m.responseStyle==="data"?R:{data:R,...M}}let I;switch(A){case"arrayBuffer":case"blob":case"formData":case"text":I=await v[A]();break;case"json":{let R=await v.text();I=R?JSON.parse(R):{};break}case"stream":return m.responseStyle==="data"?v.body:{data:v.body,...M}}return A==="json"&&(m.responseValidator&&await m.responseValidator(I),m.responseTransformer&&(I=await m.responseTransformer(I))),m.responseStyle==="data"?I:{data:I,...M}}let $=await v.text(),l;try{l=JSON.parse($)}catch{}let y=l??$,a=y;for(let A of s.error.fns)A&&(a=await A(y,v,x,m));if(a=a||{},m.throwOnError)throw a;return m.responseStyle==="data"?void 0:{error:a,...M}},p=f=>m=>u({...m,method:f}),d=f=>async m=>{let{opts:h,url:P}=await o(m);return ii({...h,body:h.body,headers:h.headers,method:f,onRequest:async(x,_)=>{let v=new Request(x,_);for(let M of s.request.fns)M&&(v=await M(v,h));return v},serializedBody:bn(h),url:P})};return{buildUrl:_n,connect:p("CONNECT"),delete:p("DELETE"),get:p("GET"),getConfig:n,head:p("HEAD"),interceptors:s,options:p("OPTIONS"),patch:p("PATCH"),post:p("POST"),put:p("PUT"),request:u,setConfig:r,sse:{connect:d("CONNECT"),delete:d("DELETE"),get:d("GET"),head:d("HEAD"),options:d("OPTIONS"),patch:d("PATCH"),post:d("POST"),put:d("PUT"),trace:d("TRACE")},trace:p("TRACE")}};var ug={$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"},pg=Object.entries(ug),di=(e,t)=>{t||(t=new Map);for(let n of e)"in"in n?n.key&&t.set(n.key,{in:n.in,map:n.map}):"key"in n?t.set(n.key,{map:n.map}):n.args&&di(n.args,t);return t},dg=e=>{for(let[t,n]of Object.entries(e))n&&typeof n=="object"&&!Object.keys(n).length&&delete e[t]},g=(e,t)=>{let n={body:{},headers:{},path:{},query:{}},r=di(t),s;for(let[o,u]of e.entries())if(t[o]&&(s=t[o]),!!s)if("in"in s)if(s.key){let p=r.get(s.key),d=p.map||s.key;p.in&&(n[p.in][d]=u)}else n.body=u;else for(let[p,d]of Object.entries(u??{})){let f=r.get(p);if(f)if(f.in){let m=f.map||p;n[f.in][m]=d}else n[f.map]=d;else{let m=pg.find(([h])=>p.startsWith(h));if(m){let[h,P]=m;n[P][p.slice(h.length)]=d}else if("allowExtra"in s&&s.allowExtra){for(let[h,P]of Object.entries(s.allowExtra))if(P){n[h][p]=d;break}}}}return dg(n),n};var gi=He(Ke({baseUrl:"http://localhost:4096"}));var w=class{client;constructor(t){this.client=t?.client??gi}},kn=class{defaultKey="default";instances=new Map;get(t){let n=this.instances.get(t??this.defaultKey);if(!n)throw new Error('No SDK client found. Create one with "new OpencodeClient()" to fix this error.');return n}set(t,n){this.instances.set(n??this.defaultKey,t)}},wn=class extends w{remove(t,n){let r=g([t],[{args:[{in:"path",key:"providerID"}]}]);return(n?.client??this.client).delete({url:"/auth/{providerID}",...n,...r})}set(t,n){let r=g([t],[{args:[{in:"path",key:"providerID"},{key:"auth",map:"body"}]}]);return(n?.client??this.client).put({url:"/auth/{providerID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},Sn=class extends w{log(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"service"},{in:"body",key:"level"},{in:"body",key:"message"},{in:"body",key:"extra"}]}]);return(n?.client??this.client).post({url:"/log",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}agents(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/agent",...n,...r})}skills(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/skill",...n,...r})}},vn=class extends w{moveSession(t,n){let r=g([t],[{args:[{in:"body",key:"sessionID"},{in:"body",key:"destination"},{in:"body",key:"moveChanges"}]}]);return(n?.client??this.client).post({url:"/experimental/control-plane/move-session",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},An=class extends w{get(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/capabilities",...n,...r})}},Cn=class extends w{get(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/console",...n,...r})}listOrgs(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/console/orgs",...n,...r})}switchOrg(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"accountID"},{in:"body",key:"orgID"}]}]);return(n?.client??this.client).post({url:"/experimental/console/switch",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},Rn=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"roots"},{in:"query",key:"start"},{in:"query",key:"cursor"},{in:"query",key:"search"},{in:"query",key:"limit"},{in:"query",key:"archived"}]}]);return(n?.client??this.client).get({url:"/experimental/session",...n,...r})}background(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/experimental/session/{sessionID}/background",...n,...r})}},Tn=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/resource",...n,...r})}},In=class extends w{generateName(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"context"}]}]);return(n?.client??this.client).post({url:"/experimental/project/{projectID}/copy/generate-name",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},En=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/workspace/adapter",...n,...r})}},jn=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/workspace",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"id"},{in:"body",key:"type"},{in:"body",key:"branch"},{in:"body",key:"extra"}]}]);return(n?.client??this.client).post({url:"/experimental/workspace",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}syncList(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/experimental/workspace/sync-list",...n,...r})}status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/workspace/status",...n,...r})}remove(t,n){let r=g([t],[{args:[{in:"path",key:"id"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/experimental/workspace/{id}",...n,...r})}warp(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"id"},{in:"body",key:"sessionID"},{in:"body",key:"copyChanges"}]}]);return(n?.client??this.client).post({url:"/experimental/workspace/warp",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}_adapter;get adapter(){return this._adapter??=new En({client:this.client})}},$n=class extends w{_controlPlane;get controlPlane(){return this._controlPlane??=new vn({client:this.client})}_capabilities;get capabilities(){return this._capabilities??=new An({client:this.client})}_console;get console(){return this._console??=new Cn({client:this.client})}_session;get session(){return this._session??=new Rn({client:this.client})}_resource;get resource(){return this._resource??=new Tn({client:this.client})}_projectCopy;get projectCopy(){return this._projectCopy??=new In({client:this.client})}_workspace;get workspace(){return this._workspace??=new jn({client:this.client})}},Mn=class extends w{get(t){return(t?.client??this.client).get({url:"/global/config",...t})}update(t,n){let r=g([t],[{args:[{key:"config",map:"body"}]}]);return(n?.client??this.client).patch({url:"/global/config",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},Dn=class extends w{health(t){return(t?.client??this.client).get({url:"/global/health",...t})}event(t){return(t?.client??this.client).sse.get({url:"/global/event",...t})}dispose(t){return(t?.client??this.client).post({url:"/global/dispose",...t})}upgrade(t,n){let r=g([t],[{args:[{in:"body",key:"target"}]}]);return(n?.client??this.client).post({url:"/global/upgrade",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}_config;get config(){return this._config??=new Mn({client:this.client})}},On=class extends w{subscribe(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).sse.get({url:"/event",...n,...r})}},qn=class extends w{get(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/config",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"config",map:"body"}]}]);return(n?.client??this.client).patch({url:"/config",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}providers(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/config/providers",...n,...r})}},Un=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"provider"},{in:"query",key:"model"}]}]);return(n?.client??this.client).get({url:"/experimental/tool",...n,...r})}ids(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/tool/ids",...n,...r})}},Fn=class extends w{remove(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"worktreeRemoveInput",map:"body"}]}]);return(n?.client??this.client).delete({url:"/experimental/worktree",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/worktree",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"worktreeCreateInput",map:"body"}]}]);return(n?.client??this.client).post({url:"/experimental/worktree",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}reset(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"worktreeResetInput",map:"body"}]}]);return(n?.client??this.client).post({url:"/experimental/worktree/reset",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},Ln=class extends w{text(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"pattern"}]}]);return(n?.client??this.client).get({url:"/find",...n,...r})}files(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"query"},{in:"query",key:"dirs"},{in:"query",key:"type"},{in:"query",key:"limit"}]}]);return(n?.client??this.client).get({url:"/find/file",...n,...r})}symbols(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"query"}]}]);return(n?.client??this.client).get({url:"/find/symbol",...n,...r})}},Bn=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"path"}]}]);return(n?.client??this.client).get({url:"/file",...n,...r})}read(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"path"}]}]);return(n?.client??this.client).get({url:"/file/content",...n,...r})}status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/file/status",...n,...r})}},Gn=class extends w{dispose(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/instance/dispose",...n,...r})}},Nn=class extends w{get(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/path",...n,...r})}},Kn=class extends w{raw(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/vcs/diff/raw",...n,...r})}},Hn=class extends w{get(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/vcs",...n,...r})}status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/vcs/status",...n,...r})}diff(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"mode"},{in:"query",key:"context"}]}]);return(n?.client??this.client).get({url:"/vcs/diff",...n,...r})}apply(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"patch"}]}]);return(n?.client??this.client).post({url:"/vcs/apply",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}_diff;get diff2(){return this._diff??=new Kn({client:this.client})}},Wn=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/command",...n,...r})}},zn=class extends w{status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/lsp",...n,...r})}},Vn=class extends w{status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/formatter",...n,...r})}},Xn=class extends w{remove(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/mcp/{name}/auth",...n,...r})}start(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/mcp/{name}/auth",...n,...r})}callback(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"code"}]}]);return(n?.client??this.client).post({url:"/mcp/{name}/auth/callback",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}authenticate(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/mcp/{name}/auth/authenticate",...n,...r})}},Jn=class extends w{status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/mcp",...n,...r})}add(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"name"},{in:"body",key:"config"}]}]);return(n?.client??this.client).post({url:"/mcp",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}connect(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/mcp/{name}/connect",...n,...r})}disconnect(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/mcp/{name}/disconnect",...n,...r})}_auth;get auth(){return this._auth??=new Xn({client:this.client})}},Qn=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/project",...n,...r})}current(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/project/current",...n,...r})}initGit(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/project/git/init",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"name"},{in:"body",key:"icon"},{in:"body",key:"commands"}]}]);return(n?.client??this.client).patch({url:"/project/{projectID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}directories(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/project/{projectID}/directories",...n,...r})}},Yn=class extends w{shells(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/pty/shells",...n,...r})}list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/pty",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"command"},{in:"body",key:"args"},{in:"body",key:"cwd"},{in:"body",key:"title"},{in:"body",key:"env"}]}]);return(n?.client??this.client).post({url:"/pty",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}remove(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/pty/{ptyID}",...n,...r})}get(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/pty/{ptyID}",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"title"},{in:"body",key:"size"}]}]);return(n?.client??this.client).put({url:"/pty/{ptyID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}connectToken(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/pty/{ptyID}/connect-token",...n,...r})}connect(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"cursor"},{in:"query",key:"ticket"}]}]);return(n?.client??this.client).get({url:"/pty/{ptyID}/connect",...n,...r})}},Zn=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/question",...n,...r})}reply(t,n){let r=g([t],[{args:[{in:"path",key:"requestID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"answers"}]}]);return(n?.client??this.client).post({url:"/question/{requestID}/reply",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}reject(t,n){let r=g([t],[{args:[{in:"path",key:"requestID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/question/{requestID}/reject",...n,...r})}},er=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/permission",...n,...r})}reply(t,n){let r=g([t],[{args:[{in:"path",key:"requestID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"reply"},{in:"body",key:"message"}]}]);return(n?.client??this.client).post({url:"/permission/{requestID}/reply",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}respond(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"permissionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"response"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/permissions/{permissionID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},tr=class extends w{authorize(t,n){let r=g([t],[{args:[{in:"path",key:"providerID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"method"},{in:"body",key:"inputs"}]}]);return(n?.client??this.client).post({url:"/provider/{providerID}/oauth/authorize",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}callback(t,n){let r=g([t],[{args:[{in:"path",key:"providerID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"method"},{in:"body",key:"code"}]}]);return(n?.client??this.client).post({url:"/provider/{providerID}/oauth/callback",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},nr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/provider",...n,...r})}auth(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/provider/auth",...n,...r})}_oauth;get oauth(){return this._oauth??=new tr({client:this.client})}},rr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"scope"},{in:"query",key:"path"},{in:"query",key:"roots"},{in:"query",key:"start"},{in:"query",key:"search"},{in:"query",key:"limit"}]}]);return(n?.client??this.client).get({url:"/session",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"parentID"},{in:"body",key:"title"},{in:"body",key:"agent"},{in:"body",key:"model"},{in:"body",key:"metadata"},{in:"body",key:"permission"},{in:"body",key:"workspaceID"}]}]);return(n?.client??this.client).post({url:"/session",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/session/status",...n,...r})}delete(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/session/{sessionID}",...n,...r})}get(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"title"},{in:"body",key:"metadata"},{in:"body",key:"permission"},{in:"body",key:"time"}]}]);return(n?.client??this.client).patch({url:"/session/{sessionID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}children(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}/children",...n,...r})}todo(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}/todo",...n,...r})}diff(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"messageID"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}/diff",...n,...r})}messages(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"limit"},{in:"query",key:"before"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}/message",...n,...r})}prompt(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"},{in:"body",key:"model"},{in:"body",key:"agent"},{in:"body",key:"noReply"},{in:"body",key:"tools"},{in:"body",key:"format"},{in:"body",key:"system"},{in:"body",key:"variant"},{in:"body",key:"parts"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/message",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}deleteMessage(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"messageID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/session/{sessionID}/message/{messageID}",...n,...r})}message(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"messageID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}/message/{messageID}",...n,...r})}fork(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/fork",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}abort(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/abort",...n,...r})}init(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"modelID"},{in:"body",key:"providerID"},{in:"body",key:"messageID"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/init",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}unshare(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/session/{sessionID}/share",...n,...r})}share(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/share",...n,...r})}summarize(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"providerID"},{in:"body",key:"modelID"},{in:"body",key:"auto"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/summarize",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}promptAsync(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"},{in:"body",key:"model"},{in:"body",key:"agent"},{in:"body",key:"noReply"},{in:"body",key:"tools"},{in:"body",key:"format"},{in:"body",key:"system"},{in:"body",key:"variant"},{in:"body",key:"parts"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/prompt_async",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}command(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"},{in:"body",key:"agent"},{in:"body",key:"model"},{in:"body",key:"arguments"},{in:"body",key:"command"},{in:"body",key:"variant"},{in:"body",key:"parts"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/command",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}shell(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"},{in:"body",key:"agent"},{in:"body",key:"model"},{in:"body",key:"command"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/shell",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}revert(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"},{in:"body",key:"partID"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/revert",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}unrevert(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/unrevert",...n,...r})}},sr=class extends w{delete(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"messageID"},{in:"path",key:"partID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/session/{sessionID}/message/{messageID}/part/{partID}",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"messageID"},{in:"path",key:"partID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"part",map:"body"}]}]);return(n?.client??this.client).patch({url:"/session/{sessionID}/message/{messageID}/part/{partID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},ir=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"body",map:"body"}]}]);return(n?.client??this.client).post({url:"/sync/history",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},or=class extends w{start(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/sync/start",...n,...r})}replay(t,n){let r=g([t],[{args:[{in:"query",key:"query_directory",map:"directory"},{in:"query",key:"workspace"},{in:"body",key:"body_directory",map:"directory"},{in:"body",key:"events"}]}]);return(n?.client??this.client).post({url:"/sync/replay",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}steal(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/sync/steal",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}_history;get history(){return this._history??=new ir({client:this.client})}},ar=class extends w{next(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/tui/control/next",...n,...r})}response(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"body",map:"body"}]}]);return(n?.client??this.client).post({url:"/tui/control/response",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},cr=class extends w{appendPrompt(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"text"}]}]);return(n?.client??this.client).post({url:"/tui/append-prompt",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}openHelp(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/open-help",...n,...r})}openSessions(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/open-sessions",...n,...r})}openThemes(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/open-themes",...n,...r})}openModels(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/open-models",...n,...r})}submitPrompt(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/submit-prompt",...n,...r})}clearPrompt(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/clear-prompt",...n,...r})}executeCommand(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"command"}]}]);return(n?.client??this.client).post({url:"/tui/execute-command",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}showToast(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"title"},{in:"body",key:"message"},{in:"body",key:"variant"},{in:"body",key:"duration"}]}]);return(n?.client??this.client).post({url:"/tui/show-toast",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}publish(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"body",map:"body"}]}]);return(n?.client??this.client).post({url:"/tui/publish",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}selectSession(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/tui/select-session",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}_control;get control(){return this._control??=new ar({client:this.client})}},lr=class extends w{get(t){return(t?.client??this.client).get({url:"/api/health",...t})}},ur=class extends w{get(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/location",...n,...r})}},pr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/agent",...n,...r})}},dr=class extends w{stage(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"body",key:"messageID"},{in:"body",key:"files"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/revert/stage",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}clear(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/revert/clear",...n,...r})}commit(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/revert/commit",...n,...r})}},gr=class extends w{list(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/permission",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"body",key:"id"},{in:"body",key:"action"},{in:"body",key:"resources"},{in:"body",key:"save"},{in:"body",key:"metadata"},{in:"body",key:"source"},{in:"body",key:"agent"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/permission",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}get(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"requestID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/permission/{requestID}",...n,...r})}reply(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"requestID"},{in:"body",key:"reply"},{in:"body",key:"message"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/permission/{requestID}/reply",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},mr=class extends w{list(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/question",...n,...r})}reply(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"requestID"},{key:"questionV2Reply",map:"body"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/question/{requestID}/reply",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}reject(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"requestID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/question/{requestID}/reject",...n,...r})}},fr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"workspace"},{in:"query",key:"limit"},{in:"query",key:"order"},{in:"query",key:"search"},{in:"query",key:"directory"},{in:"query",key:"project"},{in:"query",key:"subpath"},{in:"query",key:"cursor"}]}]);return(n?.client??this.client).get({url:"/api/session",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"body",key:"id"},{in:"body",key:"agent"},{in:"body",key:"model"},{in:"body",key:"location"}]}]);return(n?.client??this.client).post({url:"/api/session",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}active(t){return(t?.client??this.client).get({url:"/api/session/active",...t})}get(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}",...n,...r})}switchAgent(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"body",key:"agent"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/agent",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}switchModel(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"body",key:"model"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/model",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}prompt(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"body",key:"id"},{in:"body",key:"prompt"},{in:"body",key:"delivery"},{in:"body",key:"resume"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/prompt",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}compact(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/compact",...n,...r})}wait(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/wait",...n,...r})}context(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/context",...n,...r})}history(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"limit"},{in:"query",key:"after"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/history",...n,...r})}events(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"after"}]}]);return(n?.client??this.client).sse.get({url:"/api/session/{sessionID}/event",...n,...r})}interrupt(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/interrupt",...n,...r})}message(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"messageID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/message/{messageID}",...n,...r})}messages(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"limit"},{in:"query",key:"order"},{in:"query",key:"cursor"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/message",...n,...r})}_revert;get revert(){return this._revert??=new dr({client:this.client})}_permission;get permission(){return this._permission??=new gr({client:this.client})}_question;get question(){return this._question??=new mr({client:this.client})}},yr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/model",...n,...r})}},hr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/provider",...n,...r})}get(t,n){let r=g([t],[{args:[{in:"path",key:"providerID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/provider/{providerID}",...n,...r})}},br=class extends w{key(t,n){let r=g([t],[{args:[{in:"path",key:"integrationID"},{in:"query",key:"location"},{in:"body",key:"key"},{in:"body",key:"label"}]}]);return(n?.client??this.client).post({url:"/api/integration/{integrationID}/connect/key",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}oauth(t,n){let r=g([t],[{args:[{in:"path",key:"integrationID"},{in:"query",key:"location"},{in:"body",key:"methodID"},{in:"body",key:"inputs"},{in:"body",key:"label"}]}]);return(n?.client??this.client).post({url:"/api/integration/{integrationID}/connect/oauth",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},xr=class extends w{cancel(t,n){let r=g([t],[{args:[{in:"path",key:"attemptID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).delete({url:"/api/integration/attempt/{attemptID}",...n,...r})}status(t,n){let r=g([t],[{args:[{in:"path",key:"attemptID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/integration/attempt/{attemptID}",...n,...r})}complete(t,n){let r=g([t],[{args:[{in:"path",key:"attemptID"},{in:"query",key:"location"},{in:"body",key:"code"}]}]);return(n?.client??this.client).post({url:"/api/integration/attempt/{attemptID}/complete",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},_r=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/integration",...n,...r})}get(t,n){let r=g([t],[{args:[{in:"path",key:"integrationID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/integration/{integrationID}",...n,...r})}_connect;get connect(){return this._connect??=new br({client:this.client})}_attempt;get attempt(){return this._attempt??=new xr({client:this.client})}},Pr=class extends w{remove(t,n){let r=g([t],[{args:[{in:"path",key:"credentialID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).delete({url:"/api/credential/{credentialID}",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"credentialID"},{in:"query",key:"location"},{in:"body",key:"label"}]}]);return(n?.client??this.client).patch({url:"/api/credential/{credentialID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},kr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/permission/request",...n,...r})}},wr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"projectID"}]}]);return(n?.client??this.client).get({url:"/api/permission/saved",...n,...r})}remove(t,n){let r=g([t],[{args:[{in:"path",key:"id"}]}]);return(n?.client??this.client).delete({url:"/api/permission/saved/{id}",...n,...r})}},Sr=class extends w{_request;get request(){return this._request??=new kr({client:this.client})}_saved;get saved(){return this._saved??=new wr({client:this.client})}},vr=class extends w{read(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/fs/read/*",...n,...r})}list(t,n){let r=g([t],[{args:[{in:"query",key:"location"},{in:"query",key:"path"}]}]);return(n?.client??this.client).get({url:"/api/fs/list",...n,...r})}find(t,n){let r=g([t],[{args:[{in:"query",key:"location"},{in:"query",key:"query"},{in:"query",key:"type"},{in:"query",key:"limit"}]}]);return(n?.client??this.client).get({url:"/api/fs/find",...n,...r})}},Ar=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/command",...n,...r})}},Cr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/skill",...n,...r})}},Rr=class extends w{subscribe(t){return(t?.client??this.client).sse.get({url:"/api/event",...t})}},Tr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/pty",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"query",key:"location"},{in:"body",key:"command"},{in:"body",key:"args"},{in:"body",key:"cwd"},{in:"body",key:"title"},{in:"body",key:"env"}]}]);return(n?.client??this.client).post({url:"/api/pty",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}remove(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).delete({url:"/api/pty/{ptyID}",...n,...r})}get(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/pty/{ptyID}",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"location"},{in:"body",key:"title"},{in:"body",key:"size"}]}]);return(n?.client??this.client).put({url:"/api/pty/{ptyID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}connectToken(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).post({url:"/api/pty/{ptyID}/connect-token",...n,...r})}connect(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"location[directory]"},{in:"query",key:"location[workspace]"},{in:"query",key:"cursor"},{in:"query",key:"ticket"}]}]);return(n?.client??this.client).get({url:"/api/pty/{ptyID}/connect",...n,...r})}},Ir=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/question/request",...n,...r})}},Er=class extends w{_request;get request(){return this._request??=new Ir({client:this.client})}},jr=class extends w{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/reference",...n,...r})}},$r=class extends w{remove(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"location"},{in:"body",key:"directory"},{in:"body",key:"force"}]}]);return(n?.client??this.client).delete({url:"/experimental/project/{projectID}/copy",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}create(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"location"},{in:"body",key:"strategy"},{in:"body",key:"directory"},{in:"body",key:"name"}]}]);return(n?.client??this.client).post({url:"/experimental/project/{projectID}/copy",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}refresh(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).post({url:"/experimental/project/{projectID}/copy/refresh",...n,...r})}},Mr=class extends w{_health;get health(){return this._health??=new lr({client:this.client})}_location;get location(){return this._location??=new ur({client:this.client})}_agent;get agent(){return this._agent??=new pr({client:this.client})}_session;get session(){return this._session??=new fr({client:this.client})}_model;get model(){return this._model??=new yr({client:this.client})}_provider;get provider(){return this._provider??=new hr({client:this.client})}_integration;get integration(){return this._integration??=new _r({client:this.client})}_credential;get credential(){return this._credential??=new Pr({client:this.client})}_permission;get permission(){return this._permission??=new Sr({client:this.client})}_fs;get fs(){return this._fs??=new vr({client:this.client})}_command;get command(){return this._command??=new Ar({client:this.client})}_skill;get skill(){return this._skill??=new Cr({client:this.client})}_event;get event(){return this._event??=new Rr({client:this.client})}_pty;get pty(){return this._pty??=new Tr({client:this.client})}_question;get question(){return this._question??=new Er({client:this.client})}_reference;get reference(){return this._reference??=new jr({client:this.client})}_projectCopy;get projectCopy(){return this._projectCopy??=new $r({client:this.client})}},bt=class e extends w{static __registry=new kn;constructor(t){super(t),e.__registry.set(this,t?.key)}_auth;get auth(){return this._auth??=new wn({client:this.client})}_app;get app(){return this._app??=new Sn({client:this.client})}_experimental;get experimental(){return this._experimental??=new $n({client:this.client})}_global;get global(){return this._global??=new Dn({client:this.client})}_event;get event(){return this._event??=new On({client:this.client})}_config;get config(){return this._config??=new qn({client:this.client})}_tool;get tool(){return this._tool??=new Un({client:this.client})}_worktree;get worktree(){return this._worktree??=new Fn({client:this.client})}_find;get find(){return this._find??=new Ln({client:this.client})}_file;get file(){return this._file??=new Bn({client:this.client})}_instance;get instance(){return this._instance??=new Gn({client:this.client})}_path;get path(){return this._path??=new Nn({client:this.client})}_vcs;get vcs(){return this._vcs??=new Hn({client:this.client})}_command;get command(){return this._command??=new Wn({client:this.client})}_lsp;get lsp(){return this._lsp??=new zn({client:this.client})}_formatter;get formatter(){return this._formatter??=new Vn({client:this.client})}_mcp;get mcp(){return this._mcp??=new Jn({client:this.client})}_project;get project(){return this._project??=new Qn({client:this.client})}_pty;get pty(){return this._pty??=new Yn({client:this.client})}_question;get question(){return this._question??=new Zn({client:this.client})}_permission;get permission(){return this._permission??=new er({client:this.client})}_provider;get provider(){return this._provider??=new nr({client:this.client})}_session;get session(){return this._session??=new rr({client:this.client})}_part;get part(){return this._part??=new sr({client:this.client})}_sync;get sync(){return this._sync??=new or({client:this.client})}_tui;get tui(){return this._tui??=new cr({client:this.client})}_v2;get v2(){return this._v2??=new Mr({client:this.client})}};function fi(e,t,n,r){if(!r?.throwOnError||e instanceof Error)return e;if(typeof e=="object"&&e!==null&&Object.keys(e).length>0){let o=e,u=typeof o.data?.message=="string"&&o.data.message||typeof o.message=="string"&&o.message||typeof o.name=="string"&&o.name||mi(n,t);return new Error(u,{cause:{body:e,status:t?.status}})}if(typeof e=="string"&&e.length>0)return new Error(e,{cause:{body:e,status:t?.status}});let s=t?"(empty response body)":"network error (no response)";return new Error(`opencode server ${mi(n,t)}: ${s}`,{cause:{body:e,status:t?.status}})}function mi(e,t){let n=e?.method??"?",r=e?.url??"?",s=t?.status,o=t?.statusText;return`${n} ${r}${s?" \u2192 "+s:""}${o?" "+o:""}`}function gg(e,t,n){if(e)return t&&(e===t||n&&e===n(t))?t:e}function mg(e,t){if(e.method!=="GET"&&e.method!=="HEAD")return e;let n=new URL(e.url),r=!1;for(let[o,u]of[["x-opencode-directory","directory"],["x-opencode-workspace","workspace"]]){let p=gg(e.headers.get(o),u==="directory"?t.directory:t.workspace,u==="directory"?encodeURIComponent:void 0);if(p){for(let d of n.pathname.startsWith("/api/")?[u,`location[${u}]`]:[u])n.searchParams.has(d)||n.searchParams.set(d,p);r=!0}}if(!r)return e;let s=new Request(n,e);return s.headers.delete("x-opencode-directory"),s.headers.delete("x-opencode-workspace"),s}function Dr(e){e?.fetch||(e={...e,fetch:r=>(r.timeout=!1,fetch(r))}),e?.directory&&(e.headers={...e.headers,"x-opencode-directory":encodeURIComponent(e.directory)}),e?.experimental_workspaceID&&(e.headers={...e.headers,"x-opencode-workspace":e.experimental_workspaceID});let t=He(e);return t.interceptors.request.use(n=>mg(n,{directory:e?.directory,workspace:e?.experimental_workspaceID})),t.interceptors.response.use(n=>{if(n.headers.get("content-type")==="text/html")throw new Error("Request is not supported by this version of OpenCode Server (Server responded with text/html)");return n}),t.interceptors.error.use(fi),new bt({client:t})}var fg=new Set(["api","cli","mobile","web"]);function xt(e){let t=e?.trim().toLowerCase();return t&&fg.has(t)?t:null}function yg(e){return new Promise(t=>setTimeout(t,e))}async function yi(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,u=null;for(let p=0;p<r;p++)if(p>0&&(o&&n?.(),s>0&&await yg(s)),u=await e(),u)return u;return u}var hg=12e4;function bg(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Or(e,t,n=hg){let r=e instanceof Request?e.signal:t?.signal;if(bg(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function qr(e,t,n,r){let s=new Headers(e instanceof Request?e.headers:void 0);t?.headers&&new Headers(t.headers).forEach((u,p)=>{s.set(p,u)}),n&&!s.has("Authorization")&&s.set("Authorization",`Bearer ${n}`);let o=xt(r);return o&&!s.has("X-Kortix-Client")&&s.set("X-Kortix-Client",o),s}function hi(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}async function Ur(){return O().getToken()}async function ae(e){return yi(()=>O().getToken(),e,_t)}function _t(){}function Ub(e){}function Fb(e){}async function We(){return Ur()}async function bi(e){return ae(e)}function xi(e,t,n,r){let s=O().fetch??fetch;if(e instanceof Request){let o=new Request(e,{headers:n,...r?{signal:r}:{}});return s(o)}return s(e,{...t,headers:n,...r?{signal:r}:{}})}async function U(e,t,n){let{retryOnAuthError:r=!0,timeoutMs:s}=n??{},o=await bi();if(!o)return hi();let u=O().clientSource,p=qr(e,t,o,u),d=s===void 0?Or(e,t):Or(e,t,s),f=await xi(e,t,p,d);if(f.status===401&&r&&o){_t();let m=await bi({attempts:2,baseDelayMs:200});if(m&&m!==o){let h=qr(e,t,m,u);return xi(e,t,h,d)}}return f}var Re={url:null,sandboxId:null,dbSandboxId:null,version:0},xg=new Set;function _i(e,t=null,n=null){if(!(Re.url===e&&Re.sandboxId===t&&Re.dbSandboxId===n)){Re={url:e,sandboxId:t,dbSandboxId:n,version:Re.version+1};for(let r of xg)r()}}function Pi(){return Re.url}function _g(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function ze(){return _g(O().backendUrl||"http://localhost:8008/v1")}function ki(){let e=O().sandboxId;return e?`${ze()}/p/${e}/8000`:""}function Pg(e){return`${ze()}/p/${e}/8000`}function Pt(e){return Pg(e)}var S=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let u=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:u,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},Te=class extends S{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},be=class e extends Error{status;detail;constructor(t,n,r){super(r||n.message||`Billing Error: ${t}`),this.name="BillingError",this.status=t,this.detail=n,Object.setPrototypeOf(this,e.prototype)}},Ie=class e extends Error{status;detail;constructor(t=431,n,r){let s="Request headers are too large",o="Try uploading files one at a time, or reduce the number of files in a single request.";super(r||n?.message||s),this.name="RequestTooLargeError",this.status=t,this.detail={message:n?.message||s,suggestion:n?.suggestion||o},Object.setPrototypeOf(this,e.prototype)}},Fr="feature_disabled";function wi(e){if(!(e instanceof S)||e.status!==403||e.code!==Fr)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Si(e){let t=wi(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function vi(e){let t=wi(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function Ee(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 be(t,{message:r?.message||e.message||"Billing error",...r})}function Ai(e){return e instanceof be}function Ci(e){if(!(e instanceof be))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."}}var kg="X-Kortix-Impersonate",Br="kortix.impersonation",xe=null,kt=!1,Lr=new Set;function Gr(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function wg(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 Sg(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 Ri(){for(let e of Lr)try{e()}catch{}}function vg(){return kt||(kt=!0,xe=Sg(Gr()?.getItem(Br)??null)),xe&&!wg(xe)?(Ti(),null):xe}function Hb(e){if(kt=!0,!e){Ti();return}xe=e;try{Gr()?.setItem(Br,JSON.stringify(e))}catch{}Ri()}function Ti(){kt=!0;let e=xe!==null;xe=null;try{Gr()?.removeItem(Br)}catch{}e&&Ri()}function Wb(e){return Lr.add(e),()=>{Lr.delete(e)}}var Ag=/(^|\/)admin\/(api|analytics)(\/|$)/;function Cg(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Ag.test(t)}function Nr(e){if(e!==void 0&&!Cg(e))return{};let t=vg();return t?{[kg]:t.grantId}:{}}function _e(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function ce(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(_e())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function wt(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(_e())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var te=()=>O().backendUrl||"",Rg="feature_not_supported",Tg="model_not_servable",Ig="provision_in_flight",Ii="request_deadline",Eg=/^Request exceeded the \d+s server processing deadline$/,jg=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ii||Eg.test(n),$g=new Set([502,503,504]),Mg=e=>$g.has(e),Dg=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Og=2,Kr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted"),St=!1;function tx(e){St=e}function nx(){return St}async function le(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...u}=t,p=new AbortController,d=p,f=()=>d.abort();u.signal?.addEventListener("abort",f,{once:!0});let m=null,h=!1,P=!1;try{if(u.signal?.aborted)throw _e();m=setTimeout(()=>{!h&&!p.signal.aborted&&(h=!0,P=!0,p.abort())},s);let x=await ce(ae(),p.signal),_=u.body instanceof FormData,v={};_||(v["Content-Type"]="application/json"),Object.assign(v,u.headers);let M=xt(O().clientSource),$=Object.keys(v).some(R=>R.toLowerCase()==="x-kortix-client");if(M&&!$&&(v["X-Kortix-Client"]=M),St&&(v["x-kortix-admin-bypass"]="1"),Object.assign(v,Nr(e)),x)v.Authorization=`Bearer ${x}`;else return{error:new Te,success:!1};let l=Dg(u.method),y=l?Og+1:1,a;for(let R=0;R<y;R++){R>0&&await wt(250*2**(R-1),u.signal??void 0);let k=R===0?p:new AbortController;d=k,u.signal?.aborted&&k.abort(),R>0&&(m=setTimeout(()=>{P=!0,k.abort()},s));try{let j=O().fetch??fetch;a=await ce(j(e,{...u,headers:v,signal:k.signal,credentials:u.credentials??"omit"}),k.signal)}catch(j){if(m&&(clearTimeout(m),m=null),Kr(j)||R===y-1)throw j;continue}if(!(l&&Mg(a.status)&&R<y-1)){!o&&m&&(clearTimeout(m),m=null);break}try{await ce(a.arrayBuffer(),k.signal)}catch(j){if(Kr(j))throw j}finally{m&&(clearTimeout(m),m=null)}}if(!a.ok){let R=`HTTP ${a.status}: ${a.statusText}`,k=null;try{k=await ce(a.json(),d.signal),typeof k.message=="string"?R=k.message:k.error&&typeof k.error=="string"?R=k.error:typeof k.detail=="string"?R=k.detail:typeof k.detail?.message=="string"?R=k.detail.message:typeof k.reason=="string"&&(R=k.reason)}catch{}if(d.signal.aborted)throw _e();let F=jg(a.status,k,R),j=new S(R,{status:a.status,response:a,details:k||void 0,data:k,detail:k?.detail,code:F?Ii:k?.code||k?.error_code||k?.detail?.error_code||a.status.toString()});if(a.status===402&&(j=Ee(j)),a.status===403&&k?.code==="account_mfa_required"&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent("kortix:mfa-required"))}catch{}a.status===431&&(j=new Ie(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."}));let K=a.status===501&&k?.code===Rg,D=a.status===409&&k?.code===Tg,b=a.status===409&&k?.code===Ig;return n&&!K&&!D&&!b&&!F&&O().onError?.(j,r),{error:j,success:!1}}let A,I=a.headers.get("content-type");return I?.includes("application/json")?A=await ce(a.json(),d.signal):I?.includes("text/")?A=await ce(a.text(),d.signal):A=await ce(a.blob(),d.signal),{data:A,success:!0,headers:a.headers}}catch(x){m&&(clearTimeout(m),m=null);let _=Kr(x);_&&(h=!0);let v;if(_){if(!P)return{error:new S("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let M=e.replace(te(),"")||e;v=new S(`Request timed out after ${Math.round(s/1e3)}s: ${M}`,{code:"TIMEOUT",url:e,endpoint:M,timeout:s})}else x instanceof Error?(v=new S(x.message,{name:x.name||"ApiError",stack:x.stack}),n&&O().onError?.(v,r)):(v=new S(String(x)),n&&O().onError?.(v,r));return{error:v,success:!1}}finally{m&&clearTimeout(m),u.signal?.removeEventListener("abort",f)}}var rx={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new S(r.message||"Database error",{code:r.code,details:r});return O().onError?.(s,t),{error:s,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new S(n.message,{name:n.name||"ApiError",stack:n.stack}):new S(String(n));return O().onError?.(r,t),{error:r,success:!1}}}};async function qg(e,t,n={}){let{timeout:r=3e4,fetch:s=fetch}=n,o=await ae(),u={Accept:"text/event-stream","Content-Type":"application/json"},p=xt(O().clientSource);p&&(u["X-Kortix-Client"]=p),St&&(u["x-kortix-admin-bypass"]="1"),Object.assign(u,Nr(e)),o&&(u.Authorization=`Bearer ${o}`);let d=new AbortController,f=setTimeout(()=>d.abort(),r);try{return await s(`${te()}${e}`,{method:"POST",headers:u,body:JSON.stringify(t),signal:d.signal,credentials:"omit"})}finally{clearTimeout(f)}}var i={putRaw:(e,t,n)=>le(`${te()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>le(`${te()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>le(`${te()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>le(`${te()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>le(`${te()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>le(`${te()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],le(`${te()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],le(`${te()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:qg};var vt=new Map,Hr=new Map;function Wr(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Ei(e){return vt.get(Wr(e))??null}function ji(e){return vt.has(Wr(e))}async function At(e){let t=Wr(e),n=vt.get(t);if(n!==void 0)return n;let r=Hr.get(t);if(r)return r;let s=(async()=>{try{let o=await i.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let u=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return vt.set(t,u),u}catch{return null}finally{Hr.delete(t)}})();return Hr.set(t,s),s}function $i(e){let{apiBaseUrl:t}=e;return ji(t)||At(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:Ei(t)}}function re(){let e=Pi();return e||(O().billingEnabled??!1?"":ki())}async function zr(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Vr(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function Mi(e){let t=Vr(e),n=await U(`${t}/env`);if(!n.ok)throw new Error(await zr(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Di(e,t,n){let r=Vr(e),s=await U(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await zr(s,"Failed to save secret"))}async function Oi(e,t){let n=Vr(e),r=await U(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await zr(r,"Failed to delete secret"))}var Ug={list:Mi,set:Di,delete:Oi};async function Fg(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await U(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}function ue(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}async function Ct(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function Ve(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return ue(e)}async function qi(e){let t=Ve(e),n=await U(`${t}/kortix/pty`);if(!n.ok)throw new Error(await Ct(n,"Failed to list terminals"));return n.json()}async function Ui(e,t){let n=Ve(e),r=await U(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await Ct(r,"Failed to create terminal"));return r.json()}async function Fi(e,t,n){let r=Ve(e),s=await U(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await Ct(s,"Failed to update terminal"));return s.json()}async function Li(e,t){let n=Ve(e),r=await U(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Ct(r,"Failed to remove terminal"))}async function Bi(e,t,n){let r=Ve(t),o=`${(()=>{try{let f=new URL(r);return f.protocol==="https:"?f.protocol="wss:":f.protocol==="http:"&&(f.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&f.protocol==="ws:"&&(f.protocol="wss:"),ue(f.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,u=new URLSearchParams,p=await We();p&&u.set("token",p),n?.wake&&u.set("wake","1");let d=u.toString();return d?`${o}${o.includes("?")?"&":"?"}${d}`:o}var Lg={list:qi,create:Ui,update:Fi,remove:Li,webSocketUrl:Bi};async function E(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await U(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),u=await o.text(),p={};try{p=u?JSON.parse(u):{}}catch{p={}}if(!o.ok)throw new Error(p?.error||p?.message||p?.details||u.slice(0,200)||`Request failed with ${o.status}`);return p}async function vx(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 E(e,`/kortix/tasks${r}`)}async function Ax(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function Cx(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function Rx(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function Tx(e,t){return E(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function Ix(e,t,n){return E(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function Ex(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function jx(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function $x(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Mx(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return E(e,`/kortix/tickets${n}`)}async function Dx(e,t){return E(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function Ox(e,t){return E(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function qx(e,t){return E(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function Ux(e,t,n){return E(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function Fx(e,t,n){return E(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function Lx(e,t,n){return E(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function Bx(e,t,n){return E(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function Gx(e,t,n){return E(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function Nx(e,t){return E(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Kx(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function Hx(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function Wx(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function zx(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function Vx(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function Xx(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function Jx(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function Qx(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function Yx(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function Zx(e,t,n,r){return E(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function e_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function t_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function n_(e,t,n=200){return E(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function r_(e){return E(e,"/kortix/projects")}async function s_(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function i_(e,t){return E(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function o_(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function a_(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function c_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function l_(e,t,n="all"){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function u_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function p_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function d_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function g_(e,t,n,r){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function m_(e,t,n,r){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function f_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function y_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function h_(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function b_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function x_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function __(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function P_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var Bg=1e4,Gg={retryOnAuthError:!1};function je(e,t,n){return E(e,t,{signal:AbortSignal.timeout(Bg),...n},Gg)}async function k_(e,t=!1){return(await je(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function w_(e){return(await je(e,"/kortix/services/templates")).templates??[]}async function S_(e,t){return(await je(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function v_(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return je(e,s,{method:r?"DELETE":"POST"})}async function A_(e,t){return je(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function C_(e,t){return je(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Rt=new Map,Xe=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function Pe(){let e=re();if(!e)throw new Xe;return pe(e)}function pe(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Rt.get(e);if(t)return t;if(!hn())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=Dr({baseUrl:e,fetch:U});return Rt.set(e,n),n}function M_(e){Rt.delete(e)}function D_(){Rt.clear()}var Tt=new Map;function O_(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=Tt.get(e);if(t)return t;let n=Dr({baseUrl:e,fetch});return Tt.set(e,n),n}function q_(e){Tt.delete(e)}function U_(){Tt.clear()}async function Ng(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 F_(e){let t=re();if(!t)throw new S("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await U(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new S(`System reload failed (${r.status}): ${await Ng(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new S(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let u;try{u=await r.json()}catch(d){throw new S(`System reload returned malformed JSON from ${n}: ${d instanceof Error?d.message:String(d)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let p=u===!0||typeof u=="object"&&u!==null&&u.ok===!0;return{success:p,mode:e,steps:p?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:p?[]:[`the sandbox did not confirm the reload (${n})`]}}function Hi(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new S(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function $e(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 X(e){let t=(e??re()).trim();if(!t)throw new Xe;return t}async function jt(e,t){let n=await U(`${X(t)}${e}`);if(!n.ok)throw new S(await $e(n),{status:n.status,response:n});return n.json()}var Qr=["/workspace","/tmp","/home","/opt"],Kg=Qr.filter(e=>e!=="/workspace");function Wi(e){return Qr.some(t=>e===t||e.startsWith(`${t}/`))}function Et(e){return Wi(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function Me(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(Kg.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var zi=Me;async function $t(e,t){let n=X(t),r=Me(e)||".";return(await jt(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function Ye(e,t){let n=X(t),r=Me(e),s=await U(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!s.ok)throw new S(await $e(s),{status:s.status,response:s});return s.json()}async function Hg(e,t,n){let r=X(n),s=Me(e),o=await U(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new S(await $e(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new S("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let u=await o.blob();return t&&(!u.type||u.type==="application/octet-stream")?new Blob([u],{type:t}):u}async function Ze(e,t){let n=X(t);try{return await Hg(e,void 0,n)}catch{}let r=await Ye(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}async function Mt(e){return jt("/file/status",X(e))}async function Dt(e,t,n){let r=X(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),jt(`/find/file?${s.toString()}`,r)}async function Ot(e,t){let n=X(t);return(await jt(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var Je=[400,1200],Wg=e=>e===408||e===429||e===502||e===503||e===504,Gi=e=>new Promise(t=>setTimeout(t,e));function zg(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Xr=3e4,Vg=15*6e4,Xg=256;function Qe(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Xr;let t=Xr+e/Xg;return Math.min(Vg,Math.max(Xr,Math.round(t)))}async function Jg(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 It(e,t){let n;for(let s=0;s<=Je.length;s++){let o;try{o=await t(e())}catch(p){if(n=p,zg(p)||s===Je.length)break;await Gi(Je[s]);continue}if(o.ok)return o.json();let u=await Jg(o);if(n=new S(`Upload failed (${o.status}): ${u}`,{status:o.status,response:o}),!Wg(o.status)||s===Je.length)throw n;await Gi(Je[s])}if(n instanceof S)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new S(`Upload failed: ${r}`)}var Jr=64*1024;function Ni(e,t){try{e?.onProgress?.(t)}catch{}}function Ki(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function Qg(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function et(e,t,n,r,s){let o=typeof r=="string"?r:void 0,u=typeof r=="string"?s:r,p=X(o),d=Qe(e.size),f=n||(e instanceof File?e.name:"")||"";if(e.size<=Jr){let x=await It(()=>Ki(e,t,f),_=>U(`${p}/file/upload`,{method:"POST",body:_},{timeoutMs:d}));return Ni(u,{loadedBytes:e.size,totalBytes:e.size}),x}let h=(await It(()=>Ki(new Blob([],{type:e.type}),t,f),x=>U(`${p}/file/upload`,{method:"POST",body:x},{timeoutMs:Qe(0)})))[0]?.path;if(!h)throw new S("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let P=Qg(h);if(!P.name)throw new S(`Upload reservation returned an invalid file path: ${h}`,{code:"UPLOAD_INVALID_PATH"});try{for(let x=0;x<e.size;x+=Jr){let _=Math.min(e.size,x+Jr),v=e.slice(x,_,e.type),M=await It(()=>{let $=new FormData;return P.parent&&$.append("path",P.parent),$.append("filename",P.name),$.append("first",x===0?"true":"false"),$.append("offset",String(x)),$.append("file",v,P.name),$},$=>U(`${p}/file/append`,{method:"POST",body:$},{timeoutMs:Qe(v.size)}));if(M.path!==h||M.size!==_)throw new S(`Upload verification failed for ${h}: expected ${_} bytes, received ${M.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Ni(u,{loadedBytes:_,totalBytes:e.size})}}catch(x){throw await we(h,p).catch(()=>{}),x}return[{path:h,size:e.size}]}function Yg(e,t,n){let r=X(n),s=Qe(t.size);return It(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>U(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}async function qt(e,t){let n=X(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),u=o.pop()||"untitled",p=o.join("/")||"/workspace",d=await tt(`${p}/${u}`,new Blob([],{type:"application/octet-stream"}),n);return[{path:d.path,size:d.bytes}]}async function Ut(e,t,n){let r=X(n);return Yg(t,await Ze(e,r),r)}function Zg(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function em(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function tm(e){return e.slice(e.lastIndexOf("/")+1)}function nm(){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 tt(e,t,n){let r=X(n),s=Et(Zg(e.trim())),o=tm(s);if(!o)throw new S(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let u=em(s);await nt(u,r).catch(()=>{});let p=nm(),d=await et(t,u,`.${o}.kortix-write-${p}`,r),f=d[0]?.path;if(!f)throw new S(`Upload returned no file for ${s}`,{code:"UPLOAD_NO_RESULT"});let m=Et(f),h=`${s}.kortix-write-backup-${p}`,P=!1;try{await ke(s,h,r),P=!0}catch{}try{await ke(m,s,r)}catch(_){throw P&&await ke(h,s,r).catch(()=>{}),await we(m,r).catch(()=>{}),_}P&&await we(h,r).catch(()=>{});let x=d[0]?.size;return{path:s,bytes:typeof x=="number"?x:t.size}}async function we(e,t){let n=await U(`${X(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new S(`Delete failed (${n.status}): ${await $e(n)}`,{status:n.status,response:n});return n.json()}async function nt(e,t){let n=await U(`${X(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new S(`Mkdir failed (${n.status}): ${await $e(n)}`,{status:n.status,response:n});return n.json()}async function ke(e,t,n){let r=await U(`${X(n)}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:e,to:t})});if(!r.ok)throw new S(`Rename failed (${r.status}): ${await $e(r)}`,{status:r.status,response:r});return r.json()}async function Vi(){return Hi(await Pe().project.current())}async function Yr(){return Hi(await Pe().global.health())}async function Xi(){try{return(await Yr()).healthy===!0}catch{return!1}}var rm={list:$t,read:Ye,readBlob:Ze,status:Mt,findFiles:Dt,findText:Ot,upload:et,write:tt,create:qt,copy:Ut,remove:we,mkdir:nt,rename:ke,currentProject:Vi,health:Yr,isReachable:Xi,toDaemonPath:Me,toSandboxAbsolutePath:Et,toWorkspaceRelative:zi};var Zr=52428800,im=104857600,Ji=20;function c(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function es(e){return e.replace(/\/v1\/?$/,"")}async function De(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=es(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}}var Lt=e=>`/projects/${encodeURIComponent(e)}/attachments`,Bt={showErrors:!1,deadlineCoversBody:!0},Qi=3e4,om=12e4,am=6e4,cm=5*6e4,lm=6e4,um=6e4;function Ft(){return new S("Request aborted",{name:"AbortError",code:"ABORTED"})}function rt(e){if(e?.aborted)throw Ft()}function pm(e){return!(e instanceof S)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function st(e,t,n=!1){let r;for(let s=0;;s++){rt(t);try{return await e()}catch(o){let u=n&&o instanceof S&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(pm(o)||u))throw o;r??=Date.now()+(n?cm:am);let p=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+p>=r)throw o;try{await wt(p,t)}catch{throw rt(t),o}}}}function dm(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function ts(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,u=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&dm(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!u)throw new Error("Invalid attachment upload handle");return e}async function Yi(e,t,n,r){return c(await i.post(Lt(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Bt,signal:n,timeout:Qi}),"Failed to start attachment upload")}async function Zi(e,t,n,r){let s=ts({...await st(()=>Yi(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function eo(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new S(r,{status:e,details:n,code:String(n?.statusCode??e)})}function gm(e){if(!(e instanceof S))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function mm(e,t,n,r){return new Promise((s,o)=>{let u=new e,p=0,d=!1,f,m=x=>{d||(d=!0,f&&clearTimeout(f),r.signal?.removeEventListener("abort",P),x?o(x):s())},h=()=>{f&&clearTimeout(f),f=setTimeout(()=>{m(new S("Attachment upload stalled",{code:"TIMEOUT"})),u.abort()},lm)},P=()=>{m(Ft()),u.abort()};u.open(t.method,t.url);for(let[x,_]of Object.entries(t.headers))u.setRequestHeader(x,_);u.upload.onprogress=x=>{h(),p=Math.min(x.loaded,n.size),r.onProgress?.(p,n.size)},u.onload=()=>{u.status>=200&&u.status<300?(p<n.size&&r.onProgress?.(n.size,n.size),m()):m(eo(u.status,u.responseText))},u.onerror=()=>m(new S("Network error during attachment upload",{name:"TypeError"})),u.onabort=()=>m(Ft()),r.signal?.addEventListener("abort",P,{once:!0}),h(),u.send(n)})}async function fm(e,t,n){let r=O().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?Ft():new S(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw eo(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function ym(e,t,n){rt(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?mm(r,e,t,n):fm(e,t,n)}async function hm(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let u=s.upload;try{await st(()=>ym(u,t,r),r.signal)}catch(p){let d=gm(p);if(d!==409){if(o||!(d===400||d===401||d===403))throw p;o=!0,s=await Zi(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return to(e,t,s,r)}async function to(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${Lt(e)}/${encodeURIComponent(n.attachment_id)}`,u=n;for(;u.received_bytes<t.size;){rt(r.signal);let p=u.received_bytes,d=Math.min(p+s,t.size),f=t.slice(p,d),m=await st(async()=>c(await i.putRaw(`${o}/chunks/${p/s}`,f,{...Bt,signal:r.signal,timeout:Qi}),"Failed to upload attachment chunk"),r.signal);if(m.size!==t.size||m.received_bytes!==d)throw new Error("Invalid attachment chunk acknowledgment");u={...u,received_bytes:d},r.onUpload?.(u),r.onProgress?.(d,t.size)}return u}async function Gt(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");rt(n.signal);let r=n.resume?ts({...n.resume},t):ts({...await st(()=>Yi(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()<um&&(r=await Zi(e,t,r,n)),r=r.upload.kind==="direct"?await hm(e,t,r,n):await to(e,t,r,n)),n.onProcessing?.();let s=`${Lt(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await st(async()=>c(await i.post(`${s}/complete`,{},{...Bt,signal:n.signal,timeout:om}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof S&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Oe(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await i.delete(`${Lt(e)}/${encodeURIComponent(t)}`,{...Bt,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}var bm=100,xm=0,_m=new Set(["attachment_size_mismatch","attachment_failed"]),no=()=>new S("Attachment expired. Attach the file again.",{code:"attachment_expired"});function ro(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 so(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,u=0,p=!1,d,f={attachments:[]},m=()=>[...r.values()].filter(l=>!l.handedOff);function h(){d&&clearTimeout(d);let l=m().map(({item:a})=>a);(l.length!==f.attachments.length||l.some((a,A)=>a!==f.attachments[A]))&&(f={attachments:l});let y=Math.min(...l.filter(a=>a.status==="ready").map(a=>Date.parse(a.attachment.expires_at)));Number.isFinite(y)&&!p&&(d=setTimeout(()=>{for(let a of m())a.item.status==="ready"&&Date.parse(a.item.attachment.expires_at)<=Date.now()&&(a.item={...a.item,status:"error",error:no()});h()},Math.min(2147483647,Math.max(0,y-Date.now()))),typeof d=="object"&&"unref"in d&&d.unref());for(let a of s)a();for(let a of[...o])a()}function P(){if(p)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function x(l){P();let y=m();if(y.length+l.length>20)throw new Error("A message can contain up to 20 attachments");if(l.some(A=>!Number.isSafeInteger(A)||A<=0||A>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(y.reduce((A,I)=>A+I.item.size,0)+l.reduce((A,I)=>A+I,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function _(){for(let l of r.values()){if(u>=n)break;if(l.item.status!=="pending"||!l.item.file||p&&!l.handedOff)continue;let y=l.item.file;u++;let a=++l.generation,A=new AbortController;l.abort=A,l.item={...l.item,status:"uploading",error:void 0};let I=()=>(!p||l.handedOff===!0)&&r.get(l.item.id)===l&&l.generation===a,R,k=0,F,j=()=>{F=void 0,!(!I()||l.item.status!=="uploading"||R===void 0)&&(l.item={...l.item,receivedBytes:R},R=void 0,k=Date.now(),h())},K=D=>Math.floor(D*100/l.item.size);Gt(e,y,{resume:l.upload,signal:A.signal,onUpload:D=>{l.upload=D,l.removed&&Oe(e,D.attachment_id).catch(()=>{})},onProgress:D=>{if(!I()||K(D)===K(l.item.receivedBytes)||(R=D,F))return;let b=k+bm-Date.now();if(b<=0)return j();F=setTimeout(j,b),typeof F=="object"&&"unref"in F&&F.unref()},onProcessing:()=>{F&&clearTimeout(F),F=void 0,R=void 0,I()&&(l.item={...l.item,status:"processing",receivedBytes:l.item.size},h())}}).then(D=>{I()&&(l.item={...l.item,status:"ready",attachment:ro(D),receivedBytes:D.size})}).catch(D=>{D instanceof S&&_m.has(D.code??"")&&(l.upload=void 0),I()&&(l.item={...l.item,status:D instanceof S&&D.code==="ABORTED"?"aborted":"error",error:D instanceof Error?D:new Error(String(D))})}).finally(()=>{u--,F&&clearTimeout(F),l.abort===A&&(l.abort=void 0),h(),_()})}h()}function v(l){x(l.map(a=>a.size));let y=l.map(a=>{let A=`attachment-${++xm}`;return r.set(A,{generation:0,item:{id:A,file:a,filename:a.name,mime:a.type||"application/octet-stream",size:a.size,status:"pending",receivedBytes:0}}),A});return h(),_(),y}function M(l){let y=r.get(l);!y||y.item.status==="ready"||(y.generation++,y.abort?.abort(),y.item={...y.item,status:"aborted",error:new Error("Attachment upload cancelled")},h())}function $(l,{signal:y}={}){let a=[...l];return new Promise((A,I)=>{let R=()=>{o.delete(j),y?.removeEventListener("abort",F)},k=K=>{R(),I(K)},F=()=>k(_e()),j=()=>{let K=!1;for(let b of a){let T=r.get(b);if(!T)return k(new Error("Attachment was removed before it was sent"));if(p&&!T.handedOff)return k(new Error("Attachment controller is disposed"));if(T.item.status==="error"||T.item.status==="aborted")return k(T.item.error??new Error("Attachment upload failed"));T.item.status!=="ready"&&(K=!0)}if(K)return;let D;try{D=a.map(b=>{let T=ro(r.get(b).item.attachment);return{type:"file",attachment_id:T.attachment_id,filename:T.filename,mime:T.mime}})}catch(b){return k(b instanceof Error?b:new Error(String(b)))}R(),A(D)};if(y?.aborted)return F();o.add(j),y?.addEventListener("abort",F,{once:!0}),j()})}return{add:l=>v([l])[0],addMany:v,retry(l){let y=r.get(l);if(y?.handedOff||P(),!(!y||y.item.status==="ready"||y.item.status==="uploading"||y.item.status==="processing"||y.item.status==="pending")){if(!y.item.file||y.upload&&Date.parse(y.upload.expires_at)<=Date.now())throw no();y.item={...y.item,status:"pending",error:void 0},_()}},async remove(l){let y=r.get(l);if(!y)return;y.removed=!0,y.generation++,y.abort?.abort(),r.delete(l),h(),_();let a=y.upload?.attachment_id??y.item.attachment?.attachment_id;a&&Oe(e,a).catch(()=>{})},abort:M,submit(l){if(!p){for(let y of l){let a=r.get(y);a&&(a.handedOff=!0)}h()}},reclaim(l){if(!p){for(let y of l){let a=r.get(y);a&&(a.handedOff=!1)}h()}},whenReady:$,forget(l=m().map(y=>y.item.id)){for(let y of l){let a=r.get(y);a&&(a.generation++,a.abort?.abort(),r.delete(y))}h(),_()},dispose(){if(!p){p=!0,d&&clearTimeout(d);for(let l of r.values()){if(l.handedOff)continue;l.generation++,l.abort?.abort();let y=l.upload?.attachment_id??l.item.attachment?.attachment_id;y&&e&&Oe(e,y).catch(()=>{})}s.clear(),h()}},getSnapshot:()=>f,subscribe(l){return s.add(l),()=>{s.delete(l)}}}}async function io(){return c(await i.get("/accounts"))}async function oo(e){return c(await i.post("/accounts",e))}async function ao(e){return c(await i.get(`/accounts/${e}`))}async function co(e,t){return c(await i.patch(`/accounts/${e}`,{name:t}))}async function lo(e){return c(await i.get(`/accounts/${e}/branding`))}async function uo(e,t){return c(await i.put(`/accounts/${e}/branding`,t))}async function po(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),c(await i.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function go(e,t){return c(await i.delete(`/accounts/${e}/branding/assets/${t}`))}async function mo(e){return c(await i.delete(`/accounts/${e}/branding`))}async function fo(e){return c(await i.get(`/accounts/${e}/members`))}async function yo(e,t){return c(await i.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function ho(e){return c(await i.get(`/accounts/${e}/invites`))}async function bo(e,t){return c(await i.delete(`/accounts/${e}/invites/${t}`))}async function xo(e,t){return c(await i.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function _o(e){return c(await i.get(`/account-invites/${e}`,{showErrors:!1}))}async function Po(e){return c(await i.post(`/account-invites/${e}/accept`,{}))}async function ko(e){return c(await i.post(`/account-invites/${e}/decline`,{}))}async function wo(e,t){return c(await i.delete(`/accounts/${e}/members/${t}`))}async function So(e,t,n){return c(await i.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function vo(e){return c(await i.post(`/accounts/${e}/leave`,{}))}async function cP(e){return De(e,"/v1/accounts")}async function Ao(){let e=await i.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var dP=["agent_tunnel","marketplace","connectors_api_discover","agentmail_email","teams","llm_gateway","meta_agent","apps","monitors","warm_sessions","secrets_egress","pi_worker","pooled_provider_secrets"];async function qe(){return c(await i.get("/projects"))}async function Ro(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return c(await i.get(`/projects${t}`))}async function ns(e,t){return c(await i.get(`/projects/${e}`,t))}async function To(e,t,n="write"){return c(await i.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Io(e,t){return c(await i.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Eo(e){return c(await i.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function gP(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function rs(e,t){let n=c(await i.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 ss(e,t){return c(await i.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function is(e,t){return c(await i.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function mP(e,t){return c(await i.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function jo(e){return c(await i.post("/projects",e))}async function $o(e){return c(await i.post("/projects/create-repo",e))}async function Mo(e,t={}){return c(await i.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Co=200;function Pm(e){let t=e.split(`
7
+ `);try{B=JSON.parse(W),Q=!0}catch{B=W}}Q&&(s&&await s(B),r&&(B=await r(B))),n?.({data:B,event:N,id:h,retry:v}),q.length&&(yield B)}}}finally{$.removeEventListener("abort",F),R.releaseLock()}break}catch(y){if(t?.(y),u!==void 0&&M>=u)break;let a=Math.min(v*2**(M-1),p??3e4);await P(a)}}}()}};var rg=e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},sg=e=>{switch(e){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},ig=e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},yt=({allowReserved:e,explode:t,name:n,style:r,value:s})=>{if(!t){let p=(e?s:s.map(d=>encodeURIComponent(d))).join(sg(r));switch(r){case"label":return`.${p}`;case"matrix":return`;${n}=${p}`;case"simple":return p;default:return`${n}=${p}`}}let o=rg(r),u=s.map(p=>r==="label"||r==="simple"?e?p:encodeURIComponent(p):Ce({allowReserved:e,name:n,value:p})).join(o);return r==="label"||r==="matrix"?o+u:u},Ce=({allowReserved:e,name:t,value:n})=>{if(n==null)return"";if(typeof n=="object")throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},ht=({allowReserved:e,explode:t,name:n,style:r,value:s,valueOnly:o})=>{if(s instanceof Date)return o?s.toISOString():`${n}=${s.toISOString()}`;if(r!=="deepObject"&&!t){let d=[];Object.entries(s).forEach(([m,h])=>{d=[...d,m,e?h:encodeURIComponent(h)]});let f=d.join(",");switch(r){case"form":return`${n}=${f}`;case"label":return`.${f}`;case"matrix":return`;${n}=${f}`;default:return f}}let u=ig(r),p=Object.entries(s).map(([d,f])=>Ce({allowReserved:e,name:r==="deepObject"?`${n}[${d}]`:d,value:f})).join(u);return r==="label"||r==="matrix"?u+p:p};var og=/\{[^{}]+\}/g,ag=({path:e,url:t})=>{let n=t,r=t.match(og);if(r)for(let s of r){let o=!1,u=s.substring(1,s.length-1),p="simple";u.endsWith("*")&&(o=!0,u=u.substring(0,u.length-1)),u.startsWith(".")?(u=u.substring(1),p="label"):u.startsWith(";")&&(u=u.substring(1),p="matrix");let d=e[u];if(d==null)continue;if(Array.isArray(d)){n=n.replace(s,yt({explode:o,name:u,style:p,value:d}));continue}if(typeof d=="object"){n=n.replace(s,ht({explode:o,name:u,style:p,value:d,valueOnly:!0}));continue}if(p==="matrix"){n=n.replace(s,`;${Ce({name:u,value:d})}`);continue}let f=encodeURIComponent(p==="label"?`.${d}`:d);n=n.replace(s,f)}return n},oi=({baseUrl:e,path:t,query:n,querySerializer:r,url:s})=>{let o=s.startsWith("/")?s:`/${s}`,u=(e??"")+o;t&&(u=ag({path:t,url:u}));let p=n?r(n):"";return p.startsWith("?")&&(p=p.substring(1)),p&&(u+=`?${p}`),u};function xn(e){let t=e.body!==void 0;if(t&&e.bodySerializer)return"serializedBody"in e?e.serializedBody!==void 0&&e.serializedBody!==""?e.serializedBody:null:e.body!==""?e.body:null;if(t)return e.body}var ai=async(e,t)=>{let n=typeof t=="function"?await t(e):t;if(n)return e.scheme==="bearer"?`Bearer ${n}`:e.scheme==="basic"?`Basic ${btoa(n)}`:n};var _n={bodySerializer:e=>JSON.stringify(e,(t,n)=>typeof n=="bigint"?n.toString():n)};var ci=({parameters:e={},...t}={})=>r=>{let s=[];if(r&&typeof r=="object")for(let o in r){let u=r[o];if(u==null)continue;let p=e[o]||t;if(Array.isArray(u)){let d=yt({allowReserved:p.allowReserved,explode:!0,name:o,style:"form",value:u,...p.array});d&&s.push(d)}else if(typeof u=="object"){let d=ht({allowReserved:p.allowReserved,explode:!0,name:o,style:"deepObject",value:u,...p.object});d&&s.push(d)}else{let d=Ce({allowReserved:p.allowReserved,name:o,value:u});d&&s.push(d)}}return s.join("&")},li=e=>{if(!e)return"stream";let t=e.split(";")[0]?.trim();if(t){if(t.startsWith("application/json")||t.endsWith("+json"))return"json";if(t==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some(n=>t.startsWith(n)))return"blob";if(t.startsWith("text/"))return"text"}},cg=(e,t)=>t?!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)):!1,ui=async({security:e,...t})=>{for(let n of e){if(cg(t,n.name))continue;let r=await ai(n,t.auth);if(!r)continue;let s=n.name??"Authorization";switch(n.in){case"query":t.query||(t.query={}),t.query[s]=r;break;case"cookie":t.headers.append("Cookie",`${s}=${r}`);break;default:t.headers.set(s,r);break}}},Pn=e=>oi({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer=="function"?e.querySerializer:ci(e.querySerializer),url:e.url}),wn=(e,t)=>{let n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=bt(e.headers,t.headers),n},lg=e=>{let t=[];return e.forEach((n,r)=>{t.push([r,n])}),t},bt=(...e)=>{let t=new Headers;for(let n of e){if(!n)continue;let r=n instanceof Headers?lg(n):Object.entries(n);for(let[s,o]of r)if(o===null)t.delete(s);else if(Array.isArray(o))for(let u of o)t.append(s,u);else o!==void 0&&t.set(s,typeof o=="object"?JSON.stringify(o):o)}return t},Ne=class{fns=[];clear(){this.fns=[]}eject(t){let n=this.getInterceptorIndex(t);this.fns[n]&&(this.fns[n]=null)}exists(t){let n=this.getInterceptorIndex(t);return!!this.fns[n]}getInterceptorIndex(t){return typeof t=="number"?this.fns[t]?t:-1:this.fns.indexOf(t)}update(t,n){let r=this.getInterceptorIndex(t);return this.fns[r]?(this.fns[r]=n,t):!1}use(t){return this.fns.push(t),this.fns.length-1}},pi=()=>({error:new Ne,request:new Ne,response:new Ne}),ug=ci({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),pg={"Content-Type":"application/json"},Ke=(e={})=>({..._n,headers:pg,parseAs:"auto",querySerializer:ug,...e});var He=(e={})=>{let t=wn(Ke(),e),n=()=>({...t}),r=f=>(t=wn(t,f),n()),s=pi(),o=async f=>{let m={...t,...f,fetch:f.fetch??t.fetch??globalThis.fetch,headers:bt(t.headers,f.headers),serializedBody:void 0};m.security&&await ui({...m,security:m.security}),m.requestValidator&&await m.requestValidator(m),m.body!==void 0&&m.bodySerializer&&(m.serializedBody=m.bodySerializer(m.body)),(m.body===void 0||m.serializedBody==="")&&m.headers.delete("Content-Type");let h=Pn(m);return{opts:m,url:h}},u=async f=>{let{opts:m,url:h}=await o(f),P={redirect:"follow",...m,body:xn(m)},x=new Request(h,P);for(let A of s.request.fns)A&&(x=await A(x,m));let _=m.fetch,v;try{v=await _(x)}catch(A){let I=A;for(let R of s.error.fns)R&&(I=await R(A,void 0,x,m));if(I=I||{},m.throwOnError)throw I;return m.responseStyle==="data"?void 0:{error:I,request:x,response:void 0}}for(let A of s.response.fns)A&&(v=await A(v,x,m));let M={request:x,response:v};if(v.ok){let A=(m.parseAs==="auto"?li(v.headers.get("Content-Type")):m.parseAs)??"json";if(v.status===204||v.headers.get("Content-Length")==="0"){let R;switch(A){case"arrayBuffer":case"blob":case"text":R=await v[A]();break;case"formData":R=new FormData;break;case"stream":R=v.body;break;default:R={};break}return m.responseStyle==="data"?R:{data:R,...M}}let I;switch(A){case"arrayBuffer":case"blob":case"formData":case"text":I=await v[A]();break;case"json":{let R=await v.text();I=R?JSON.parse(R):{};break}case"stream":return m.responseStyle==="data"?v.body:{data:v.body,...M}}return A==="json"&&(m.responseValidator&&await m.responseValidator(I),m.responseTransformer&&(I=await m.responseTransformer(I))),m.responseStyle==="data"?I:{data:I,...M}}let $=await v.text(),l;try{l=JSON.parse($)}catch{}let y=l??$,a=y;for(let A of s.error.fns)A&&(a=await A(y,v,x,m));if(a=a||{},m.throwOnError)throw a;return m.responseStyle==="data"?void 0:{error:a,...M}},p=f=>m=>u({...m,method:f}),d=f=>async m=>{let{opts:h,url:P}=await o(m);return ii({...h,body:h.body,headers:h.headers,method:f,onRequest:async(x,_)=>{let v=new Request(x,_);for(let M of s.request.fns)M&&(v=await M(v,h));return v},serializedBody:xn(h),url:P})};return{buildUrl:Pn,connect:p("CONNECT"),delete:p("DELETE"),get:p("GET"),getConfig:n,head:p("HEAD"),interceptors:s,options:p("OPTIONS"),patch:p("PATCH"),post:p("POST"),put:p("PUT"),request:u,setConfig:r,sse:{connect:d("CONNECT"),delete:d("DELETE"),get:d("GET"),head:d("HEAD"),options:d("OPTIONS"),patch:d("PATCH"),post:d("POST"),put:d("PUT"),trace:d("TRACE")},trace:p("TRACE")}};var dg={$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"},gg=Object.entries(dg),di=(e,t)=>{t||(t=new Map);for(let n of e)"in"in n?n.key&&t.set(n.key,{in:n.in,map:n.map}):"key"in n?t.set(n.key,{map:n.map}):n.args&&di(n.args,t);return t},mg=e=>{for(let[t,n]of Object.entries(e))n&&typeof n=="object"&&!Object.keys(n).length&&delete e[t]},g=(e,t)=>{let n={body:{},headers:{},path:{},query:{}},r=di(t),s;for(let[o,u]of e.entries())if(t[o]&&(s=t[o]),!!s)if("in"in s)if(s.key){let p=r.get(s.key),d=p.map||s.key;p.in&&(n[p.in][d]=u)}else n.body=u;else for(let[p,d]of Object.entries(u??{})){let f=r.get(p);if(f)if(f.in){let m=f.map||p;n[f.in][m]=d}else n[f.map]=d;else{let m=gg.find(([h])=>p.startsWith(h));if(m){let[h,P]=m;n[P][p.slice(h.length)]=d}else if("allowExtra"in s&&s.allowExtra){for(let[h,P]of Object.entries(s.allowExtra))if(P){n[h][p]=d;break}}}}return mg(n),n};var gi=He(Ke({baseUrl:"http://localhost:4096"}));var k=class{client;constructor(t){this.client=t?.client??gi}},kn=class{defaultKey="default";instances=new Map;get(t){let n=this.instances.get(t??this.defaultKey);if(!n)throw new Error('No SDK client found. Create one with "new OpencodeClient()" to fix this error.');return n}set(t,n){this.instances.set(n??this.defaultKey,t)}},Sn=class extends k{remove(t,n){let r=g([t],[{args:[{in:"path",key:"providerID"}]}]);return(n?.client??this.client).delete({url:"/auth/{providerID}",...n,...r})}set(t,n){let r=g([t],[{args:[{in:"path",key:"providerID"},{key:"auth",map:"body"}]}]);return(n?.client??this.client).put({url:"/auth/{providerID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},vn=class extends k{log(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"service"},{in:"body",key:"level"},{in:"body",key:"message"},{in:"body",key:"extra"}]}]);return(n?.client??this.client).post({url:"/log",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}agents(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/agent",...n,...r})}skills(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/skill",...n,...r})}},An=class extends k{moveSession(t,n){let r=g([t],[{args:[{in:"body",key:"sessionID"},{in:"body",key:"destination"},{in:"body",key:"moveChanges"}]}]);return(n?.client??this.client).post({url:"/experimental/control-plane/move-session",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},Cn=class extends k{get(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/capabilities",...n,...r})}},Rn=class extends k{get(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/console",...n,...r})}listOrgs(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/console/orgs",...n,...r})}switchOrg(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"accountID"},{in:"body",key:"orgID"}]}]);return(n?.client??this.client).post({url:"/experimental/console/switch",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},Tn=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"roots"},{in:"query",key:"start"},{in:"query",key:"cursor"},{in:"query",key:"search"},{in:"query",key:"limit"},{in:"query",key:"archived"}]}]);return(n?.client??this.client).get({url:"/experimental/session",...n,...r})}background(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/experimental/session/{sessionID}/background",...n,...r})}},In=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/resource",...n,...r})}},En=class extends k{generateName(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"context"}]}]);return(n?.client??this.client).post({url:"/experimental/project/{projectID}/copy/generate-name",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},jn=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/workspace/adapter",...n,...r})}},$n=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/workspace",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"id"},{in:"body",key:"type"},{in:"body",key:"branch"},{in:"body",key:"extra"}]}]);return(n?.client??this.client).post({url:"/experimental/workspace",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}syncList(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/experimental/workspace/sync-list",...n,...r})}status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/workspace/status",...n,...r})}remove(t,n){let r=g([t],[{args:[{in:"path",key:"id"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/experimental/workspace/{id}",...n,...r})}warp(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"id"},{in:"body",key:"sessionID"},{in:"body",key:"copyChanges"}]}]);return(n?.client??this.client).post({url:"/experimental/workspace/warp",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}_adapter;get adapter(){return this._adapter??=new jn({client:this.client})}},Mn=class extends k{_controlPlane;get controlPlane(){return this._controlPlane??=new An({client:this.client})}_capabilities;get capabilities(){return this._capabilities??=new Cn({client:this.client})}_console;get console(){return this._console??=new Rn({client:this.client})}_session;get session(){return this._session??=new Tn({client:this.client})}_resource;get resource(){return this._resource??=new In({client:this.client})}_projectCopy;get projectCopy(){return this._projectCopy??=new En({client:this.client})}_workspace;get workspace(){return this._workspace??=new $n({client:this.client})}},Dn=class extends k{get(t){return(t?.client??this.client).get({url:"/global/config",...t})}update(t,n){let r=g([t],[{args:[{key:"config",map:"body"}]}]);return(n?.client??this.client).patch({url:"/global/config",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},On=class extends k{health(t){return(t?.client??this.client).get({url:"/global/health",...t})}event(t){return(t?.client??this.client).sse.get({url:"/global/event",...t})}dispose(t){return(t?.client??this.client).post({url:"/global/dispose",...t})}upgrade(t,n){let r=g([t],[{args:[{in:"body",key:"target"}]}]);return(n?.client??this.client).post({url:"/global/upgrade",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}_config;get config(){return this._config??=new Dn({client:this.client})}},qn=class extends k{subscribe(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).sse.get({url:"/event",...n,...r})}},Un=class extends k{get(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/config",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"config",map:"body"}]}]);return(n?.client??this.client).patch({url:"/config",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}providers(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/config/providers",...n,...r})}},Fn=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"provider"},{in:"query",key:"model"}]}]);return(n?.client??this.client).get({url:"/experimental/tool",...n,...r})}ids(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/tool/ids",...n,...r})}},Ln=class extends k{remove(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"worktreeRemoveInput",map:"body"}]}]);return(n?.client??this.client).delete({url:"/experimental/worktree",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/experimental/worktree",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"worktreeCreateInput",map:"body"}]}]);return(n?.client??this.client).post({url:"/experimental/worktree",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}reset(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"worktreeResetInput",map:"body"}]}]);return(n?.client??this.client).post({url:"/experimental/worktree/reset",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},Bn=class extends k{text(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"pattern"}]}]);return(n?.client??this.client).get({url:"/find",...n,...r})}files(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"query"},{in:"query",key:"dirs"},{in:"query",key:"type"},{in:"query",key:"limit"}]}]);return(n?.client??this.client).get({url:"/find/file",...n,...r})}symbols(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"query"}]}]);return(n?.client??this.client).get({url:"/find/symbol",...n,...r})}},Gn=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"path"}]}]);return(n?.client??this.client).get({url:"/file",...n,...r})}read(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"path"}]}]);return(n?.client??this.client).get({url:"/file/content",...n,...r})}status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/file/status",...n,...r})}},Nn=class extends k{dispose(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/instance/dispose",...n,...r})}},Kn=class extends k{get(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/path",...n,...r})}},Hn=class extends k{raw(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/vcs/diff/raw",...n,...r})}},Wn=class extends k{get(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/vcs",...n,...r})}status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/vcs/status",...n,...r})}diff(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"mode"},{in:"query",key:"context"}]}]);return(n?.client??this.client).get({url:"/vcs/diff",...n,...r})}apply(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"patch"}]}]);return(n?.client??this.client).post({url:"/vcs/apply",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}_diff;get diff2(){return this._diff??=new Hn({client:this.client})}},zn=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/command",...n,...r})}},Vn=class extends k{status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/lsp",...n,...r})}},Xn=class extends k{status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/formatter",...n,...r})}},Jn=class extends k{remove(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/mcp/{name}/auth",...n,...r})}start(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/mcp/{name}/auth",...n,...r})}callback(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"code"}]}]);return(n?.client??this.client).post({url:"/mcp/{name}/auth/callback",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}authenticate(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/mcp/{name}/auth/authenticate",...n,...r})}},Qn=class extends k{status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/mcp",...n,...r})}add(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"name"},{in:"body",key:"config"}]}]);return(n?.client??this.client).post({url:"/mcp",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}connect(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/mcp/{name}/connect",...n,...r})}disconnect(t,n){let r=g([t],[{args:[{in:"path",key:"name"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/mcp/{name}/disconnect",...n,...r})}_auth;get auth(){return this._auth??=new Jn({client:this.client})}},Yn=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/project",...n,...r})}current(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/project/current",...n,...r})}initGit(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/project/git/init",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"name"},{in:"body",key:"icon"},{in:"body",key:"commands"}]}]);return(n?.client??this.client).patch({url:"/project/{projectID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}directories(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/project/{projectID}/directories",...n,...r})}},Zn=class extends k{shells(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/pty/shells",...n,...r})}list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/pty",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"command"},{in:"body",key:"args"},{in:"body",key:"cwd"},{in:"body",key:"title"},{in:"body",key:"env"}]}]);return(n?.client??this.client).post({url:"/pty",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}remove(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/pty/{ptyID}",...n,...r})}get(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/pty/{ptyID}",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"title"},{in:"body",key:"size"}]}]);return(n?.client??this.client).put({url:"/pty/{ptyID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}connectToken(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/pty/{ptyID}/connect-token",...n,...r})}connect(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"cursor"},{in:"query",key:"ticket"}]}]);return(n?.client??this.client).get({url:"/pty/{ptyID}/connect",...n,...r})}},er=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/question",...n,...r})}reply(t,n){let r=g([t],[{args:[{in:"path",key:"requestID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"answers"}]}]);return(n?.client??this.client).post({url:"/question/{requestID}/reply",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}reject(t,n){let r=g([t],[{args:[{in:"path",key:"requestID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/question/{requestID}/reject",...n,...r})}},tr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/permission",...n,...r})}reply(t,n){let r=g([t],[{args:[{in:"path",key:"requestID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"reply"},{in:"body",key:"message"}]}]);return(n?.client??this.client).post({url:"/permission/{requestID}/reply",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}respond(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"permissionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"response"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/permissions/{permissionID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},nr=class extends k{authorize(t,n){let r=g([t],[{args:[{in:"path",key:"providerID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"method"},{in:"body",key:"inputs"}]}]);return(n?.client??this.client).post({url:"/provider/{providerID}/oauth/authorize",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}callback(t,n){let r=g([t],[{args:[{in:"path",key:"providerID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"method"},{in:"body",key:"code"}]}]);return(n?.client??this.client).post({url:"/provider/{providerID}/oauth/callback",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},rr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/provider",...n,...r})}auth(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/provider/auth",...n,...r})}_oauth;get oauth(){return this._oauth??=new nr({client:this.client})}},sr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"scope"},{in:"query",key:"path"},{in:"query",key:"roots"},{in:"query",key:"start"},{in:"query",key:"search"},{in:"query",key:"limit"}]}]);return(n?.client??this.client).get({url:"/session",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"parentID"},{in:"body",key:"title"},{in:"body",key:"agent"},{in:"body",key:"model"},{in:"body",key:"metadata"},{in:"body",key:"permission"},{in:"body",key:"workspaceID"}]}]);return(n?.client??this.client).post({url:"/session",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}status(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/session/status",...n,...r})}delete(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/session/{sessionID}",...n,...r})}get(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"title"},{in:"body",key:"metadata"},{in:"body",key:"permission"},{in:"body",key:"time"}]}]);return(n?.client??this.client).patch({url:"/session/{sessionID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}children(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}/children",...n,...r})}todo(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}/todo",...n,...r})}diff(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"messageID"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}/diff",...n,...r})}messages(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"query",key:"limit"},{in:"query",key:"before"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}/message",...n,...r})}prompt(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"},{in:"body",key:"model"},{in:"body",key:"agent"},{in:"body",key:"noReply"},{in:"body",key:"tools"},{in:"body",key:"format"},{in:"body",key:"system"},{in:"body",key:"variant"},{in:"body",key:"parts"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/message",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}deleteMessage(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"messageID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/session/{sessionID}/message/{messageID}",...n,...r})}message(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"messageID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/session/{sessionID}/message/{messageID}",...n,...r})}fork(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/fork",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}abort(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/abort",...n,...r})}init(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"modelID"},{in:"body",key:"providerID"},{in:"body",key:"messageID"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/init",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}unshare(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/session/{sessionID}/share",...n,...r})}share(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/share",...n,...r})}summarize(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"providerID"},{in:"body",key:"modelID"},{in:"body",key:"auto"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/summarize",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}promptAsync(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"},{in:"body",key:"model"},{in:"body",key:"agent"},{in:"body",key:"noReply"},{in:"body",key:"tools"},{in:"body",key:"format"},{in:"body",key:"system"},{in:"body",key:"variant"},{in:"body",key:"parts"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/prompt_async",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}command(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"},{in:"body",key:"agent"},{in:"body",key:"model"},{in:"body",key:"arguments"},{in:"body",key:"command"},{in:"body",key:"variant"},{in:"body",key:"parts"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/command",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}shell(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"},{in:"body",key:"agent"},{in:"body",key:"model"},{in:"body",key:"command"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/shell",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}revert(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"messageID"},{in:"body",key:"partID"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/revert",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}unrevert(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/session/{sessionID}/unrevert",...n,...r})}},ir=class extends k{delete(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"messageID"},{in:"path",key:"partID"},{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).delete({url:"/session/{sessionID}/message/{messageID}/part/{partID}",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"messageID"},{in:"path",key:"partID"},{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"part",map:"body"}]}]);return(n?.client??this.client).patch({url:"/session/{sessionID}/message/{messageID}/part/{partID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},or=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"body",map:"body"}]}]);return(n?.client??this.client).post({url:"/sync/history",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},ar=class extends k{start(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/sync/start",...n,...r})}replay(t,n){let r=g([t],[{args:[{in:"query",key:"query_directory",map:"directory"},{in:"query",key:"workspace"},{in:"body",key:"body_directory",map:"directory"},{in:"body",key:"events"}]}]);return(n?.client??this.client).post({url:"/sync/replay",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}steal(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/sync/steal",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}_history;get history(){return this._history??=new or({client:this.client})}},cr=class extends k{next(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).get({url:"/tui/control/next",...n,...r})}response(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"body",map:"body"}]}]);return(n?.client??this.client).post({url:"/tui/control/response",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},lr=class extends k{appendPrompt(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"text"}]}]);return(n?.client??this.client).post({url:"/tui/append-prompt",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}openHelp(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/open-help",...n,...r})}openSessions(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/open-sessions",...n,...r})}openThemes(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/open-themes",...n,...r})}openModels(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/open-models",...n,...r})}submitPrompt(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/submit-prompt",...n,...r})}clearPrompt(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"}]}]);return(n?.client??this.client).post({url:"/tui/clear-prompt",...n,...r})}executeCommand(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"command"}]}]);return(n?.client??this.client).post({url:"/tui/execute-command",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}showToast(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"title"},{in:"body",key:"message"},{in:"body",key:"variant"},{in:"body",key:"duration"}]}]);return(n?.client??this.client).post({url:"/tui/show-toast",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}publish(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{key:"body",map:"body"}]}]);return(n?.client??this.client).post({url:"/tui/publish",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}selectSession(t,n){let r=g([t],[{args:[{in:"query",key:"directory"},{in:"query",key:"workspace"},{in:"body",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/tui/select-session",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}_control;get control(){return this._control??=new cr({client:this.client})}},ur=class extends k{get(t){return(t?.client??this.client).get({url:"/api/health",...t})}},pr=class extends k{get(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/location",...n,...r})}},dr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/agent",...n,...r})}},gr=class extends k{stage(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"body",key:"messageID"},{in:"body",key:"files"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/revert/stage",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}clear(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/revert/clear",...n,...r})}commit(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/revert/commit",...n,...r})}},mr=class extends k{list(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/permission",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"body",key:"id"},{in:"body",key:"action"},{in:"body",key:"resources"},{in:"body",key:"save"},{in:"body",key:"metadata"},{in:"body",key:"source"},{in:"body",key:"agent"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/permission",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}get(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"requestID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/permission/{requestID}",...n,...r})}reply(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"requestID"},{in:"body",key:"reply"},{in:"body",key:"message"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/permission/{requestID}/reply",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},fr=class extends k{list(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/question",...n,...r})}reply(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"requestID"},{key:"questionV2Reply",map:"body"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/question/{requestID}/reply",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}reject(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"requestID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/question/{requestID}/reject",...n,...r})}},yr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"workspace"},{in:"query",key:"limit"},{in:"query",key:"order"},{in:"query",key:"search"},{in:"query",key:"directory"},{in:"query",key:"project"},{in:"query",key:"subpath"},{in:"query",key:"cursor"}]}]);return(n?.client??this.client).get({url:"/api/session",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"body",key:"id"},{in:"body",key:"agent"},{in:"body",key:"model"},{in:"body",key:"location"}]}]);return(n?.client??this.client).post({url:"/api/session",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}active(t){return(t?.client??this.client).get({url:"/api/session/active",...t})}get(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}",...n,...r})}switchAgent(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"body",key:"agent"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/agent",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}switchModel(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"body",key:"model"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/model",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}prompt(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"body",key:"id"},{in:"body",key:"prompt"},{in:"body",key:"delivery"},{in:"body",key:"resume"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/prompt",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}compact(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/compact",...n,...r})}wait(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/wait",...n,...r})}context(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/context",...n,...r})}history(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"limit"},{in:"query",key:"after"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/history",...n,...r})}events(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"after"}]}]);return(n?.client??this.client).sse.get({url:"/api/session/{sessionID}/event",...n,...r})}interrupt(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"}]}]);return(n?.client??this.client).post({url:"/api/session/{sessionID}/interrupt",...n,...r})}message(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"path",key:"messageID"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/message/{messageID}",...n,...r})}messages(t,n){let r=g([t],[{args:[{in:"path",key:"sessionID"},{in:"query",key:"limit"},{in:"query",key:"order"},{in:"query",key:"cursor"}]}]);return(n?.client??this.client).get({url:"/api/session/{sessionID}/message",...n,...r})}_revert;get revert(){return this._revert??=new gr({client:this.client})}_permission;get permission(){return this._permission??=new mr({client:this.client})}_question;get question(){return this._question??=new fr({client:this.client})}},hr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/model",...n,...r})}},br=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/provider",...n,...r})}get(t,n){let r=g([t],[{args:[{in:"path",key:"providerID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/provider/{providerID}",...n,...r})}},xr=class extends k{key(t,n){let r=g([t],[{args:[{in:"path",key:"integrationID"},{in:"query",key:"location"},{in:"body",key:"key"},{in:"body",key:"label"}]}]);return(n?.client??this.client).post({url:"/api/integration/{integrationID}/connect/key",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}oauth(t,n){let r=g([t],[{args:[{in:"path",key:"integrationID"},{in:"query",key:"location"},{in:"body",key:"methodID"},{in:"body",key:"inputs"},{in:"body",key:"label"}]}]);return(n?.client??this.client).post({url:"/api/integration/{integrationID}/connect/oauth",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},_r=class extends k{cancel(t,n){let r=g([t],[{args:[{in:"path",key:"attemptID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).delete({url:"/api/integration/attempt/{attemptID}",...n,...r})}status(t,n){let r=g([t],[{args:[{in:"path",key:"attemptID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/integration/attempt/{attemptID}",...n,...r})}complete(t,n){let r=g([t],[{args:[{in:"path",key:"attemptID"},{in:"query",key:"location"},{in:"body",key:"code"}]}]);return(n?.client??this.client).post({url:"/api/integration/attempt/{attemptID}/complete",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},Pr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/integration",...n,...r})}get(t,n){let r=g([t],[{args:[{in:"path",key:"integrationID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/integration/{integrationID}",...n,...r})}_connect;get connect(){return this._connect??=new xr({client:this.client})}_attempt;get attempt(){return this._attempt??=new _r({client:this.client})}},wr=class extends k{remove(t,n){let r=g([t],[{args:[{in:"path",key:"credentialID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).delete({url:"/api/credential/{credentialID}",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"credentialID"},{in:"query",key:"location"},{in:"body",key:"label"}]}]);return(n?.client??this.client).patch({url:"/api/credential/{credentialID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}},kr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/permission/request",...n,...r})}},Sr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"projectID"}]}]);return(n?.client??this.client).get({url:"/api/permission/saved",...n,...r})}remove(t,n){let r=g([t],[{args:[{in:"path",key:"id"}]}]);return(n?.client??this.client).delete({url:"/api/permission/saved/{id}",...n,...r})}},vr=class extends k{_request;get request(){return this._request??=new kr({client:this.client})}_saved;get saved(){return this._saved??=new Sr({client:this.client})}},Ar=class extends k{read(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/fs/read/*",...n,...r})}list(t,n){let r=g([t],[{args:[{in:"query",key:"location"},{in:"query",key:"path"}]}]);return(n?.client??this.client).get({url:"/api/fs/list",...n,...r})}find(t,n){let r=g([t],[{args:[{in:"query",key:"location"},{in:"query",key:"query"},{in:"query",key:"type"},{in:"query",key:"limit"}]}]);return(n?.client??this.client).get({url:"/api/fs/find",...n,...r})}},Cr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/command",...n,...r})}},Rr=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/skill",...n,...r})}},Tr=class extends k{subscribe(t){return(t?.client??this.client).sse.get({url:"/api/event",...t})}},Ir=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/pty",...n,...r})}create(t,n){let r=g([t],[{args:[{in:"query",key:"location"},{in:"body",key:"command"},{in:"body",key:"args"},{in:"body",key:"cwd"},{in:"body",key:"title"},{in:"body",key:"env"}]}]);return(n?.client??this.client).post({url:"/api/pty",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}remove(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).delete({url:"/api/pty/{ptyID}",...n,...r})}get(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/pty/{ptyID}",...n,...r})}update(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"location"},{in:"body",key:"title"},{in:"body",key:"size"}]}]);return(n?.client??this.client).put({url:"/api/pty/{ptyID}",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}connectToken(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).post({url:"/api/pty/{ptyID}/connect-token",...n,...r})}connect(t,n){let r=g([t],[{args:[{in:"path",key:"ptyID"},{in:"query",key:"location[directory]"},{in:"query",key:"location[workspace]"},{in:"query",key:"cursor"},{in:"query",key:"ticket"}]}]);return(n?.client??this.client).get({url:"/api/pty/{ptyID}/connect",...n,...r})}},Er=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/question/request",...n,...r})}},jr=class extends k{_request;get request(){return this._request??=new Er({client:this.client})}},$r=class extends k{list(t,n){let r=g([t],[{args:[{in:"query",key:"location"}]}]);return(n?.client??this.client).get({url:"/api/reference",...n,...r})}},Mr=class extends k{remove(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"location"},{in:"body",key:"directory"},{in:"body",key:"force"}]}]);return(n?.client??this.client).delete({url:"/experimental/project/{projectID}/copy",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}create(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"location"},{in:"body",key:"strategy"},{in:"body",key:"directory"},{in:"body",key:"name"}]}]);return(n?.client??this.client).post({url:"/experimental/project/{projectID}/copy",...n,...r,headers:{"Content-Type":"application/json",...n?.headers,...r.headers}})}refresh(t,n){let r=g([t],[{args:[{in:"path",key:"projectID"},{in:"query",key:"location"}]}]);return(n?.client??this.client).post({url:"/experimental/project/{projectID}/copy/refresh",...n,...r})}},Dr=class extends k{_health;get health(){return this._health??=new ur({client:this.client})}_location;get location(){return this._location??=new pr({client:this.client})}_agent;get agent(){return this._agent??=new dr({client:this.client})}_session;get session(){return this._session??=new yr({client:this.client})}_model;get model(){return this._model??=new hr({client:this.client})}_provider;get provider(){return this._provider??=new br({client:this.client})}_integration;get integration(){return this._integration??=new Pr({client:this.client})}_credential;get credential(){return this._credential??=new wr({client:this.client})}_permission;get permission(){return this._permission??=new vr({client:this.client})}_fs;get fs(){return this._fs??=new Ar({client:this.client})}_command;get command(){return this._command??=new Cr({client:this.client})}_skill;get skill(){return this._skill??=new Rr({client:this.client})}_event;get event(){return this._event??=new Tr({client:this.client})}_pty;get pty(){return this._pty??=new Ir({client:this.client})}_question;get question(){return this._question??=new jr({client:this.client})}_reference;get reference(){return this._reference??=new $r({client:this.client})}_projectCopy;get projectCopy(){return this._projectCopy??=new Mr({client:this.client})}},xt=class e extends k{static __registry=new kn;constructor(t){super(t),e.__registry.set(this,t?.key)}_auth;get auth(){return this._auth??=new Sn({client:this.client})}_app;get app(){return this._app??=new vn({client:this.client})}_experimental;get experimental(){return this._experimental??=new Mn({client:this.client})}_global;get global(){return this._global??=new On({client:this.client})}_event;get event(){return this._event??=new qn({client:this.client})}_config;get config(){return this._config??=new Un({client:this.client})}_tool;get tool(){return this._tool??=new Fn({client:this.client})}_worktree;get worktree(){return this._worktree??=new Ln({client:this.client})}_find;get find(){return this._find??=new Bn({client:this.client})}_file;get file(){return this._file??=new Gn({client:this.client})}_instance;get instance(){return this._instance??=new Nn({client:this.client})}_path;get path(){return this._path??=new Kn({client:this.client})}_vcs;get vcs(){return this._vcs??=new Wn({client:this.client})}_command;get command(){return this._command??=new zn({client:this.client})}_lsp;get lsp(){return this._lsp??=new Vn({client:this.client})}_formatter;get formatter(){return this._formatter??=new Xn({client:this.client})}_mcp;get mcp(){return this._mcp??=new Qn({client:this.client})}_project;get project(){return this._project??=new Yn({client:this.client})}_pty;get pty(){return this._pty??=new Zn({client:this.client})}_question;get question(){return this._question??=new er({client:this.client})}_permission;get permission(){return this._permission??=new tr({client:this.client})}_provider;get provider(){return this._provider??=new rr({client:this.client})}_session;get session(){return this._session??=new sr({client:this.client})}_part;get part(){return this._part??=new ir({client:this.client})}_sync;get sync(){return this._sync??=new ar({client:this.client})}_tui;get tui(){return this._tui??=new lr({client:this.client})}_v2;get v2(){return this._v2??=new Dr({client:this.client})}};function fi(e,t,n,r){if(!r?.throwOnError||e instanceof Error)return e;if(typeof e=="object"&&e!==null&&Object.keys(e).length>0){let o=e,u=typeof o.data?.message=="string"&&o.data.message||typeof o.message=="string"&&o.message||typeof o.name=="string"&&o.name||mi(n,t);return new Error(u,{cause:{body:e,status:t?.status}})}if(typeof e=="string"&&e.length>0)return new Error(e,{cause:{body:e,status:t?.status}});let s=t?"(empty response body)":"network error (no response)";return new Error(`opencode server ${mi(n,t)}: ${s}`,{cause:{body:e,status:t?.status}})}function mi(e,t){let n=e?.method??"?",r=e?.url??"?",s=t?.status,o=t?.statusText;return`${n} ${r}${s?" \u2192 "+s:""}${o?" "+o:""}`}function fg(e,t,n){if(e)return t&&(e===t||n&&e===n(t))?t:e}function yg(e,t){if(e.method!=="GET"&&e.method!=="HEAD")return e;let n=new URL(e.url),r=!1;for(let[o,u]of[["x-opencode-directory","directory"],["x-opencode-workspace","workspace"]]){let p=fg(e.headers.get(o),u==="directory"?t.directory:t.workspace,u==="directory"?encodeURIComponent:void 0);if(p){for(let d of n.pathname.startsWith("/api/")?[u,`location[${u}]`]:[u])n.searchParams.has(d)||n.searchParams.set(d,p);r=!0}}if(!r)return e;let s=new Request(n,e);return s.headers.delete("x-opencode-directory"),s.headers.delete("x-opencode-workspace"),s}function Or(e){e?.fetch||(e={...e,fetch:r=>(r.timeout=!1,fetch(r))}),e?.directory&&(e.headers={...e.headers,"x-opencode-directory":encodeURIComponent(e.directory)}),e?.experimental_workspaceID&&(e.headers={...e.headers,"x-opencode-workspace":e.experimental_workspaceID});let t=He(e);return t.interceptors.request.use(n=>yg(n,{directory:e?.directory,workspace:e?.experimental_workspaceID})),t.interceptors.response.use(n=>{if(n.headers.get("content-type")==="text/html")throw new Error("Request is not supported by this version of OpenCode Server (Server responded with text/html)");return n}),t.interceptors.error.use(fi),new xt({client:t})}var hg=new Set(["api","cli","mobile","web"]);function _t(e){let t=e?.trim().toLowerCase();return t&&hg.has(t)?t:null}function bg(e){return new Promise(t=>setTimeout(t,e))}async function yi(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,u=null;for(let p=0;p<r;p++)if(p>0&&(o&&n?.(),s>0&&await bg(s)),u=await e(),u)return u;return u}var xg=12e4;function _g(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function qr(e,t,n=xg){let r=e instanceof Request?e.signal:t?.signal;if(_g(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function Ur(e,t,n,r){let s=new Headers(e instanceof Request?e.headers:void 0);t?.headers&&new Headers(t.headers).forEach((u,p)=>{s.set(p,u)}),n&&!s.has("Authorization")&&s.set("Authorization",`Bearer ${n}`);let o=_t(r);return o&&!s.has("X-Kortix-Client")&&s.set("X-Kortix-Client",o),s}function hi(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}async function Fr(){return O().getToken()}async function ae(e){return yi(()=>O().getToken(),e,Pt)}function Pt(){}function Lb(e){}function Bb(e){}async function We(){return Fr()}async function bi(e){return ae(e)}function xi(e,t,n,r){let s=O().fetch??fetch;if(e instanceof Request){let o=new Request(e,{headers:n,...r?{signal:r}:{}});return s(o)}return s(e,{...t,headers:n,...r?{signal:r}:{}})}async function U(e,t,n){let{retryOnAuthError:r=!0,timeoutMs:s}=n??{},o=await bi();if(!o)return hi();let u=O().clientSource,p=Ur(e,t,o,u),d=s===void 0?qr(e,t):qr(e,t,s),f=await xi(e,t,p,d);if(f.status===401&&r&&o){Pt();let m=await bi({attempts:2,baseDelayMs:200});if(m&&m!==o){let h=Ur(e,t,m,u);return xi(e,t,h,d)}}return f}var Re={url:null,sandboxId:null,dbSandboxId:null,version:0},Pg=new Set;function _i(e,t=null,n=null){if(!(Re.url===e&&Re.sandboxId===t&&Re.dbSandboxId===n)){Re={url:e,sandboxId:t,dbSandboxId:n,version:Re.version+1};for(let r of Pg)r()}}function Pi(){return Re.url}function wg(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function ze(){return wg(O().backendUrl||"http://localhost:8008/v1")}function wi(){let e=O().sandboxId;return e?`${ze()}/p/${e}/8000`:""}function kg(e){return`${ze()}/p/${e}/8000`}function wt(e){return kg(e)}var S=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let u=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:u,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},Te=class extends S{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},be=class e extends Error{status;detail;constructor(t,n,r){super(r||n.message||`Billing Error: ${t}`),this.name="BillingError",this.status=t,this.detail=n,Object.setPrototypeOf(this,e.prototype)}},Ie=class e extends Error{status;detail;constructor(t=431,n,r){let s="Request headers are too large",o="Try uploading files one at a time, or reduce the number of files in a single request.";super(r||n?.message||s),this.name="RequestTooLargeError",this.status=t,this.detail={message:n?.message||s,suggestion:n?.suggestion||o},Object.setPrototypeOf(this,e.prototype)}},Lr="feature_disabled";function ki(e){if(!(e instanceof S)||e.status!==403||e.code!==Lr)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Si(e){let t=ki(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function vi(e){let t=ki(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}function Ee(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 be(t,{message:r?.message||e.message||"Billing error",...r})}function Ai(e){return e instanceof be}function Ci(e){if(!(e instanceof be))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."}}var Sg="X-Kortix-Impersonate",Gr="kortix.impersonation",xe=null,kt=!1,Br=new Set;function Nr(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function vg(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 Ag(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 Ri(){for(let e of Br)try{e()}catch{}}function Cg(){return kt||(kt=!0,xe=Ag(Nr()?.getItem(Gr)??null)),xe&&!vg(xe)?(Ti(),null):xe}function zb(e){if(kt=!0,!e){Ti();return}xe=e;try{Nr()?.setItem(Gr,JSON.stringify(e))}catch{}Ri()}function Ti(){kt=!0;let e=xe!==null;xe=null;try{Nr()?.removeItem(Gr)}catch{}e&&Ri()}function Vb(e){return Br.add(e),()=>{Br.delete(e)}}var Rg=/(^|\/)admin\/(api|analytics)(\/|$)/;function Tg(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Rg.test(t)}function Kr(e){if(e!==void 0&&!Tg(e))return{};let t=Cg();return t?{[Sg]:t.grantId}:{}}function _e(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function ce(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(_e())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function St(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(_e())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var te=()=>O().backendUrl||"",Ig="feature_not_supported",Eg="model_not_servable",jg="provision_in_flight",Ii="request_deadline",$g=/^Request exceeded the \d+s server processing deadline$/,Mg=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ii||$g.test(n),Dg=new Set([502,503,504]),Og=e=>Dg.has(e),qg=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Ug=2,Hr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted"),vt=!1;function rx(e){vt=e}function sx(){return vt}async function le(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...u}=t,p=new AbortController,d=p,f=()=>d.abort();u.signal?.addEventListener("abort",f,{once:!0});let m=null,h=!1,P=!1;try{if(u.signal?.aborted)throw _e();m=setTimeout(()=>{!h&&!p.signal.aborted&&(h=!0,P=!0,p.abort())},s);let x=await ce(ae(),p.signal),_=u.body instanceof FormData,v={};_||(v["Content-Type"]="application/json"),Object.assign(v,u.headers);let M=_t(O().clientSource),$=Object.keys(v).some(R=>R.toLowerCase()==="x-kortix-client");if(M&&!$&&(v["X-Kortix-Client"]=M),vt&&(v["x-kortix-admin-bypass"]="1"),Object.assign(v,Kr(e)),x)v.Authorization=`Bearer ${x}`;else return{error:new Te,success:!1};let l=qg(u.method),y=l?Ug+1:1,a;for(let R=0;R<y;R++){R>0&&await St(250*2**(R-1),u.signal??void 0);let w=R===0?p:new AbortController;d=w,u.signal?.aborted&&w.abort(),R>0&&(m=setTimeout(()=>{P=!0,w.abort()},s));try{let j=O().fetch??fetch;a=await ce(j(e,{...u,headers:v,signal:w.signal,credentials:u.credentials??"omit"}),w.signal)}catch(j){if(m&&(clearTimeout(m),m=null),Hr(j)||R===y-1)throw j;continue}if(!(l&&Og(a.status)&&R<y-1)){!o&&m&&(clearTimeout(m),m=null);break}try{await ce(a.arrayBuffer(),w.signal)}catch(j){if(Hr(j))throw j}finally{m&&(clearTimeout(m),m=null)}}if(!a.ok){let R=`HTTP ${a.status}: ${a.statusText}`,w=null;try{w=await ce(a.json(),d.signal),typeof w.message=="string"?R=w.message:w.error&&typeof w.error=="string"?R=w.error:typeof w.detail=="string"?R=w.detail:typeof w.detail?.message=="string"?R=w.detail.message:typeof w.reason=="string"&&(R=w.reason)}catch{}if(d.signal.aborted)throw _e();let F=Mg(a.status,w,R),j=new S(R,{status:a.status,response:a,details:w||void 0,data:w,detail:w?.detail,code:F?Ii:w?.code||w?.error_code||w?.detail?.error_code||a.status.toString()});if(a.status===402&&(j=Ee(j)),a.status===403&&w?.code==="account_mfa_required"&&typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent("kortix:mfa-required"))}catch{}a.status===431&&(j=new Ie(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."}));let K=a.status===501&&w?.code===Ig,D=a.status===409&&w?.code===Eg,b=a.status===409&&w?.code===jg;return n&&!K&&!D&&!b&&!F&&O().onError?.(j,r),{error:j,success:!1}}let A,I=a.headers.get("content-type");return I?.includes("application/json")?A=await ce(a.json(),d.signal):I?.includes("text/")?A=await ce(a.text(),d.signal):A=await ce(a.blob(),d.signal),{data:A,success:!0,headers:a.headers}}catch(x){m&&(clearTimeout(m),m=null);let _=Hr(x);_&&(h=!0);let v;if(_){if(!P)return{error:new S("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let M=e.replace(te(),"")||e;v=new S(`Request timed out after ${Math.round(s/1e3)}s: ${M}`,{code:"TIMEOUT",url:e,endpoint:M,timeout:s})}else x instanceof Error?(v=new S(x.message,{name:x.name||"ApiError",stack:x.stack}),n&&O().onError?.(v,r)):(v=new S(String(x)),n&&O().onError?.(v,r));return{error:v,success:!1}}finally{m&&clearTimeout(m),u.signal?.removeEventListener("abort",f)}}var ix={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new S(r.message||"Database error",{code:r.code,details:r});return O().onError?.(s,t),{error:s,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new S(n.message,{name:n.name||"ApiError",stack:n.stack}):new S(String(n));return O().onError?.(r,t),{error:r,success:!1}}}};async function Fg(e,t,n={}){let{timeout:r=3e4,fetch:s=fetch}=n,o=await ae(),u={Accept:"text/event-stream","Content-Type":"application/json"},p=_t(O().clientSource);p&&(u["X-Kortix-Client"]=p),vt&&(u["x-kortix-admin-bypass"]="1"),Object.assign(u,Kr(e)),o&&(u.Authorization=`Bearer ${o}`);let d=new AbortController,f=setTimeout(()=>d.abort(),r);try{return await s(`${te()}${e}`,{method:"POST",headers:u,body:JSON.stringify(t),signal:d.signal,credentials:"omit"})}finally{clearTimeout(f)}}var i={putRaw:(e,t,n)=>le(`${te()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>le(`${te()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>le(`${te()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>le(`${te()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>le(`${te()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>le(`${te()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],le(`${te()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],le(`${te()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:Fg};var At=new Map,Wr=new Map;function zr(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Ei(e){return At.get(zr(e))??null}function ji(e){return At.has(zr(e))}async function Ct(e){let t=zr(e),n=At.get(t);if(n!==void 0)return n;let r=Wr.get(t);if(r)return r;let s=(async()=>{try{let o=await i.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let u=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return At.set(t,u),u}catch{return null}finally{Wr.delete(t)}})();return Wr.set(t,s),s}function $i(e){let{apiBaseUrl:t}=e;return ji(t)||Ct(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:Ei(t)}}function re(){let e=Pi();return e||(O().billingEnabled??!1?"":wi())}async function Vr(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Xr(e){if(!e)throw new Error("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading");return e}async function Mi(e){let t=Xr(e),n=await U(`${t}/env`);if(!n.ok)throw new Error(await Vr(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function Di(e,t,n){let r=Xr(e),s=await U(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await Vr(s,"Failed to save secret"))}async function Oi(e,t){let n=Xr(e),r=await U(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Vr(r,"Failed to delete secret"))}var Lg={list:Mi,set:Di,delete:Oi};async function Bg(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await U(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}function ue(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}async function Rt(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function Ve(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return ue(e)}async function qi(e){let t=Ve(e),n=await U(`${t}/kortix/pty`);if(!n.ok)throw new Error(await Rt(n,"Failed to list terminals"));return n.json()}async function Ui(e,t){let n=Ve(e),r=await U(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await Rt(r,"Failed to create terminal"));return r.json()}async function Fi(e,t,n){let r=Ve(e),s=await U(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await Rt(s,"Failed to update terminal"));return s.json()}async function Li(e,t){let n=Ve(e),r=await U(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await Rt(r,"Failed to remove terminal"))}async function Bi(e,t,n){let r=Ve(t),o=`${(()=>{try{let f=new URL(r);return f.protocol==="https:"?f.protocol="wss:":f.protocol==="http:"&&(f.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&f.protocol==="ws:"&&(f.protocol="wss:"),ue(f.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,u=new URLSearchParams,p=await We();p&&u.set("token",p),n?.wake&&u.set("wake","1");let d=u.toString();return d?`${o}${o.includes("?")?"&":"?"}${d}`:o}var Gg={list:qi,create:Ui,update:Fi,remove:Li,webSocketUrl:Bi};async function E(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await U(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),u=await o.text(),p={};try{p=u?JSON.parse(u):{}}catch{p={}}if(!o.ok)throw new Error(p?.error||p?.message||p?.details||u.slice(0,200)||`Request failed with ${o.status}`);return p}async function Cx(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 E(e,`/kortix/tasks${r}`)}async function Rx(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function Tx(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function Ix(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function Ex(e,t){return E(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function jx(e,t,n){return E(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function $x(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function Mx(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function Dx(e,t){return E(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Ox(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return E(e,`/kortix/tickets${n}`)}async function qx(e,t){return E(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function Ux(e,t){return E(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function Fx(e,t){return E(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function Lx(e,t,n){return E(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function Bx(e,t,n){return E(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function Gx(e,t,n){return E(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function Nx(e,t,n){return E(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function Kx(e,t,n){return E(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function Hx(e,t){return E(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Wx(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function zx(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function Vx(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function Xx(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function Jx(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function Qx(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function Yx(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function Zx(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function e_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function t_(e,t,n,r){return E(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function n_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function r_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function s_(e,t,n=200){return E(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function i_(e){return E(e,"/kortix/projects")}async function o_(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function a_(e,t){return E(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function c_(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function l_(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function u_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function p_(e,t,n="all"){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function d_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function g_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function m_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function f_(e,t,n,r){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function y_(e,t,n,r){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function h_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function b_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function x_(e,t){return E(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function __(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function P_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function w_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function k_(e,t,n){return E(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var Ng=1e4,Kg={retryOnAuthError:!1};function je(e,t,n){return E(e,t,{signal:AbortSignal.timeout(Ng),...n},Kg)}async function S_(e,t=!1){return(await je(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function v_(e){return(await je(e,"/kortix/services/templates")).templates??[]}async function A_(e,t){return(await je(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function C_(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return je(e,s,{method:r?"DELETE":"POST"})}async function R_(e,t){return je(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function T_(e,t){return je(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var Tt=new Map,Xe=class extends Error{constructor(t="[opencode-sdk] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function Pe(){let e=re();if(!e)throw new Xe;return pe(e)}function pe(e){if(!e)throw new Error("[opencode-sdk] getClientForUrl called without a url");let t=Tt.get(e);if(t)return t;if(!bn())throw new Error("[opencode-sdk] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=Or({baseUrl:e,fetch:U});return Tt.set(e,n),n}function O_(e){Tt.delete(e)}function q_(){Tt.clear()}var It=new Map;function U_(e){if(!e)throw new Error("[opencode-sdk] getPublicClientForUrl called without a url");let t=It.get(e);if(t)return t;let n=Or({baseUrl:e,fetch});return It.set(e,n),n}function F_(e){It.delete(e)}function L_(){It.clear()}async function Hg(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 B_(e){let t=re();if(!t)throw new S("[opencode-sdk] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await U(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new S(`System reload failed (${r.status}): ${await Hg(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new S(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let u;try{u=await r.json()}catch(d){throw new S(`System reload returned malformed JSON from ${n}: ${d instanceof Error?d.message:String(d)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let p=u===!0||typeof u=="object"&&u!==null&&u.ok===!0;return{success:p,mode:e,steps:p?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:p?[]:[`the sandbox did not confirm the reload (${n})`]}}function Hi(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new S(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function $e(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 X(e){let t=(e??re()).trim();if(!t)throw new Xe;return t}async function $t(e,t){let n=await U(`${X(t)}${e}`);if(!n.ok)throw new S(await $e(n),{status:n.status,response:n});return n.json()}var Yr=["/workspace","/tmp","/home","/opt"],Wg=Yr.filter(e=>e!=="/workspace");function Wi(e){return Yr.some(t=>e===t||e.startsWith(`${t}/`))}function jt(e){return Wi(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function Me(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(Wg.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var zi=Me;async function Mt(e,t){let n=X(t),r=Me(e)||".";return(await $t(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function Ye(e,t){let n=X(t),r=Me(e),s=await U(`${n}/file/content?path=${encodeURIComponent(r)}`);if(!s.ok)throw new S(await $e(s),{status:s.status,response:s});return s.json()}async function zg(e,t,n){let r=X(n),s=Me(e),o=await U(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new S(await $e(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new S("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let u=await o.blob();return t&&(!u.type||u.type==="application/octet-stream")?new Blob([u],{type:t}):u}async function Ze(e,t){let n=X(t);try{return await zg(e,void 0,n)}catch{}let r=await Ye(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}async function Dt(e){return $t("/file/status",X(e))}async function Ot(e,t,n){let r=X(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),$t(`/find/file?${s.toString()}`,r)}async function qt(e,t){let n=X(t);return(await $t(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var Je=[400,1200],Vg=e=>e===408||e===429||e===502||e===503||e===504,Gi=e=>new Promise(t=>setTimeout(t,e));function Xg(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Jr=3e4,Jg=15*6e4,Qg=256;function Qe(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Jr;let t=Jr+e/Qg;return Math.min(Jg,Math.max(Jr,Math.round(t)))}async function Yg(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 Et(e,t){let n;for(let s=0;s<=Je.length;s++){let o;try{o=await t(e())}catch(p){if(n=p,Xg(p)||s===Je.length)break;await Gi(Je[s]);continue}if(o.ok)return o.json();let u=await Yg(o);if(n=new S(`Upload failed (${o.status}): ${u}`,{status:o.status,response:o}),!Vg(o.status)||s===Je.length)throw n;await Gi(Je[s])}if(n instanceof S)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new S(`Upload failed: ${r}`)}var Qr=64*1024;function Ni(e,t){try{e?.onProgress?.(t)}catch{}}function Ki(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function Zg(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function et(e,t,n,r,s){let o=typeof r=="string"?r:void 0,u=typeof r=="string"?s:r,p=X(o),d=Qe(e.size),f=n||(e instanceof File?e.name:"")||"";if(e.size<=Qr){let x=await Et(()=>Ki(e,t,f),_=>U(`${p}/file/upload`,{method:"POST",body:_},{timeoutMs:d}));return Ni(u,{loadedBytes:e.size,totalBytes:e.size}),x}let h=(await Et(()=>Ki(new Blob([],{type:e.type}),t,f),x=>U(`${p}/file/upload`,{method:"POST",body:x},{timeoutMs:Qe(0)})))[0]?.path;if(!h)throw new S("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let P=Zg(h);if(!P.name)throw new S(`Upload reservation returned an invalid file path: ${h}`,{code:"UPLOAD_INVALID_PATH"});try{for(let x=0;x<e.size;x+=Qr){let _=Math.min(e.size,x+Qr),v=e.slice(x,_,e.type),M=await Et(()=>{let $=new FormData;return P.parent&&$.append("path",P.parent),$.append("filename",P.name),$.append("first",x===0?"true":"false"),$.append("offset",String(x)),$.append("file",v,P.name),$},$=>U(`${p}/file/append`,{method:"POST",body:$},{timeoutMs:Qe(v.size)}));if(M.path!==h||M.size!==_)throw new S(`Upload verification failed for ${h}: expected ${_} bytes, received ${M.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Ni(u,{loadedBytes:_,totalBytes:e.size})}}catch(x){throw await ke(h,p).catch(()=>{}),x}return[{path:h,size:e.size}]}function em(e,t,n){let r=X(n),s=Qe(t.size);return Et(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>U(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}async function Ut(e,t){let n=X(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),u=o.pop()||"untitled",p=o.join("/")||"/workspace",d=await tt(`${p}/${u}`,new Blob([],{type:"application/octet-stream"}),n);return[{path:d.path,size:d.bytes}]}async function Ft(e,t,n){let r=X(n);return em(t,await Ze(e,r),r)}function tm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function nm(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function rm(e){return e.slice(e.lastIndexOf("/")+1)}function sm(){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 tt(e,t,n){let r=X(n),s=jt(tm(e.trim())),o=rm(s);if(!o)throw new S(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let u=nm(s);await nt(u,r).catch(()=>{});let p=sm(),d=await et(t,u,`.${o}.kortix-write-${p}`,r),f=d[0]?.path;if(!f)throw new S(`Upload returned no file for ${s}`,{code:"UPLOAD_NO_RESULT"});let m=jt(f),h=`${s}.kortix-write-backup-${p}`,P=!1;try{await we(s,h,r),P=!0}catch{}try{await we(m,s,r)}catch(_){throw P&&await we(h,s,r).catch(()=>{}),await ke(m,r).catch(()=>{}),_}P&&await ke(h,r).catch(()=>{});let x=d[0]?.size;return{path:s,bytes:typeof x=="number"?x:t.size}}async function ke(e,t){let n=await U(`${X(t)}/file`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new S(`Delete failed (${n.status}): ${await $e(n)}`,{status:n.status,response:n});return n.json()}async function nt(e,t){let n=await U(`${X(t)}/file/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!n.ok)throw new S(`Mkdir failed (${n.status}): ${await $e(n)}`,{status:n.status,response:n});return n.json()}async function we(e,t,n){let r=await U(`${X(n)}/file/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({from:e,to:t})});if(!r.ok)throw new S(`Rename failed (${r.status}): ${await $e(r)}`,{status:r.status,response:r});return r.json()}async function Vi(){return Hi(await Pe().project.current())}async function Zr(){return Hi(await Pe().global.health())}async function Xi(){try{return(await Zr()).healthy===!0}catch{return!1}}var im={list:Mt,read:Ye,readBlob:Ze,status:Dt,findFiles:Ot,findText:qt,upload:et,write:tt,create:Ut,copy:Ft,remove:ke,mkdir:nt,rename:we,currentProject:Vi,health:Zr,isReachable:Xi,toDaemonPath:Me,toSandboxAbsolutePath:jt,toWorkspaceRelative:zi};var es=52428800,am=104857600,Ji=20;function c(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function ts(e){return e.replace(/\/v1\/?$/,"")}async function De(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=ts(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}}var Bt=e=>`/projects/${encodeURIComponent(e)}/attachments`,Gt={showErrors:!1,deadlineCoversBody:!0},Qi=3e4,cm=12e4,lm=6e4,um=5*6e4,pm=6e4,dm=6e4;function Lt(){return new S("Request aborted",{name:"AbortError",code:"ABORTED"})}function rt(e){if(e?.aborted)throw Lt()}function gm(e){return!(e instanceof S)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function st(e,t,n=!1){let r;for(let s=0;;s++){rt(t);try{return await e()}catch(o){let u=n&&o instanceof S&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(gm(o)||u))throw o;r??=Date.now()+(n?um:lm);let p=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+p>=r)throw o;try{await St(p,t)}catch{throw rt(t),o}}}}function mm(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function ns(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,u=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&mm(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!u)throw new Error("Invalid attachment upload handle");return e}async function Yi(e,t,n,r){return c(await i.post(Bt(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Gt,signal:n,timeout:Qi}),"Failed to start attachment upload")}async function Zi(e,t,n,r){let s=ns({...await st(()=>Yi(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function eo(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new S(r,{status:e,details:n,code:String(n?.statusCode??e)})}function fm(e){if(!(e instanceof S))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function ym(e,t,n,r){return new Promise((s,o)=>{let u=new e,p=0,d=!1,f,m=x=>{d||(d=!0,f&&clearTimeout(f),r.signal?.removeEventListener("abort",P),x?o(x):s())},h=()=>{f&&clearTimeout(f),f=setTimeout(()=>{m(new S("Attachment upload stalled",{code:"TIMEOUT"})),u.abort()},pm)},P=()=>{m(Lt()),u.abort()};u.open(t.method,t.url);for(let[x,_]of Object.entries(t.headers))u.setRequestHeader(x,_);u.upload.onprogress=x=>{h(),p=Math.min(x.loaded,n.size),r.onProgress?.(p,n.size)},u.onload=()=>{u.status>=200&&u.status<300?(p<n.size&&r.onProgress?.(n.size,n.size),m()):m(eo(u.status,u.responseText))},u.onerror=()=>m(new S("Network error during attachment upload",{name:"TypeError"})),u.onabort=()=>m(Lt()),r.signal?.addEventListener("abort",P,{once:!0}),h(),u.send(n)})}async function hm(e,t,n){let r=O().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?Lt():new S(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw eo(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function bm(e,t,n){rt(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?ym(r,e,t,n):hm(e,t,n)}async function xm(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let u=s.upload;try{await st(()=>bm(u,t,r),r.signal)}catch(p){let d=fm(p);if(d!==409){if(o||!(d===400||d===401||d===403))throw p;o=!0,s=await Zi(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return to(e,t,s,r)}async function to(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${Bt(e)}/${encodeURIComponent(n.attachment_id)}`,u=n;for(;u.received_bytes<t.size;){rt(r.signal);let p=u.received_bytes,d=Math.min(p+s,t.size),f=t.slice(p,d),m=await st(async()=>c(await i.putRaw(`${o}/chunks/${p/s}`,f,{...Gt,signal:r.signal,timeout:Qi}),"Failed to upload attachment chunk"),r.signal);if(m.size!==t.size||m.received_bytes!==d)throw new Error("Invalid attachment chunk acknowledgment");u={...u,received_bytes:d},r.onUpload?.(u),r.onProgress?.(d,t.size)}return u}async function Nt(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");rt(n.signal);let r=n.resume?ns({...n.resume},t):ns({...await st(()=>Yi(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()<dm&&(r=await Zi(e,t,r,n)),r=r.upload.kind==="direct"?await xm(e,t,r,n):await to(e,t,r,n)),n.onProcessing?.();let s=`${Bt(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await st(async()=>c(await i.post(`${s}/complete`,{},{...Gt,signal:n.signal,timeout:cm}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof S&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function Oe(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await i.delete(`${Bt(e)}/${encodeURIComponent(t)}`,{...Gt,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}var _m=100,Pm=0,wm=new Set(["attachment_size_mismatch","attachment_failed"]),no=()=>new S("Attachment expired. Attach the file again.",{code:"attachment_expired"});function ro(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 so(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,u=0,p=!1,d,f={attachments:[]},m=()=>[...r.values()].filter(l=>!l.handedOff);function h(){d&&clearTimeout(d);let l=m().map(({item:a})=>a);(l.length!==f.attachments.length||l.some((a,A)=>a!==f.attachments[A]))&&(f={attachments:l});let y=Math.min(...l.filter(a=>a.status==="ready").map(a=>Date.parse(a.attachment.expires_at)));Number.isFinite(y)&&!p&&(d=setTimeout(()=>{for(let a of m())a.item.status==="ready"&&Date.parse(a.item.attachment.expires_at)<=Date.now()&&(a.item={...a.item,status:"error",error:no()});h()},Math.min(2147483647,Math.max(0,y-Date.now()))),typeof d=="object"&&"unref"in d&&d.unref());for(let a of s)a();for(let a of[...o])a()}function P(){if(p)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function x(l){P();let y=m();if(y.length+l.length>20)throw new Error("A message can contain up to 20 attachments");if(l.some(A=>!Number.isSafeInteger(A)||A<=0||A>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(y.reduce((A,I)=>A+I.item.size,0)+l.reduce((A,I)=>A+I,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function _(){for(let l of r.values()){if(u>=n)break;if(l.item.status!=="pending"||!l.item.file||p&&!l.handedOff)continue;let y=l.item.file;u++;let a=++l.generation,A=new AbortController;l.abort=A,l.item={...l.item,status:"uploading",error:void 0};let I=()=>(!p||l.handedOff===!0)&&r.get(l.item.id)===l&&l.generation===a,R,w=0,F,j=()=>{F=void 0,!(!I()||l.item.status!=="uploading"||R===void 0)&&(l.item={...l.item,receivedBytes:R},R=void 0,w=Date.now(),h())},K=D=>Math.floor(D*100/l.item.size);Nt(e,y,{resume:l.upload,signal:A.signal,onUpload:D=>{l.upload=D,l.removed&&Oe(e,D.attachment_id).catch(()=>{})},onProgress:D=>{if(!I()||K(D)===K(l.item.receivedBytes)||(R=D,F))return;let b=w+_m-Date.now();if(b<=0)return j();F=setTimeout(j,b),typeof F=="object"&&"unref"in F&&F.unref()},onProcessing:()=>{F&&clearTimeout(F),F=void 0,R=void 0,I()&&(l.item={...l.item,status:"processing",receivedBytes:l.item.size},h())}}).then(D=>{I()&&(l.item={...l.item,status:"ready",attachment:ro(D),receivedBytes:D.size})}).catch(D=>{D instanceof S&&wm.has(D.code??"")&&(l.upload=void 0),I()&&(l.item={...l.item,status:D instanceof S&&D.code==="ABORTED"?"aborted":"error",error:D instanceof Error?D:new Error(String(D))})}).finally(()=>{u--,F&&clearTimeout(F),l.abort===A&&(l.abort=void 0),h(),_()})}h()}function v(l){x(l.map(a=>a.size));let y=l.map(a=>{let A=`attachment-${++Pm}`;return r.set(A,{generation:0,item:{id:A,file:a,filename:a.name,mime:a.type||"application/octet-stream",size:a.size,status:"pending",receivedBytes:0}}),A});return h(),_(),y}function M(l){let y=r.get(l);!y||y.item.status==="ready"||(y.generation++,y.abort?.abort(),y.item={...y.item,status:"aborted",error:new Error("Attachment upload cancelled")},h())}function $(l,{signal:y}={}){let a=[...l];return new Promise((A,I)=>{let R=()=>{o.delete(j),y?.removeEventListener("abort",F)},w=K=>{R(),I(K)},F=()=>w(_e()),j=()=>{let K=!1;for(let b of a){let T=r.get(b);if(!T)return w(new Error("Attachment was removed before it was sent"));if(p&&!T.handedOff)return w(new Error("Attachment controller is disposed"));if(T.item.status==="error"||T.item.status==="aborted")return w(T.item.error??new Error("Attachment upload failed"));T.item.status!=="ready"&&(K=!0)}if(K)return;let D;try{D=a.map(b=>{let T=ro(r.get(b).item.attachment);return{type:"file",attachment_id:T.attachment_id,filename:T.filename,mime:T.mime}})}catch(b){return w(b instanceof Error?b:new Error(String(b)))}R(),A(D)};if(y?.aborted)return F();o.add(j),y?.addEventListener("abort",F,{once:!0}),j()})}return{add:l=>v([l])[0],addMany:v,retry(l){let y=r.get(l);if(y?.handedOff||P(),!(!y||y.item.status==="ready"||y.item.status==="uploading"||y.item.status==="processing"||y.item.status==="pending")){if(!y.item.file||y.upload&&Date.parse(y.upload.expires_at)<=Date.now())throw no();y.item={...y.item,status:"pending",error:void 0},_()}},async remove(l){let y=r.get(l);if(!y)return;y.removed=!0,y.generation++,y.abort?.abort(),r.delete(l),h(),_();let a=y.upload?.attachment_id??y.item.attachment?.attachment_id;a&&Oe(e,a).catch(()=>{})},abort:M,submit(l){if(!p){for(let y of l){let a=r.get(y);a&&(a.handedOff=!0)}h()}},reclaim(l){if(!p){for(let y of l){let a=r.get(y);a&&(a.handedOff=!1)}h()}},whenReady:$,forget(l=m().map(y=>y.item.id)){for(let y of l){let a=r.get(y);a&&(a.generation++,a.abort?.abort(),r.delete(y))}h(),_()},dispose(){if(!p){p=!0,d&&clearTimeout(d);for(let l of r.values()){if(l.handedOff)continue;l.generation++,l.abort?.abort();let y=l.upload?.attachment_id??l.item.attachment?.attachment_id;y&&e&&Oe(e,y).catch(()=>{})}s.clear(),h()}},getSnapshot:()=>f,subscribe(l){return s.add(l),()=>{s.delete(l)}}}}async function io(){return c(await i.get("/accounts"))}async function oo(e){return c(await i.post("/accounts",e))}async function ao(e){return c(await i.get(`/accounts/${e}`))}async function co(e,t){return c(await i.patch(`/accounts/${e}`,{name:t}))}async function lo(e){return c(await i.get(`/accounts/${e}/branding`))}async function uo(e,t){return c(await i.put(`/accounts/${e}/branding`,t))}async function po(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),c(await i.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function go(e,t){return c(await i.delete(`/accounts/${e}/branding/assets/${t}`))}async function mo(e){return c(await i.delete(`/accounts/${e}/branding`))}async function fo(e){return c(await i.get(`/accounts/${e}/members`))}async function yo(e,t){return c(await i.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function ho(e){return c(await i.get(`/accounts/${e}/invites`))}async function bo(e,t){return c(await i.delete(`/accounts/${e}/invites/${t}`))}async function xo(e,t){return c(await i.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function _o(e){return c(await i.get(`/account-invites/${e}`,{showErrors:!1}))}async function Po(e){return c(await i.post(`/account-invites/${e}/accept`,{}))}async function wo(e){return c(await i.post(`/account-invites/${e}/decline`,{}))}async function ko(e,t){return c(await i.delete(`/accounts/${e}/members/${t}`))}async function So(e,t,n){return c(await i.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function vo(e){return c(await i.post(`/accounts/${e}/leave`,{}))}async function uP(e){return De(e,"/v1/accounts")}async function Ao(){let e=await i.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var mP=["agent_tunnel","marketplace","connectors_api_discover","agentmail_email","teams","llm_gateway","meta_agent","apps","monitors","warm_sessions","secrets_egress","pi_worker","pooled_provider_secrets"];async function qe(){return c(await i.get("/projects"))}async function Ro(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return c(await i.get(`/projects${t}`))}async function rs(e,t){return c(await i.get(`/projects/${e}`,t))}async function To(e,t,n="write"){return c(await i.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Io(e,t){return c(await i.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Eo(e){return c(await i.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function fP(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function ss(e,t){let n=c(await i.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 is(e,t){return c(await i.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function os(e,t){return c(await i.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function yP(e,t){return c(await i.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function jo(e){return c(await i.post("/projects",e))}async function $o(e){return c(await i.post("/projects/create-repo",e))}async function Mo(e,t={}){return c(await i.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Co=200;function km(e){let t=e.split(`
8
8
  `).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
9
- `);try{return JSON.parse(n)}catch(r){let s=n.length>Co?`${n.slice(0,Co)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function fP(e,t,n={}){let r=await i.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let d=await r.json().catch(()=>null);throw new S(d?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:d?.code})}let s=r.body?.getReader();if(!s)throw new Error("Provision stream is unavailable on this runtime (no response body)");let o=new TextDecoder,u="",p=null;try{for(;;){let{done:d,value:f}=await s.read();if(d)break;u+=o.decode(f,{stream:!0});let m=u.indexOf(`
9
+ `);try{return JSON.parse(n)}catch(r){let s=n.length>Co?`${n.slice(0,Co)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function hP(e,t,n={}){let r=await i.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let d=await r.json().catch(()=>null);throw new S(d?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:d?.code})}let s=r.body?.getReader();if(!s)throw new Error("Provision stream is unavailable on this runtime (no response body)");let o=new TextDecoder,u="",p=null;try{for(;;){let{done:d,value:f}=await s.read();if(d)break;u+=o.decode(f,{stream:!0});let m=u.indexOf(`
10
10
 
11
11
  `);for(;m!==-1;){let h=u.slice(0,m);u=u.slice(m+2),m=u.indexOf(`
12
12
 
13
- `);let P=Pm(h);if(P){if(t(P),P.type==="error")throw new S(P.error,{status:P.status,code:P.code});P.type==="done"&&(p=P.project)}}}}finally{s.cancel().catch(()=>{})}if(!p)throw new Error("Provision stream ended without a result");return p}async function yP(){try{return c(await i.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function os(e,t){return c(await i.patch(`/projects/${e}`,t))}async function Do(e,t,n){return c(await i.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Oo(e,t,n){return c(await i.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function qo(e,t){return c(await i.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function hP(e,t){return c(await i.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function bP(e,t){return c(await i.patch(`/projects/${e}/warm-pool`,t))}async function Uo(e,t){return c(await i.patch(`/projects/${e}/onboarding`,{completed:t}))}async function xP(e,t){return c(await i.patch(`/projects/${e}/onboarding`,{profile:t}))}async function as(e){return c(await i.delete(`/projects/${e}`))}async function _P(e,t){return De(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function PP(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=es(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let s=await r.json().catch(()=>null);return s?.project_id?{ok:!0,project:s}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function Fo(e){return c(await i.post("/projects/link-repository",e,{showErrors:!1}))}async function Lo(e){return c(await i.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Bo(e){return c(await i.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Go(e){return c(await i.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function No(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),c(await i.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function Ko(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return c(await i.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function Ho(e){return c(await i.post("/projects/github/installation",e,{showErrors:!1}))}async function Wo(e){return c(await i.post("/projects/github/installations/link",e,{showErrors:!1}))}async function zo(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),c(await i.delete(`/projects/github/installation?${n.toString()}`))}async function Vo(){return c(await i.get("/projects/git/backend",{showErrors:!1}))}async function Xo(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 c(await i.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function EP(e,t){return c(await i.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Jo(e,t){return c(await i.get(`/projects/${e}/access-requests`,t))}async function Qo(e,t,n="member"){return c(await i.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Yo(e,t){return c(await i.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Zo(e){return c(await i.get(`/projects/${e}/access`))}async function ea(e,t,n){return c(await i.put(`/projects/${e}/access/${t}`,{role:n}))}async function ta(e,t){return c(await i.delete(`/projects/${e}/access/${t}`))}function jP(e){return"status"in e&&e.status==="invited"}async function na(e,t,n,r){return c(await i.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function ra(e){return c(await i.get(`/projects/${e}/access/pending-invites`))}async function sa(e,t){return c(await i.delete(`/projects/${e}/access/pending-invites/${t}`))}async function ia(e,t){return c(await i.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function oa(e){return c(await i.get(`/projects/${e}/group-grants`))}async function aa(e,t,n,r){return c(await i.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function ca(e,t,n,r){return c(await i.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function la(e,t){return c(await i.delete(`/projects/${e}/group-grants/${t}`))}async function ua(e){return c(await i.get(`/projects/${e}/resource-grants`))}async function pa(e,t){return c(await i.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 da(e,t){return c(await i.delete(`/projects/${e}/resource-grants/${t}`))}async function ga(e,t){return c(await i.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function ma(e,t){return c(await i.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function fa(e,t,n){return c(await i.post(`/projects/${e}/approvals/${t}`,{decision:n}))}async function ya(e){return c(await i.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function ha(e,t){return c(await i.post(`/projects/${e}/secrets`,t))}async function ba(e,t,n,r={}){return c(await i.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function xa(e,t,n){return c(await i.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function _a(e,t,n){return c(await i.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel}}))}async function Pa(e,t,n){return c(await i.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function ka(e,t){return c(await i.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}async function wa(e,t){return c(await i.put(`/projects/${e}/git-credential`,t))}async function Sa(e,t){return c(await i.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function va(e,t,n){return c(await i.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Aa(e,t){return c(await i.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var cs=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Nt=(e,t)=>`${cs(e)}/${encodeURIComponent(t)}`,Ca=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Ra(e){return c(await i.get(cs(e)))}async function Ta(e,t){return c(await i.post(cs(e),t))}async function Ia(e,t,n){return c(await i.put(`${Nt(e,t)}/value`,{value:n}))}async function Ea(e,t){return c(await i.delete(Nt(e,t)))}async function ja(e,t,n,r){return c(await i.put(`${Nt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function $a(e,t,n,r){return c(await i.delete(`${Nt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function Ma(e,t,n){return c(await i.get(Ca(e,t,n)))}async function Da(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return c(await i.get(n))}async function Oa(e,t,n,r){return c(await i.put(Ca(e,t,n),{secret_ids:r}))}function ls(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function us(e){return c(await i.get(ls(e,"catalog"))).connectors??[]}async function Kt(e){let t=[];for(let n of await us(e))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(),s=r.split(/\s+/).filter(Boolean),o=[],u=[];for(let p of await Kt(e)){let d=`${p.tool} ${p.description}`.toLowerCase();!r||d.includes(r)?o.push(p):s.every(f=>d.includes(f))&&u.push(p)}return[...o,...u].slice(0,n.limit??20)}async function Ua(e,t){return(await Kt(e)).find(n=>n.tool===t)??null}function km(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 Fa(e,t,n={}){let{connector:r,action:s}=km(t);return c(await i.post(ls(e,"call"),{connector:r,action:s,args:n}))}function wm(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 Sm(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 La(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim()));let u=Sm(O().backendUrl),p=ls(e,"attachments"),d=await U(`${u}${p}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),f=await d.text(),m=null;if(f)try{m=JSON.parse(f)}catch{m=f}if(!d.ok)throw new S(wm(m,d.status),{status:d.status,code:String(m&&typeof m=="object"?m.code??d.status:d.status),details:m,response:d,endpoint:p});return m}async function Ba(e){return c(await i.get(`/projects/${e}/connections`))}async function Ga(e){return c(await i.get(`/projects/${e}/connections/all`))}async function Na(e,t){return c(await i.post(`/projects/${e}/connections`,t))}async function Ka(e,t){return c(await i.post(`/projects/${e}/connections/me`,t))}async function Ha(e,t,n){return c(await i.put(`/projects/${e}/connections/${t}/credential`,n))}function se(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function HP(e,t){return c(await i.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function WP(e,t,n){return c(await i.put(se(e,t,"application"),n))}async function zP(e,t){return c(await i.get(se(e,t,"application")))}async function VP(e,t,n){return c(await i.post(se(e,t,"discover"),n))}async function XP(e,t,n={}){return c(await i.post(se(e,t,"discover-resource"),n))}async function JP(e,t,n){return c(await i.post(se(e,t,"register"),n))}async function QP(e,t,n){return c(await i.post(se(e,t,"authorize"),n))}async function YP(e,t,n){return c(await i.post(se(e,t,"device"),n))}async function ZP(e,t,n){return c(await i.post(se(e,t,`device/${encodeURIComponent(n)}`),{}))}async function ek(e,t){return c(await i.get(se(e,t,"status")))}async function Wa(e,t){return c(await i.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function za(e,t){return c(await i.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Va(e,t){return c(await i.put(`/projects/${e}/connections/${t}/default`,{}))}async function Xa(e,t,n={}){return c(await i.post(`/projects/${e}/connections/${t}/connect`,n))}async function Ja(e,t){return c(await i.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Qa(e){return c(await i.get(`/connectors/projects/${e}/connectors`,{showErrors:!1}))}async function Ya(e){return c(await i.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Za(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function ec(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function tc(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function nc(e,t){return c(await i.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function rc(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function tk(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function nk(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function sc(e,t){return c(await i.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function ic(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function vm(e,t){return c(await i.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{}))}var oc=vm;async function rk(e,t){return c(await i.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function ac(e,t){return c(await i.post(`/connectors/projects/${e}/connectors`,t))}async function cc(e,t){return c(await i.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function lc(e,t){return c(await i.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function uc(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return c(await i.get(`/connectors/projects/${e}/pipedream/apps${o?`?${o}`:""}`))}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 c(await i.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function sk(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=c(await i.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function 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 c(await i.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function ps(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return c(await i.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function dc(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 c(await i.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function ds(e,t){let n=new URLSearchParams({id:t});return c(await i.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var ok=ps,ak=ds;async function gc(){return c(await i.get("/connectors/connect-status"))}async function mc(e,t,n){let r=typeof n=="string"?{value:n}:n;return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function ck(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Am(e,t){return c(await i.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,{}))}var fc=Am;async function yc(e){return c(await i.get(`/connectors/projects/${e}/policies`))}async function hc(e,t,n){return c(await i.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function bc(e){return c(await i.get(`/projects/${e}/sandboxes`))}async function xc(e){return c(await i.get(`/projects/${e}/snapshots`))}async function gs(e){return c(await i.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function _c(e,t){return c(await i.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Pc(e){return c(await i.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function kc(e,t){return c(await i.post(`/projects/${e}/sandbox-templates`,t))}async function wc(e,t,n){return c(await i.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Sc(e,t){return c(await i.delete(`/projects/${e}/sandbox-templates/${t}`))}async function vc(e,t){return c(await i.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Ac(e){return c(await i.get(`/projects/${e}/sandboxes`))}async function Cc(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 c(await i.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function Rc(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)),c(await i.get(`/projects/${e}/files/search?${r.toString()}`))}async function Tc(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),c(await i.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}async function Ic(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=await ae(),u=`${O().backendUrl||""}/projects/${e}/files/archive${s}`,p=await fetch(u,{method:"GET",headers:o?{Authorization:`Bearer ${o}`}:{}});if(!p.ok){let d=await p.text().catch(()=>"");throw new Error(d||`Failed to download (HTTP ${p.status})`)}return await p.blob()}async function Ec(e){return c(await i.get(`/projects/${e}/branches`))}async function jc(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 c(await i.get(`/projects/${e}/commits${r}`))}async function $c(e,t){return c(await i.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Mc(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return c(await i.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function Dc(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),c(await i.get(`/projects/${e}/files/history?${r.toString()}`))}async function Oc(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return c(await i.get(`/projects/${e}/version-diff?${n.toString()}`))}async function qc(e,t){let n=t?`?status=${t}`:"";return c(await i.get(`/projects/${e}/change-requests${n}`,{showErrors:!1,timeout:15e3}))}async function Uc(e,t){return c(await i.get(`/projects/${e}/change-requests/${t}`))}async function Fc(e,t){return c(await i.get(`/projects/${e}/change-requests/${t}/diff`))}async function Lc(e,t){return c(await i.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function Bc(e,t){return c(await i.post(`/projects/${e}/change-requests`,t))}async function Gc(e,t,n){return c(await i.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Nc(e,t){return c(await i.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Kc(e,t){return c(await i.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function Hc(e,t,n){return c(await i.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Wc(e,t,n){return c(await i.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}var ms=new Set;function Ht(e){e&&ms.add(e)}function zc(e){return!!e&&ms.has(e)}function Ck(e){e&&ms.delete(e)}var jk=50,Cm=200,$k=Cm;function Vc(e){let t=new URLSearchParams;return 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),t.size>0?`?${t}`:""}async function Xc(e,t){let n=await i.get(`/projects/${e}/sessions${Vc(t)}`);return{items:c(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function it(e,t){return c(await i.get(`/projects/${e}/sessions${Vc(t)}`))}async function Jc(e,t,n){return c(await i.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Qc(e,t){return c(await i.get(`/projects/${e}/sessions/${t}/previews`))}async function Yc(e,t){return c(await i.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Zc(e,t,n){return c(await i.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function el(e,t,n){return c(await i.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function ot(e,t){let n=c(await i.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||Ht(n?.session_id),n}async function tl(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=c(await i.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Ht(r.session.session_id),r}async function nl(e,t){let n=c(await i.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Ht(n.session_id),n}async function fs(e,t,n){return c(await i.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function rl(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return c(await i.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function sl(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return c(await i.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function il(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),c(await i.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1}))}async function ol(e,t){return c(await i.get(`/projects/${e}/sessions/${t}/turn`))}async function Mk(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return c(await i.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}async function al(e,t,n){return c(await i.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 cl(e,t){return c(await i.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function ll(e,t,n){return c(await i.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function ul(e,t,n){return c(await i.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function pl(e,t,n){return c(await i.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function dl(e,t,n){return c(await i.patch(`/projects/${e}/sessions/${t}`,n))}async function gl(e,t){return c(await i.delete(`/projects/${e}/sessions/${t}`))}async function Wt(e,t){return c(await i.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function zt(e,t){return c(await i.post(`/projects/${e}/sessions/${t}/stop`,{}))}async function ml(e,t){return c(await i.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function Rm(e){let t=e.split(`
13
+ `);let P=km(h);if(P){if(t(P),P.type==="error")throw new S(P.error,{status:P.status,code:P.code});P.type==="done"&&(p=P.project)}}}}finally{s.cancel().catch(()=>{})}if(!p)throw new Error("Provision stream ended without a result");return p}async function bP(){try{return c(await i.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function as(e,t){return c(await i.patch(`/projects/${e}`,t))}async function Do(e,t,n){return c(await i.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Oo(e,t,n){return c(await i.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function qo(e,t){return c(await i.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function xP(e,t){return c(await i.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function _P(e,t){return c(await i.patch(`/projects/${e}/warm-pool`,t))}async function Uo(e,t){return c(await i.patch(`/projects/${e}/onboarding`,{completed:t}))}async function PP(e,t){return c(await i.patch(`/projects/${e}/onboarding`,{profile:t}))}async function cs(e){return c(await i.delete(`/projects/${e}`))}async function wP(e,t){return De(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function kP(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=ts(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let s=await r.json().catch(()=>null);return s?.project_id?{ok:!0,project:s}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function Fo(e){return c(await i.post("/projects/link-repository",e,{showErrors:!1}))}async function Lo(e){return c(await i.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Bo(e){return c(await i.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Go(e){return c(await i.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function No(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),c(await i.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function Ko(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return c(await i.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function Ho(e){return c(await i.post("/projects/github/installation",e,{showErrors:!1}))}async function Wo(e){return c(await i.post("/projects/github/installations/link",e,{showErrors:!1}))}async function zo(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),c(await i.delete(`/projects/github/installation?${n.toString()}`))}async function Vo(){return c(await i.get("/projects/git/backend",{showErrors:!1}))}async function Xo(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 c(await i.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function $P(e,t){return c(await i.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function Jo(e,t){return c(await i.get(`/projects/${e}/access-requests`,t))}async function Qo(e,t,n="member"){return c(await i.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Yo(e,t){return c(await i.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Zo(e){return c(await i.get(`/projects/${e}/access`))}async function ea(e,t,n){return c(await i.put(`/projects/${e}/access/${t}`,{role:n}))}async function ta(e,t){return c(await i.delete(`/projects/${e}/access/${t}`))}function MP(e){return"status"in e&&e.status==="invited"}async function na(e,t,n,r){return c(await i.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function ra(e){return c(await i.get(`/projects/${e}/access/pending-invites`))}async function sa(e,t){return c(await i.delete(`/projects/${e}/access/pending-invites/${t}`))}async function ia(e,t){return c(await i.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function oa(e){return c(await i.get(`/projects/${e}/group-grants`))}async function aa(e,t,n,r){return c(await i.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function ca(e,t,n,r){return c(await i.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function la(e,t){return c(await i.delete(`/projects/${e}/group-grants/${t}`))}async function ua(e){return c(await i.get(`/projects/${e}/resource-grants`))}async function pa(e,t){return c(await i.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 da(e,t){return c(await i.delete(`/projects/${e}/resource-grants/${t}`))}async function ga(e,t){return c(await i.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function ma(e,t){return c(await i.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function fa(e,t,n){return c(await i.post(`/projects/${e}/approvals/${t}`,{decision:n}))}async function ya(e){return c(await i.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function ha(e,t){return c(await i.post(`/projects/${e}/secrets`,t))}async function ba(e,t,n,r={}){return c(await i.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function xa(e,t,n){return c(await i.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function _a(e,t,n){return c(await i.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel}}))}async function Pa(e,t,n){return c(await i.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function wa(e,t){return c(await i.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}async function ka(e,t){return c(await i.put(`/projects/${e}/git-credential`,t))}async function Sa(e,t){return c(await i.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function va(e,t,n){return c(await i.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Aa(e,t){return c(await i.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var ls=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,it=(e,t)=>`${ls(e)}/${encodeURIComponent(t)}`,Ca=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Ra(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return c(await i.get(`${ls(e)}${n}`))}async function Ta(e,t){return c(await i.post(ls(e),t))}async function Ia(e,t,n){return c(await i.put(`${it(e,t)}/value`,{value:n}))}async function Ea(e,t){return c(await i.delete(it(e,t)))}async function ja(e,t,n,r){return c(await i.put(`${it(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function $a(e,t,n,r){return c(await i.delete(`${it(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function Ma(e,t,n,r){return c(await i.put(`${it(e,t)}/access`,{mode:n,user_ids:r}))}async function Da(e,t,n){return c(await i.get(Ca(e,t,n)))}async function Oa(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return c(await i.get(n))}async function qa(e,t,n,r){return c(await i.put(Ca(e,t,n),{secret_ids:r}))}function Kt(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function us(e){return c(await i.get(Kt(e,"catalog"))).connectors??[]}async function Ht(e){let t=[];for(let n of await us(e))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 Ua(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],u=[];for(let p of await Ht(e)){let d=`${p.tool} ${p.description}`.toLowerCase();!r||d.includes(r)?o.push(p):s.every(f=>d.includes(f))&&u.push(p)}return[...o,...u].slice(0,n.limit??20)}async function Fa(e,t){return(await Ht(e)).find(n=>n.tool===t)??null}function Sm(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 La(e,t,n={},r={}){let{connector:s,action:o}=Sm(t),u=r.account?.trim();return c(await i.post(Kt(e,"call"),{connector:s,action:o,args:n,...u?{account:u}:{}}))}async function Ba(e,t){let n=await i.get(Kt(e,`connectors/${encodeURIComponent(t)}/accounts`));return c(n).accounts??[]}function vm(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 Am(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 Ga(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim()));let u=Am(O().backendUrl),p=Kt(e,"attachments"),d=await U(`${u}${p}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),f=await d.text(),m=null;if(f)try{m=JSON.parse(f)}catch{m=f}if(!d.ok)throw new S(vm(m,d.status),{status:d.status,code:String(m&&typeof m=="object"?m.code??d.status:d.status),details:m,response:d,endpoint:p});return m}async function Na(e){return c(await i.get(`/projects/${e}/connections`))}async function Ka(e){return c(await i.get(`/projects/${e}/connections/all`))}async function Ha(e,t){return c(await i.post(`/projects/${e}/connections`,t))}async function Wa(e,t){return c(await i.post(`/projects/${e}/connections/me`,t))}async function za(e,t,n){return c(await i.put(`/projects/${e}/connections/${t}/credential`,n))}function se(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function zP(e,t){return c(await i.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function VP(e,t,n){return c(await i.put(se(e,t,"application"),n))}async function XP(e,t){return c(await i.get(se(e,t,"application")))}async function JP(e,t,n){return c(await i.post(se(e,t,"discover"),n))}async function QP(e,t,n={}){return c(await i.post(se(e,t,"discover-resource"),n))}async function YP(e,t,n){return c(await i.post(se(e,t,"register"),n))}async function ZP(e,t,n){return c(await i.post(se(e,t,"authorize"),n))}async function ew(e,t,n){return c(await i.post(se(e,t,"device"),n))}async function tw(e,t,n){return c(await i.post(se(e,t,`device/${encodeURIComponent(n)}`),{}))}async function nw(e,t){return c(await i.get(se(e,t,"status")))}async function Va(e,t){return c(await i.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Xa(e,t){return c(await i.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Ja(e,t){return c(await i.put(`/projects/${e}/connections/${t}/default`,{}))}async function Qa(e,t,n={}){return c(await i.post(`/projects/${e}/connections/${t}/connect`,n))}async function Ya(e,t){return c(await i.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Za(e){return c(await i.get(`/connectors/projects/${e}/connectors`,{showErrors:!1}))}async function ec(e){return c(await i.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function tc(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function nc(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function rc(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function sc(e,t){return c(await i.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function ic(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function rw(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function sw(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function oc(e,t){return c(await i.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function ac(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function Cm(e,t,n={}){return c(await i.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,n.owner?{owner:n.owner}:{}))}var cc=Cm;async function iw(e,t){return c(await i.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function lc(e,t){return c(await i.post(`/connectors/projects/${e}/connectors`,t))}async function uc(e,t){return c(await i.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function pc(e,t){return c(await i.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function dc(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return c(await i.get(`/connectors/projects/${e}/pipedream/apps${o?`?${o}`:""}`))}async function gc(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return c(await i.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function ow(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=c(await i.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function aw(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 c(await i.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function ps(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return c(await i.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function mc(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 c(await i.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function ds(e,t){let n=new URLSearchParams({id:t});return c(await i.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var cw=ps,lw=ds;async function fc(){return c(await i.get("/connectors/connect-status"))}async function yc(e,t,n){let r=typeof n=="string"?{value:n}:n;return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function uw(e,t,n){return c(await i.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Rm(e,t){return c(await i.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,{}))}var hc=Rm;async function bc(e){return c(await i.get(`/connectors/projects/${e}/policies`))}async function xc(e,t,n){return c(await i.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function _c(e){return c(await i.get(`/projects/${e}/sandboxes`))}async function Pc(e){return c(await i.get(`/projects/${e}/snapshots`))}async function gs(e){return c(await i.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function wc(e,t){return c(await i.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function kc(e){return c(await i.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Sc(e,t){return c(await i.post(`/projects/${e}/sandbox-templates`,t))}async function vc(e,t,n){return c(await i.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Ac(e,t){return c(await i.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Cc(e,t){return c(await i.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Rc(e){return c(await i.get(`/projects/${e}/sandboxes`))}async function Tc(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 c(await i.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function Ic(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)),c(await i.get(`/projects/${e}/files/search?${r.toString()}`))}async function Ec(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),c(await i.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}async function jc(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=await ae(),u=`${O().backendUrl||""}/projects/${e}/files/archive${s}`,p=await fetch(u,{method:"GET",headers:o?{Authorization:`Bearer ${o}`}:{}});if(!p.ok){let d=await p.text().catch(()=>"");throw new Error(d||`Failed to download (HTTP ${p.status})`)}return await p.blob()}async function $c(e){return c(await i.get(`/projects/${e}/branches`))}async function Mc(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 c(await i.get(`/projects/${e}/commits${r}`))}async function Dc(e,t){return c(await i.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Oc(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return c(await i.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}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)),c(await i.get(`/projects/${e}/files/history?${r.toString()}`))}async function Uc(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return c(await i.get(`/projects/${e}/version-diff?${n.toString()}`))}async function Fc(e,t){let n=t?`?status=${t}`:"";return c(await i.get(`/projects/${e}/change-requests${n}`,{showErrors:!1,timeout:15e3}))}async function Lc(e,t){return c(await i.get(`/projects/${e}/change-requests/${t}`))}async function Bc(e,t){return c(await i.get(`/projects/${e}/change-requests/${t}/diff`))}async function Gc(e,t){return c(await i.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function Nc(e,t){return c(await i.post(`/projects/${e}/change-requests`,t))}async function Kc(e,t,n){return c(await i.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function Hc(e,t){return c(await i.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function Wc(e,t){return c(await i.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function zc(e,t,n){return c(await i.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function Vc(e,t,n){return c(await i.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}var ms=new Set;function Wt(e){e&&ms.add(e)}function Xc(e){return!!e&&ms.has(e)}function Tw(e){e&&ms.delete(e)}var Mw=50,Tm=200,Dw=Tm;function Jc(e){let t=new URLSearchParams;return 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),t.size>0?`?${t}`:""}async function Qc(e,t){let n=await i.get(`/projects/${e}/sessions${Jc(t)}`);return{items:c(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function ot(e,t){return c(await i.get(`/projects/${e}/sessions${Jc(t)}`))}async function Yc(e,t,n){return c(await i.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Zc(e,t){return c(await i.get(`/projects/${e}/sessions/${t}/previews`))}async function el(e,t){return c(await i.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function tl(e,t,n){return c(await i.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function nl(e,t,n){return c(await i.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function at(e,t){let n=c(await i.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||Wt(n?.session_id),n}async function rl(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=c(await i.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Wt(r.session.session_id),r}async function sl(e,t){let n=c(await i.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Wt(n.session_id),n}async function fs(e,t,n){return c(await i.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function il(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return c(await i.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function ol(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return c(await i.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function al(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),c(await i.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1}))}async function cl(e,t){return c(await i.get(`/projects/${e}/sessions/${t}/turn`))}async function Ow(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return c(await i.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}async function ll(e,t,n){return c(await i.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 ul(e,t){return c(await i.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function pl(e,t,n){return c(await i.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function dl(e,t,n){return c(await i.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function gl(e,t,n){return c(await i.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function ml(e,t,n){return c(await i.patch(`/projects/${e}/sessions/${t}`,n))}async function fl(e,t){return c(await i.delete(`/projects/${e}/sessions/${t}`))}async function zt(e,t){return c(await i.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Vt(e,t){return c(await i.post(`/projects/${e}/sessions/${t}/stop`,{}))}async function yl(e,t){return c(await i.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function Im(e){let t=e.split(`
14
14
  `).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).replace(/^ /,""));if(t.length===0)return null;try{return JSON.parse(t.join(`
15
- `))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function fl(e,t,n={}){return c(await i.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function yl(e,t,n,r,s={}){let o=await i.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,s);if(!o.ok){let m=await o.json().catch(()=>null);throw new S(m?.error||`Reload failed: HTTP ${o.status}`,{status:o.status,code:m?.code,data:m})}let u=o.body?.getReader();if(!u)throw new Error("Reload stream is unavailable on this runtime (no response body)");let p=new TextDecoder,d="",f=null;try{for(;;){let{done:m,value:h}=await u.read();if(m)break;d+=p.decode(h,{stream:!0});let P=d.indexOf(`
15
+ `))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function hl(e,t,n={}){return c(await i.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function bl(e,t,n,r,s={}){let o=await i.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,s);if(!o.ok){let m=await o.json().catch(()=>null);throw new S(m?.error||`Reload failed: HTTP ${o.status}`,{status:o.status,code:m?.code,data:m})}let u=o.body?.getReader();if(!u)throw new Error("Reload stream is unavailable on this runtime (no response body)");let p=new TextDecoder,d="",f=null;try{for(;;){let{done:m,value:h}=await u.read();if(m)break;d+=p.decode(h,{stream:!0});let P=d.indexOf(`
16
16
 
17
17
  `);for(;P!==-1;){let x=d.slice(0,P);d=d.slice(P+2),P=d.indexOf(`
18
18
 
19
- `);let _=Rm(x);if(_){if(r(_),_.type==="error")throw new S(_.error,{status:_.status,code:_.code,data:{reason:_.reason}});_.type==="done"&&(f=_.result)}}}}finally{u.cancel().catch(()=>{})}if(!f)throw new Error("Reload stream ended without a result");return f}async function hl(e,t){return c(await i.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function bl(e,t,n){return c(await i.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function xl(e,t,n){return c(await i.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{opencode_model:n}))}async function _l(e){return c(await i.get(`/projects/${e}/triggers`))}async function Pl(e,t){return c(await i.post(`/projects/${e}/triggers`,t))}async function kl(e,t,n){return c(await i.patch(`/projects/${e}/triggers/${t}`,n))}async function wl(e,t){return c(await i.delete(`/projects/${e}/triggers/${t}`))}async function Sl(e,t){return c(await i.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function vl(e,t){return c(await i.post(`/projects/${e}/triggers/${t}/fire`,{}))}var de=new Map;function ys(e,t){return`${e}::${t}`}function Al(e,t){de.delete(e),de.set(e,t)}function Cl(e,t){let n=ys(e,t),r=de.get(n);return r&&Al(n,r),r}function Rl(e,t,n){let r=ys(e,t);if(!de.has(r)&&de.size>=512){let s=de.keys().next().value;s!==void 0&&de.delete(s)}Al(r,n)}function Tl(e,t){de.delete(ys(e,t))}function Kk(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!e.opencode_session_id)return null;let t=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return t?{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:t,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},opencode_session_id:e.opencode_session_id,runtime_url:e.sandbox_url}:null}var hs=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 Hk(e){return e instanceof Error&&e.name==="SessionStartError"}function Tm(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new hs(s,{status:n,code:r,terminal:!0}):null}async function Ue(e,t,n){let r=n&&n>0?`?wait_ms=${Math.floor(n)}`:"",s=await i.post(`/projects/${e}/sessions/${t}/start${r}`,{},{showErrors:!1});if(!s.success||!s.data){let p=Tm(s.error);if(p&&!(p.status===404&&zc(t)))throw p;return null}let o=s.data,u=o.sandbox?.external_id;return o.stage==="ready"&&u&&o.opencode_session_id&&Rl(e,t,{opencodeSessionId:o.opencode_session_id,runtimeUrl:Pt(u),sandboxId:u}),o}function Wk(e,t){return["session-start",e,t]}async function Il(e){return c(await i.get(`/projects/${e}/model-defaults`))}async function El(e,t){return c(await i.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 c(await i.delete(`/projects/${e}/model-defaults?${n}`))}async function Zk(e,t){return c(await i.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}async function Ml(e,t,n){let r=Em(n);return c(await i.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}function $l(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Im(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Em(e){let t=e.connectors_required?$l(e.connectors_required):void 0,n=e.connectors_personal?$l(e.connectors_personal):void 0;if(t&&n&&!Im(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 ow(e,t){let n=c(await i.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?bs(n.block):null}}async function aw(e,t,n){let r=bs(n,!0),s=c(await i.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?bs(s.block):null}}function bs(e,t=!1){let n=$m(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}function Dl(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function jm(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function $m(e){let t=e.connectors_required?Dl(e.connectors_required):void 0,n=e.connectors_personal?Dl(e.connectors_personal):void 0;if(t&&n&&!jm(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 cw(e,t,n){return c(await i.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Ol(e,t){return c(await i.put(`/projects/${e}/default-agent`,{agent:t}))}function xs(){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 Mm(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function dw(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,isGrandfathered:t.is_grandfathered===!0};let n=e??xs(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:Mm(r),label:s,sublabel:null,isGrandfathered:!1}}async function ql(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString(),r=n?`?${n}`:"",s=await i.get(`/billing/account-state${r}`,{showErrors:!1}),o=s.error?.status===404&&/billing is not enabled/i.test(s.error.message||"");if(s.error&&s.error.status!==401&&!o)throw s.error;return s.error?xs():s.data}async function Ul(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString(),r=n?`?${n}`:"",s=await i.get(`/billing/account-state/minimal${r}`,{showErrors:!1}),o=s.error?.status===404&&/billing is not enabled/i.test(s.error.message||"");if(s.error&&s.error.status!==401&&!o)throw s.error;return s.error?xs():s.data}async function Fl(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 c(await i.get(`/billing/transactions${n?`?${n}`:""}`))}async function Ll(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 c(await i.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Bl(){return c(await i.get("/billing/credit-breakdown"))}async function Gl(e){let t=e!=null?`?days=${e}`:"";return c(await i.get(`/billing/usage-history${t}`))}async function Nl(){return c(await i.get("/billing/tier-configurations"))}async function gw(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return De(e,`/v1/billing/account-state${t}`)}async function Kl(e){return c(await i.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 Hl(e,t){return c(await i.post("/billing/confirm-checkout-session",{account_id:t,session_id:e}),"Failed to confirm checkout session")}async function Wl(e,t){return c(await i.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function zl(e,t){return c(await i.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Vl(e){return c(await i.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Xl(e,t,n){return c(await i.post("/billing/schedule-downgrade",{account_id:n,target_tier_key:e,commitment_type:t}),"Failed to schedule downgrade")}async function Jl(e){return c(await i.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function Ql(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),c(await i.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function Yl(e){return c(await i.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 Zl(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return c(await i.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function eu(e){return c(await i.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 mw(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return c(await i.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function fw(e){return c(await i.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 yw(e){return c(await i.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function hw(e){return c(await i.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function tu(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 c(await i.get(`/usage${n?`?${n}`:""}`))}function _s(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Vt(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Xt(e){return e.size>0?`?${e}`:""}async function ru(e={}){let t=new URLSearchParams;return _s(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Vt(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)),c(await i.get(`/usage/session-costs${Xt(t)}`))}async function Ps(e,t={}){let n=new URLSearchParams;return _s(n,t),c(await i.get(`/usage/session-costs/${encodeURIComponent(e)}${Xt(n)}`))}async function ww(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Vt(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)),c(await i.get(`/usage/cost-by-project${Xt(t)}`))}async function Sw(e={}){let t=new URLSearchParams;return _s(t,e),e.sessionId&&t.set("session_id",e.sessionId),Vt(t,e),c(await i.get(`/usage/cost-summary${Xt(t)}`))}function nu(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),e==="sessions"){let s=t;s.projectId&&n.set("project_id",s.projectId),s.ownerId&&n.set("owner_id",s.ownerId)}Vt(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`${O().backendUrl||""}${r}?${n}`}async function vw(e,t={}){let n=nu(e==="projects"?"projects":"sessions",t),r=await ae(),s=await fetch(n,{method:"GET",headers:r?{Authorization:`Bearer ${r}`}:{}});if(!s.ok){let d=await s.text().catch(()=>"");throw new Error(d||`Failed to export CSV (HTTP ${s.status})`)}let o=s.headers.get("x-kortix-row-cap"),u=o!=null?Number(o):NaN;return{blob:await s.blob(),rowCap:Number.isFinite(u)?u:null}}async function su(e,t){return c(await i.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function Tw(e){return su("slack",e)}function Iw(e){return su("teams",e)}async function iu(e){let t=await i.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function ou(e,t){return c(await i.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var Dm={oauth_available:!1,install_url:null};async function au(e){let t=await i.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?Dm:t.data}async function cu(e){return c(await i.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function lu(e){let t=await i.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function uu(e,t){return c(await i.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function pu(e,t){return c(await i.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 ks(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 Om={provider:"agentmail",managed_available:!1};async function du(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await i.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?ks(r.data):null}async function gu(e){let t=await i.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Om:t.data}async function mu(e,t){let n=c(await i.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return ks(n)}async function fu(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await i.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 yu(e,t,n){let r=c(await i.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return ks(r)}async function Ew(e){return c(await i.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function jw(e,t,n){return c(await i.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function hu(e){return c(await i.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function bu(e,t){return c(await i.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function xu(e){return c(await i.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function _u(e,t){return c(await i.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Pu(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return c(await i.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function ku(e,t){return c(await i.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function wu(e,t){return c(await i.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Su(e,t){return c(await i.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function vu(e,t){return c(await i.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Au(e,t){return c(await i.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Cu(e,t){return c(await i.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ru(e){return c(await i.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Tu(e,t){return c(await i.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Iu(e,t){return c(await i.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Eu(e){return c(await i.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function ju(e,t){return c(await i.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function $u(e,t){return c(await i.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Mu(e,t,n,r,s){return c(await i.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function Ow(e,t){return c(await i.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function Lw(){return c(await i.get("/referrals/code"),"GET_CODE_FAILED")}async function Bw(){return c(await i.post("/referrals/code/refresh",{}),"REFRESH_CODE_FAILED")}async function Gw(e){return c(await i.post("/referrals/validate",{referral_code:e}),"VALIDATE_CODE_FAILED")}async function Nw(){return c(await i.get("/referrals/stats"),"GET_STATS_FAILED")}async function Kw(e={}){let t=new URLSearchParams({limit:String(e.limit??50),offset:String(e.offset??0)});return c(await i.get(`/referrals/list?${t}`),"GET_REFERRALS_FAILED")}async function Hw(e){return c(await i.post("/referrals/email",{emails:e}),"SEND_EMAILS_FAILED")}function C(e){if(!e.success||e.data===void 0)throw e.error||new Error("Unexpected empty response");return e.data}function L(e){return i.get(e,{showErrors:!1})}async function Du(e){return C(await L(`/accounts/${e}/iam/groups`)).groups}async function Ou(e,t){return C(await L(`/accounts/${e}/iam/groups/${t}`))}async function qu(e,t){return C(await i.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Uu(e,t,n){return C(await i.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Fu(e,t){return C(await i.delete(`/accounts/${e}/iam/groups/${t}`))}async function Lu(e,t){return C(await L(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Bu(e,t,n){return C(await i.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function Vw(e,t){return C(await L(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Gu(e,t,n){return C(await i.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function Xw(e,t){return C(await L(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function Jw(e,t){let n=C(await L(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}async function Qw(e,t={}){let n=new URLSearchParams;t.resourceType&&n.set("resourceType",t.resourceType),t.principalType&&n.set("principalType",t.principalType),t.principalId&&n.set("principalId",t.principalId),t.projectId&&n.set("projectId",t.projectId);let r=n.toString();return C(await L(`/accounts/${e}/iam/resource-grants${r?`?${r}`:""}`)).grants}async function Yw(e,t={}){let n=new URLSearchParams;t.principalType&&n.set("principalType",t.principalType),t.principalId&&n.set("principalId",t.principalId),t.scopeType&&n.set("scopeType",t.scopeType),t.scopeId!==void 0&&n.set("scopeId",t.scopeId===null?"null":t.scopeId);let r=n.toString();return C(await L(`/accounts/${e}/iam/policies${r?`?${r}`:""}`)).policies}async function Zw(e,t){return C(await i.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function eS(e,t,n){return C(await i.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function tS(e,t){return C(await i.delete(`/accounts/${e}/iam/policies/${t}`))}async function nS(e,t){return C(await i.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function rS(e,t){return C(await i.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Nu(e){return C(await L(`/accounts/${e}/iam/roles`)).roles}async function Ku(e){return C(await L(`/accounts/${e}/iam/agent-identities`)).agents}async function Hu(e,t){return C(await L(`/accounts/${e}/iam/roles/${t}/permissions`))}async function sS(e){return C(await L(`/accounts/${e}/iam/actions`)).actions}async function Wu(e,t){return C(await L(`/accounts/${e}/iam/roles/${t}/usage`))}async function zu(e,t){return C(await i.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Vu(e,t,n){return C(await i.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Xu(e,t,n){return C(await i.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Ju(e,t){return C(await i.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function iS(e,t,n){return C(await i.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function oS(e){return C(await L(`/accounts/${e}/iam/scim/tokens`)).tokens}async function aS(e,t){return C(await i.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function cS(e,t){return C(await i.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function lS(e){return C(await L(`/accounts/${e}/iam/mfa-required`))}async function uS(e){return C(await L(`/accounts/${e}/iam/mfa-required/preview`))}async function pS(e,t){return C(await i.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function dS(e){return C(await L(`/accounts/${e}/iam/sso/provider`)).provider}async function gS(e,t){return C(await i.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function mS(e,t){return C(await i.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function fS(e){return C(await i.delete(`/accounts/${e}/iam/sso/provider`))}async function yS(e){return C(await L(`/accounts/${e}/iam/sso/mappings`)).mappings}async function hS(e,t){return C(await i.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function bS(e,t){return C(await i.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function xS(e){return C(await L(`/accounts/${e}/iam/session-policy`))}async function _S(e,t){return C(await i.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function PS(e){return C(await L(`/accounts/${e}/iam/sessions`)).sessions}async function kS(e,t){return C(await i.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function wS(e){return C(await L(`/accounts/${e}/iam/pat-policy`))}async function SS(e,t){return C(await i.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function vS(e){return C(await L(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function AS(e,t){return C(await i.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function CS(e,t){return C(await i.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function RS(e,t){return C(await i.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function TS(e){return C(await L(`/accounts/${e}/audit/webhooks`)).webhooks}async function IS(e,t){return C(await i.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function ES(e,t,n){return C(await i.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function jS(e,t){return C(await i.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function $S(e,t={}){let n=new URLSearchParams;t.action&&n.set("action",t.action),t.actor&&n.set("actor",t.actor),t.project_id&&n.set("project_id",t.project_id),t.session_id&&n.set("session_id",t.session_id),t.actor_type&&n.set("actor_type",t.actor_type),t.source&&n.set("source",t.source),t.phase&&n.set("phase",t.phase),t.outcome&&n.set("outcome",t.outcome),t.request_id&&n.set("request_id",t.request_id),t.correlation_id&&n.set("correlation_id",t.correlation_id),t.resource_type&&n.set("resource_type",t.resource_type),t.since&&n.set("since",t.since),t.until&&n.set("until",t.until),t.q&&n.set("q",t.q),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString();return C(await L(`/accounts/${e}/audit${r?`?${r}`:""}`))}async function Qu(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),C(await L(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Yu(e,t,n){return n.length===0?[]:C(await i.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function MS(e){return C(await L(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function DS(e,t){return C(await i.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function Zu(e){return c(await i.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function ep(e,t){return c(await i.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function tp(e,t){return c(await i.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function np(e,t,n){return c(await i.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function rp(e,t){return c(await i.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function sp(e,t){return c(await i.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function ip(e){return i.get(e,{showErrors:!1})}function qm(e){let t=new URLSearchParams;e?.principalType&&t.set("principal_type",e.principalType),e?.principalId&&t.set("principal_id",e.principalId),e?.scopeType&&t.set("scope_type",e.scopeType),e?.scopeId&&t.set("scope_id",e.scopeId),e?.objectType&&t.set("object_type",e.objectType),e?.objectId&&t.set("object_id",e.objectId),e?.roleId&&t.set("role_id",e.roleId),e?.includeExpired&&t.set("include_expired","true");let n=t.toString();return n?`?${n}`:""}async function op(e,t){return c(await ip(`/accounts/${e}/iam/assignments${qm(t)}`)).assignments}async function ap(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),c(await i.post(`/accounts/${e}/iam/assignments`,n))}async function cp(e,t){return c(await i.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function lp(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return c(await ip(`/accounts/${e}/iam/permissions${n}`)).permissions}async function HS(){let e=await i.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:c(e,"Failed to load account deletion status")}async function WS(e="User requested deletion"){return c(await i.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function zS(){return c(await i.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function VS(){return c(await i.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function XS(){return(await i.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function ZS(){return i.get("/admin/api/provider-distribution").then(e=>c(e))}function ev(e=300){return i.get(`/admin/api/sandboxes?limit=${e}`).then(t=>c(t))}function tv(e){return i.put("/admin/api/provider-distribution",e).then(t=>c(t))}function nv(e){return i.get(`/admin/api/provider-analytics?days=${e}`).then(t=>c(t))}function rv(e,t){return i.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>c(n))}function sv(){return i.get("/admin/api/provider-fallback").then(e=>c(e))}function iv(e){return i.put("/admin/api/provider-fallback",{enabled:e}).then(t=>c(t))}async function lv(e){return c(await i.get(`/google/auth-url?return_url=${encodeURIComponent(e)}`),"Failed to get Google auth URL")}async function uv(e,t){return c(await i.post("/presentation-tools/convert-and-upload-to-slides",{presentation_path:e,sandbox_url:t},{timeout:18e4}),"Failed to upload to Google Slides")}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 c(await i.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function pp(e,t){return c(await i.get(`/projects/${e}/review/items/${t}`))}async function dp(e,t){return c(await i.post(`/projects/${e}/review/items`,t))}async function gp(e,t,n){return c(await i.post(`/projects/${e}/review/items/${t}/act`,n))}async function mp(e,t){return c(await i.post(`/projects/${e}/review/bulk`,t))}async function fp(e){return c(await i.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function yp(e){return c(await i.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 i.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var ws=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function bp(e,t=""){return`${ze()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function xp(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let s=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new ws(s,t.status)}return r}async function xv(e){return xp(bp(e))}async function _v(e){return xp(bp(e,"/messages"))}async function _p(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 c(await i.get(`/accounts/tokens${r}`))}async function Pp(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return c(await i.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function kp(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return c(await i.delete(`/accounts/tokens/${e}${n}`))}async function wp(e){return c(await i.get(`/projects/${e}/cli-token`))}async function Sp(e,t){return c(await i.post(`/projects/${e}/cli-token`,t??{}))}async function vp(e,t){return c(await i.delete(`/projects/${e}/cli-token/${t}`))}async function Ap(e,t){let n=new URLSearchParams;t?.action&&n.set("action",t.action),t?.actor&&n.set("actor",t.actor),t?.actorType&&n.set("actor_type",t.actorType),t?.projectId&&n.set("project_id",t.projectId),t?.sessionId&&n.set("session_id",t.sessionId),t?.source&&n.set("source",t.source),t?.phase&&n.set("phase",t.phase),t?.outcome&&n.set("outcome",t.outcome),t?.resourceType&&n.set("resource_type",t.resourceType),t?.requestId&&n.set("request_id",t.requestId),t?.correlationId&&n.set("correlation_id",t.correlationId),t?.since&&n.set("since",t.since),t?.until&&n.set("until",t.until),t?.q&&n.set("q",t.q),t?.cursor&&n.set("cursor",t.cursor),t?.limit!=null&&n.set("limit",String(t.limit));let r=n.toString();return c(await i.get(`/accounts/${e}/audit${r?`?${r}`:""}`))}async function Cp(e,t){let n=new URLSearchParams;t?.action&&n.set("action",t.action),t?.actor&&n.set("actor",t.actor),t?.actorType&&n.set("actor_type",t.actorType),t?.sessionId&&n.set("session_id",t.sessionId),t?.source&&n.set("source",t.source),t?.phase&&n.set("phase",t.phase),t?.outcome&&n.set("outcome",t.outcome),t?.resourceType&&n.set("resource_type",t.resourceType),t?.requestId&&n.set("request_id",t.requestId),t?.correlationId&&n.set("correlation_id",t.correlationId),t?.since&&n.set("since",t.since),t?.until&&n.set("until",t.until),t?.q&&n.set("q",t.q),t?.cursor&&n.set("cursor",t.cursor),t?.limit!=null&&n.set("limit",String(t.limit));let r=n.toString();return c(await i.get(`/projects/${e}/audit${r?`?${r}`:""}`))}async function Rp(e,t){let n=new URLSearchParams;t?.format&&n.set("format",t.format),t?.action&&n.set("action",t.action),t?.actor&&n.set("actor",t.actor),t?.actorType&&n.set("actor_type",t.actorType),t?.projectId&&n.set("project_id",t.projectId),t?.sessionId&&n.set("session_id",t.sessionId),t?.source&&n.set("source",t.source),t?.phase&&n.set("phase",t.phase),t?.outcome&&n.set("outcome",t.outcome),t?.resourceType&&n.set("resource_type",t.resourceType),t?.requestId&&n.set("request_id",t.requestId),t?.correlationId&&n.set("correlation_id",t.correlationId),t?.since&&n.set("since",t.since),t?.until&&n.set("until",t.until),t?.q&&n.set("q",t.q),t?.cursor&&n.set("cursor",t.cursor),t?.limit!=null&&n.set("limit",String(t.limit));let r=n.toString();return c(await i.get(`/accounts/${e}/audit/export${r?`?${r}`:""}`))}async function Tp(e){return c(await i.get(`/accounts/${e}/audit/webhooks`))}async function Ip(e,t){return c(await i.post(`/accounts/${e}/audit/webhooks`,t))}async function Ep(e,t,n){return c(await i.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function jp(e,t){return c(await i.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function $p(e,t){return c(await i.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 Mp(e,t){return c(await i.post(`/projects/${e}/connect-requests`,{slug:t.slug,expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function Iv(e){return c(await i.get(`/approval-links/${e}`),"Failed to load approval")}async function Dp(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return c(await i.get(`/marketplace/items${n}`))}async function Op(){return c(await i.get("/marketplace/marketplaces"))}async function qp(){return c(await i.get("/marketplace/marketplaces/featured"))}async function Up(e){return c(await i.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Fp(e,t){return c(await i.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Lp(){return c(await i.get("/marketplace/sources"))}async function Bp(e){return c(await i.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Gp(e){return c(await i.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function Mv(e,t){return c(await i.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function Uv(e){return c(await i.get(`/templates/${encodeURIComponent(e)}`))}async function Fv(e,t){return c(await i.post(`/templates/${encodeURIComponent(e)}/install`,t))}async function Np(e){return c(await i.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Kp(e,t){return c(await i.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Hp(e,t){return c(await i.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Wp(e,t,n){return c(await i.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function zp(e,t){return c(await i.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Vp(e,t){return c(await i.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Xp(e,t,n){return c(await i.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Jp(e,t){return c(await i.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Ss(e,t){return c(await i.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function vs(e,t,n){return c(await i.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function Um(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function Fm(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 Qp(e,t,n={}){let r=await Um(t),s=n.mediaType??"application/gzip",o=await Ss(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let u=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!u.ok){let p=await u.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${u.status}${p?`: ${p}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),vs(e,o.artifact.artifact_id,{sha256:await Fm(r),size_bytes:r.byteLength})}async function Yp(e,t,n){return c(await i.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Zp(e,t){return c(await i.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function ed(e,t,n){return c(await i.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function td(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return c(await i.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function nd(e,t){return c(await i.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function rd(e,t){return c(await i.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function sd(e,t,n){return c(await i.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}async function As(e){return c(await i.get(`/projects/${e}/model-access`))}async function Cs(e,t){return c(await i.put(`/projects/${e}/model-access`,t))}var at=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};function Lm(e){let t=ue(e?.backendUrl??O().backendUrl??"");if(!t)throw new at("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);return t.endsWith("/v1")?t:`${t}/v1`}async function V(e,t,n){let r=n?.fetch??O().fetch??((d,f)=>fetch(d,f)),s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let o=await r(`${Lm(n)}${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}:{}}),u=await o.text().catch(()=>""),p=null;try{p=u?JSON.parse(u):null}catch{p=u}if(!o.ok){let d=p&&typeof p=="object"?p:{};throw new at(typeof d.error=="string"?d.error:"auth_error",typeof d.error_description=="string"&&d.error_description?d.error_description:typeof d.error=="string"?d.error:o.statusText||`HTTP ${o.status}`,o.status)}return p}function Rs(e,t){return V("/auth/signup",{body:e},t)}function Ts(e,t){return V("/auth/sign-in/password",{body:e},t)}function Is(e,t){return V("/auth/sign-in/magic-link",{body:e},t)}function Es(e,t){return V("/auth/verify-otp",{body:e},t)}function js(e,t){return V("/auth/sign-in/oauth",{body:e},t)}function $s(e,t){return V("/auth/oauth/exchange",{body:e},t)}function ct(e,t){return V("/auth/refresh",{body:e},t)}function Ms(e,t){return V("/auth/password/reset",{body:e},t)}function Ds(e,t,n){return V("/auth/password/update",{body:e,bearer:t},n)}function Os(e,t){return V("/auth/user",{bearer:e},t)}function qs(e,t,n){return V("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function Us(e,t){return V("/auth/sign-in/sso",{body:e},t)}var Fs={enroll:(e,t,n)=>V("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>V(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>V(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>V(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function Ls(e,t={},n){return V("/auth/sign-out",{body:t,bearer:e},n)}function Bs(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,u=null,p=new Set,d=x=>(x.expires_at??0)*1e3,f=x=>d(x)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let x of[...p])try{x(r)}catch{}try{e.onChange?.(r)}catch{}}async function h(){if(o)return r;o=!0;let x=await e.storage.get();if(x)try{let _=JSON.parse(x);_.session?.access_token&&_.session?.refresh_token&&(r=_.session,s=_.user??null)}catch{r=null}return r}async function P(){if(await h(),!r)return null;if(!u){let x=r.refresh_token;u=ct({refresh_token:x},e.request).then(async _=>(r=_.session,_.user&&(s=_.user),await m(),r)).catch(async _=>{let v=_&&typeof _=="object"&&"status"in _?_.status:0;if(v>=400&&v<500)return r=null,s=null,await m(),null;throw _}).finally(()=>{u=null})}return u}return{subscribe(x){return p.add(x),()=>{p.delete(x)}},current:()=>r,user:()=>s,load:h,async set(x,_){await h(),r=x,_!==void 0&&(s=_),x||(s=null),await m()},async getToken(){return await h(),r?f(r)?(await P().catch(()=>r))?.access_token??null:r.access_token:null},refresh:P,async clear(){r=null,s=null,o=!0,await m()}}}var Gm=["control_plane","provider_ingress","daemon","upstream_port"];function id(e){return typeof e=="string"&&Gm.includes(e)?e:null}function Zv(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function od(e,t){let n=(e===void 0?re():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await U(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let u=o,p=id(r.headers.get("X-Kortix-Proxy-Hop"))??id(o?.hop),d=Number(r.headers.get("X-Kortix-Upstream-Status")),f=o?.upstream_status,m=Number.isFinite(d)&&d>0?d:typeof f=="number"?f:null;return{status:r.status,ok:r.ok,health:u,body:s,hop:p,upstreamStatus:m}}var ge={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};var ad=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,cd=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,ld=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,ud=new Set([22,4096,parseInt(ge.KORTIX_MASTER,10)]);function Nm(e){return cd.test(e)}function Jt(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 Km(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var Hm=new Set(["'",'"',"`","<","(","["]),Wm=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function zm(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&&Hm.has(e[t]);)t++;for(;n>t&&Wm.has(e[n-1]);)n--;return e.slice(t,n)}function Vm(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var Xm=/^\/proxy\/(\d{1,5})(\/.*)?$/,Jm=/^\/(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 Qm(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:Jm.test(t.pathname)}catch{return!1}}function Qt(e){if(!e)return null;let t=zm(Km(e.trim())),n=fd(t);if(n){let r=Jt(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,u=parseInt(ge.KORTIX_MASTER,10);if(s===u){let d=r.pathname.match(Xm);if(d){let f=parseInt(d[1],10);if(f>=1&&f<=65535)return s=f,o=Jt(`${d[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let p=Jt(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${p}`,port:s,path:p}}catch{let r=Vm(e);return r&&r!==e?Qt(r):null}}function Ym(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,u=o+r[0].length;t.some(([d,f])=>o>=d&&u<=f)||t.push([o,u])}return t}function Zm(e,t){return t.some(([n,r])=>e>=n&&e<r)}function ef(e){let t=[],n=new Set,r=Ym(e);ad.lastIndex=0;let s;for(;(s=ad.exec(e))!==null;){let o=Qt(s[0]);if(!o)continue;let{originalUrl:u,port:p,path:d}=o;p<1||p>65535||ud.has(p)||n.has(u)||(n.add(u),t.push({originalUrl:u,port:p,path:d,startIndex:s.index,endIndex:s.index+u.length,inCodeBlock:Zm(s.index,r)}))}return t}function rA(e){return ef(e).length>0}function tf(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function pd(e){return e.trim().toLowerCase().split("_").join("-")}function dd(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function nf(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let s=r.split("{port}").join(String(e)).split("{sandbox}").join(pd(n.sandboxId));return`${dd(s)}${t}`}function rf(e){return e.sandboxId.trim().length>0}function Se(e,t,n){let r=Jt(t);if(!rf(n))return cf(e,r);let s=nf(e,r,n);return s||(tf(n.apiBaseUrl)?`http://p${e}-${pd(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${dd(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function sA(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return Se(3211,`/open?path=/workspace/${r}`,t)}function sf(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function iA(e){return`http://localhost:3211${sf(e)}`}function of(){return"/health"}function oA(e){return Se(3211,of(),e)}function aA(e,t){return Se(e,"/",t)}function af(e){let t=Qt(e);return!(!t||ud.has(t.port)||Qm(e))}function gd(e,t){if(!e)return e;let n=Qt(e);return n?af(n.originalUrl)?Se(n.port,n.path,t):n.originalUrl:e}function cf(e,t="/"){return`http://localhost:${e}${t}`}var md=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function fd(e){let t=e.match(cd);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(ld);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(md);if(r)try{let s=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(s.port,10)||(s.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function cA(e){try{let t=fd(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function lA(e){return Nm(e)||ld.test(e)||md.test(e)}function uA(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var lt="/web-proxy/";function pA(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${lt}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(ge.KORTIX_MASTER,10);return`${Se(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function dA(e){try{let t=new URL(e),n=t.pathname.indexOf(lt);if(n===-1)return null;let s=t.pathname.slice(n+lt.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],u=s[2],p=s[3]||"/";return`${o}://${u}${p}${t.search}${t.hash}`}catch{return null}}function gA(e){try{return new URL(e).pathname.includes(lt)}catch{return e.includes(lt)}}function mA(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 fA(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}var yd="frontend";function Yt(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${yd}] ${t}`,...n?[n]:[]);try{Pe().app.log({service:yd,level:e,message:t,extra:n})}catch{}}var me={debug:(e,t)=>Yt("debug",e,t),info:(e,t)=>Yt("info",e,t),warn:(e,t)=>Yt("warn",e,t),error:(e,t)=>Yt("error",e,t)};function lf(e){return{type:"heartbeat-gap",gapMs:e}}function uf(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 pf={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},df=16,gf=8,mf=6e4,ff=5e3,yf=250,hf=1e3,bf=3e4,xf=5,_f=3e3,Pf=3e4,kf=2e4,wf=2e3,Sf=8;function vf(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function hd(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 Zt=new WeakMap;function Af(e,t,n){let r=t.timers??pf,s=t.connectTimeoutMs??kf,o=t.heartbeatTimeoutMs??mf,u=t.maxConsecutiveHardFailures??Sf,p=new AbortController;function d(M,...$){for(let l of n){let y=M(l);if(y)try{y(...$)}catch(a){console.warn("[opencode-events] subscriber handler threw, skipping",a)}}}let f=r.now(),m=[],h,P=0,x=new Map,_=()=>{if(h&&r.clearTimeout(h),h=void 0,m.length===0)return;let M=m;m=[],x.clear(),P=r.now(),f=r.now();for(let $ of M)$&&d(l=>l.onEvent,$.event)},v=()=>{if(h)return;let M=r.now()-P;h=r.setTimeout(_,Math.max(0,df-M))};return(async()=>{let M=0,$=0;for(;!p.signal.aborted;){let l=!1,y=!1,a,A,I=null,R=r.now(),k=new AbortController,F=hd(p.signal);F.promise.then(()=>k.abort());try{let q=await new Promise((Z,ee)=>{let G=!1;A=r.setTimeout(()=>{G||(G=!0,me.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:s}),k.abort(),ee(new Error(`SSE connect timed out after ${s}ms`)))},s),e.global.event({signal:k.signal,sseDefaultRetryDelay:_f,sseMaxRetryDelay:Pf,sseMaxRetryAttempts:1}).then(J=>{G||(G=!0,r.clearTimeout(A),Z(J))},J=>{G||(G=!0,r.clearTimeout(A),ee(J))})}),{stream:N}=q;f=r.now();let B=()=>{r.clearTimeout(a),a=r.setTimeout(()=>{me.warn("SSE heartbeat timeout, forcing reconnect"),k.abort()},o)};B();let Q=r.now(),W=N[Symbol.asyncIterator]();for(;!k.signal.aborted;){let Z=W.next().then(oe=>({kind:"next",result:oe}),oe=>({kind:"error",error:oe})),ee=hd(k.signal),G=await Promise.race([Z,ee.promise.then(()=>({kind:"aborted"}))]);if(ee.cleanup(),G.kind==="aborted")break;if(G.kind==="error")throw G.error;if(G.result.done)break;l=!0,B();let J=G.result.value,he=J&&typeof J=="object"&&"payload"in J?J.payload:J;if(!he?.type)continue;let Ge=vf(he);if(Ge){let oe=x.get(Ge);oe!==void 0&&(m[oe]=void 0),x.set(Ge,m.length)}m.push({type:he.type,event:he}),v(),!(r.now()-Q<gf)&&(Q=r.now(),await new Promise(oe=>r.setTimeout(oe,0)))}y=l}catch(q){if(p.signal.aborted)break;I=q;let N=String(q),B=N.includes("401")||N.includes("403")||N.includes("Unauthorized")||N.includes("Token refresh failed");if(me.error("SSE event stream error",{error:N,retryCount:M,isAuthError:B}),B)try{_t(),await Ur(),me.info("SSE: refreshed auth token after auth error")}catch(Q){me.error("SSE: failed to refresh auth token",{error:String(Q)})}}finally{r.clearTimeout(a),r.clearTimeout(A),k.abort(),F.cleanup(),_()}if(p.signal.aborted)break;let j=r.now()-R,K=I?.cause?.status;if($=!l&&(typeof K=="number"&&K>=400||j<wf)?$+1:0,$>=u){me.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:$,lastError:String(I)}),d(q=>q.onParked,{consecutiveFailures:$,lastError:I});break}let b=r.now()-f;b>ff&&d(q=>q.onGapRehydrate,b),y?M=0:(M++,M>1&&me.warn("SSE event stream reconnecting",{retryCount:M}));let T=y?yf:Math.min(hf*2**Math.min(M-1,xf),bf);await new Promise(q=>{let N=r.setTimeout(q,T),B=()=>{r.clearTimeout(N),q()};p.signal.addEventListener("abort",B,{once:!0})})}})(),{subscribers:n,teardown:()=>{p.abort(),h&&r.clearTimeout(h)}}}function Gs(e){let{client:t,onEvent:n,onGapRehydrate:r,onParked:s,signal:o}=e,u={onEvent:n,onGapRehydrate:r,onParked:s},p=Zt.get(t);p?p.subscribers.add(u):(p=Af(t,e,new Set([u])),Zt.set(t,p));let d=p,f=!1,m=()=>{f||(f=!0,o&&o.removeEventListener("abort",h),d.subscribers.delete(u),d.subscribers.size===0&&(d.teardown(),Zt.get(t)===d&&Zt.delete(t)))},h=()=>m();return o&&(o.aborted?m():o.addEventListener("abort",h,{once:!0})),{close:m}}function Cf(){return Pe()}var en=new Map,tn=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function Rf(e,t){yn(e,t);function n(l){try{return new URL(l)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(l,window.location.origin)}catch{return null}throw new S(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(l)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}function r(l){let y=O().backendUrl??e.backendUrl,a=80,A=n(y);return A&&(a=A.port?Number(A.port):A.protocol==="https:"?443:80),$i({sandboxId:l,apiBaseUrl:y,backendPort:a})}let s={signUp:Rs,signInWithPassword:Ts,sendMagicLink:Is,verifyOtp:Es,signInWithProvider:js,exchangeCode:$s,refresh:ct,resetPassword:Ms,updatePassword:Ds,updateUserMetadata:qs,signInWithSso:Us,mfa:Fs,user:Os,signOut:Ls,session:Bs},o={list:io,get:ao,create:oo,secretResources:{list:Ra,create:Ta,rotate:Ia,remove:Ea,grant:ja,revoke:$a},updateName:co,branding:{get:lo,update:uo,uploadAsset:po,removeAsset:go,reset:mo},leave:vo,members:fo,invite:yo,removeMember:wo,updateMemberRole:So,invites:ho,cancelInvite:bo,resendInvite:xo,tokens:{list:_p,create:Pp,revoke:kp},audit:{log:Ap,export:Rp,webhooks:{list:Tp,create:Ip,update:Ep,remove:jp}}},u={assignments:{list:op,create:ap,revoke:cp},permissions:{list:lp,forRole:Hu},roles:{list:Nu,create:zu,update:Vu,setPermissions:Xu,remove:Ju,usage:Wu},groups:{list:Du,get:Ou,create:qu,update:Uu,remove:Fu,members:{list:Lu,add:Bu,remove:Gu}},agentIdentities:Ku,oauthClients:{list:Zu,get:ep,create:tp,update:np,rotateSecret:rp,remove:sp},can:Qu,canBatch:Yu},p={accountState:ql,accountStateMinimal:Ul,transactions:Fl,transactionsSummary:Ll,creditBreakdown:Bl,usageHistory:Gl,usageRollup:tu,sessionCosts:{list:ru,get:Ps},tierConfigurations:Nl,checkout:{createSession:l=>Kl(l),confirmSession:(l,y)=>Hl(l,y)},subscription:{createPortalSession:(l,y)=>Wl(l,y),cancel:(l,y)=>zl(l,y),reactivate:l=>Vl(l),scheduleDowngrade:(l,y,a)=>Xl(l,y,a),cancelScheduledChange:l=>Jl(l),prorationPreview:(l,y)=>Ql(l,y)},credits:{purchase:l=>Yl(l),autoTopupSettings:l=>Zl(l),configureAutoTopup:l=>eu(l)}},d={describe:_o,accept:Po,decline:ko},f={list:qe,listForAccount:Ro,get:ns,detail:rs,create:jo,createRepo:$o,provision:Mo,update:os,archive:as,llmCatalog:ss,modelPicker:is,modelAccess:As,setModelAccess:Cs,sandboxHealth:gs,sandboxTemplates:bc,sessions:it,createSession:ot},m={linkRepository:Fo,getInstallation:Lo,listInstallations:Bo,listLinkableInstallations:Go,listRepositories:No,listRepositoryBranches:Ko,linkInstallation:Wo,saveInstallation:Ho,deleteInstallation:zo},h={get:Vo,repositories:Xo},P={list:fp,create:yp,revoke:hp},x=gc,_={items:l=>Dp(l),item:l=>Up(l),itemFile:(l,y)=>Fp(l,y),marketplaces:()=>Op(),featured:()=>qp(),sources:{list:()=>Lp(),add:l=>Bp(l),remove:l=>Gp(l)}};function v(l){return{catalog:()=>us(l),tools:()=>Kt(l),search:(...y)=>qa(l,...y),describe:(...y)=>Ua(l,...y),call:(...y)=>Fa(l,...y),uploadAttachment:(...y)=>La(l,...y)}}function M(l){let y={list:()=>Ba(l),listAll:()=>Ga(l),reconcile:(...a)=>Na(l,...a),reconcileMember:(...a)=>Ka(l,...a),updateCredential:(...a)=>Ha(l,...a),revoke:(...a)=>Wa(l,...a),activate:(...a)=>za(l,...a),setDefault:(...a)=>Va(l,...a),pipedreamConnect:(...a)=>Xa(l,...a),pipedreamFinalize:(...a)=>Ja(l,...a)};return{attachments:{upload:(...a)=>Gt(l,...a),delete:(...a)=>Oe(l,...a),createController:a=>so(l,a)},get:a=>ns(l,a),detail:()=>rs(l),audit:a=>Cp(l,a),update:a=>os(l,a),archive:()=>as(l),llmCatalog:()=>ss(l),modelPicker:()=>is(l),modelAccess:()=>As(l),setModelAccess:a=>Cs(l,a),sandboxHealth:()=>gs(l),onboardingComplete:(...a)=>Uo(l,...a),apps:{list:()=>Np(l),create:a=>Kp(l,a),get:a=>Hp(l,a),update:(...a)=>Wp(l,...a),access:{get:(...a)=>Vp(l,...a),update:(...a)=>Xp(l,...a),session:(...a)=>Jp(l,...a)},remove:a=>zp(l,a),artifacts:{register:a=>Ss(l,a),uploadArchive:(...a)=>Qp(l,...a),finalize:(...a)=>vs(l,...a)},deployments:{create:(...a)=>Yp(l,...a),list:a=>Zp(l,a),get:(...a)=>ed(l,...a),logs:(...a)=>td(l,...a)},start:a=>nd(l,a),stop:a=>rd(l,a),rollback:(...a)=>sd(l,...a)},tokens:{list:()=>wp(l),create:a=>Sp(l,a),revoke:a=>vp(l,a)},setupLinks:{requestSecret:a=>$p(l,a),requestConnector:a=>Mp(l,a)},validateManifest:a=>Io(l,a),gitToken:()=>Eo(l),secrets:{list:()=>ya(l),upsert:a=>ha(l,a),setStrategy:(...a)=>ba(l,...a),broker:(...a)=>xa(l,...a),remove:a=>Sa(l,a),setPersonal:(...a)=>va(l,...a),removePersonal:a=>Aa(l,a),setGitCredential:a=>wa(l,a),startProviderOAuth:(...a)=>_a(l,...a),pollProviderOAuth:(...a)=>Pa(l,...a),removeProviderOAuth:a=>ka(l,a)},access:{list:()=>Zo(l),invite:(...a)=>na(l,...a),update:(...a)=>ea(l,...a),revoke:a=>ta(l,a),pendingInvites:()=>ra(l),resendInvite:(...a)=>ia(l,...a),revokeInvite:(...a)=>sa(l,...a),requests:()=>Jo(l),approveRequest:(...a)=>Qo(l,...a),rejectRequest:(...a)=>Yo(l,...a),groupGrants:()=>oa(l),attachGroupGrant:(...a)=>aa(l,...a),updateGroupGrant:(...a)=>ca(l,...a),detachGroupGrant:a=>la(l,a),resourceGrants:{list:()=>ua(l),create:a=>pa(l,a),remove:a=>da(l,a)}},connectors:{...v(l),list:()=>Qa(l),config:(...a)=>sc(l,...a),create:(...a)=>ac(l,...a),remove:(...a)=>lc(l,...a),sync:()=>Ya(l),auth:{discover:(...a)=>cc(l,...a)},setName:(...a)=>ic(l,...a),setCredentialMode:(...a)=>Za(l,...a),setAuthorizationStrategy:(...a)=>ec(l,...a),setCredential:(...a)=>mc(l,...a),setSensitive:(...a)=>tc(l,...a),connections:y,policies:{get:(...a)=>nc(l,...a),set:(...a)=>rc(l,...a)},pipedream:{listApps:(...a)=>uc(l,...a),listSections:(...a)=>pc(l,...a),connect:(...a)=>oc(l,...a),finalize:(...a)=>fc(l,...a)},discover:{list:(...a)=>ps(l,...a),sections:(...a)=>dc(l,...a),detail:(...a)=>ds(l,...a)}},policies:{list:()=>yc(l),set:(...a)=>hc(l,...a)},triggers:{list:()=>_l(l),create:(...a)=>Pl(l,...a),update:(...a)=>kl(l,...a),remove:(...a)=>wl(l,...a),fire:(...a)=>vl(l,...a),setActivation:(...a)=>Sl(l,...a)},files:{list:a=>Cc(l,a),read:(a,A)=>Tc(l,a,A),search:(...a)=>Rc(l,...a),archive:(...a)=>Ic(l,...a),history:(...a)=>Dc(l,...a)},git:{commits:()=>jc(l),commit:a=>$c(l,a),commitDiff:a=>Mc(l,a),branches:()=>Ec(l),versionDiff:(...a)=>Oc(l,...a),inviteCollaborator:(...a)=>To(l,...a)},changeRequests:{list:()=>qc(l),get:a=>Uc(l,a),diff:a=>Fc(l,a),mergePreview:a=>Lc(l,a),open:(...a)=>Bc(l,...a),merge:(...a)=>Gc(l,...a),close:(...a)=>Nc(l,...a),reopen:(...a)=>Kc(l,...a),requestChanges:(...a)=>Hc(l,...a)},sessions:{list:a=>it(l,a),listPage:a=>Xc(l,a),create:a=>ot(l,a),ensureWarm:()=>tl(l),claimWarm:a=>nl(l,a)},review:{list:a=>up(l,a),get:a=>pp(l,a),submit:a=>dp(l,a),act:(...a)=>gp(l,...a),bulkAct:a=>mp(l,a)},approvals:{list:a=>ga(l,a),resolve:(...a)=>fa(l,...a),sessionsNeedingInput:a=>ma(l,a)},gateway:{logs:a=>Pu(l,a),log:a=>ku(l,a),overview:a=>wu(l,a),series:a=>Su(l,a),breakdown:a=>vu(l,a),sessions:a=>Au(l,a),errors:a=>Cu(l,a),budgets:()=>Ru(l),setBudget:a=>Tu(l,a),deleteBudget:a=>Iu(l,a),keys:()=>Eu(l),createKey:a=>ju(l,a),revokeKey:a=>$u(l,a),routing:{get:()=>hu(l),set:a=>bu(l,a),reset:()=>xu(l),preview:a=>_u(l,a)},playground:(a,A,I)=>Mu(l,a,A,I)},channels:{slack:{installation:()=>iu(l),connect:a=>ou(l,a),mode:()=>au(l),manifest:()=>cu(l),disconnect:()=>lu(l),getFile:a=>uu(l,a),uploadFile:a=>pu(l,a)},email:{installation:a=>du(l,a),mode:()=>gu(l),connect:a=>mu(l,a),disconnect:a=>fu(l,a),updatePolicy:(...a)=>yu(l,...a)}},updateFeatureFlag:(...a)=>Do(l,...a),updateExperimentalFeature:(...a)=>Oo(l,...a),modelDefaults:{get:()=>Il(l),set:a=>El(l,a),clear:a=>jl(l,a)},setDefaultAgent:a=>Ol(l,a),sandbox:{list:()=>Ac(l),snapshots:()=>xc(l),rebuildSnapshot:a=>_c(l,a),fixWithAgent:()=>Pc(l),createTemplate:a=>kc(l,a),updateTemplate:(...a)=>wc(l,...a),removeTemplate:a=>Sc(l,a),buildTemplate:a=>vc(l,a),setProvider:a=>qo(l,a)},setAgentScope:(...a)=>Ml(l,...a),session:a=>$(l,a)}}function $(l,y){let a=null,A,I,R=null;async function k(){R||(R=fs(l,y,{showErrors:!1}).then(b=>{let T=typeof b.metadata?.opencode_model=="string"?b.metadata.opencode_model.trim():"",q=T.indexOf("/"),N=q>0&&q<T.length-1?{providerID:T.slice(0,q),modelID:T.slice(q+1)}:void 0,B=b.agent_name?.trim()||void 0;return{model:N,agent:B}}));try{return await R}catch(b){throw R=null,b}}function F(){if(a)return a;let b=Cl(l,y);return b&&(a=b),a}async function j(b){let T=F();if(T)return T;let q=b?.readyTimeoutMs??18e4,N=At(O().backendUrl??e.backendUrl).catch(()=>null),B=`${l}
20
- ${y}`,Q=en.get(B);if(Q)return a=await Q,await N,a;let W=(async()=>{let Z=Date.now()+q,ee=()=>Math.max(0,Z-Date.now()),G=await Ue(l,y,Math.min(3e4,ee()));for(;Date.now()<Z&&(G==null||(G.stage==="provisioning"||G.stage==="starting")&&G.retriable);)await new Promise(Ge=>setTimeout(Ge,Math.min(1e3,ee()))),G=await Ue(l,y,Math.min(3e4,ee()));if(!G||G.stage!=="ready"||!G.sandbox||!G.opencode_session_id)throw new S(`Session runtime not ready (stage: ${G?.stage??"unknown"})`,{code:"RUNTIME_UNAVAILABLE"});let J=G.sandbox.external_id;if(!J)throw new S("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let he=Pt(J);return _i(he,J),{opencodeSessionId:G.opencode_session_id,runtimeUrl:he,sandboxId:J}})();en.set(B,W);try{return a=await W,await N,a}finally{en.get(B)===W&&en.delete(B)}}function K(b){let T=F();if(!T)throw new tn(b);return T}function D(){a=null,Tl(l,y)}return{get:b=>fs(l,y,b),cost:()=>Ps(y,{projectId:l}),update:b=>dl(l,y,b),delete:()=>(D(),gl(l,y)),start:(...b)=>Ue(l,y,...b),restart:()=>(D(),Wt(l,y)),stop:()=>(D(),zt(l,y)),configState:()=>ml(l,y),reloadConfig:b=>(D(),fl(l,y,b)),reloadConfigStream:(...b)=>(D(),yl(l,y,...b)),setSharing:b=>Jc(l,y,b),previews:()=>Qc(l,y),commit:b=>Wc(l,y,b),publicShares:{list:()=>Yc(l,y),create:(...b)=>Zc(l,y,...b),revoke:(...b)=>el(l,y,...b)},audit:(b,T)=>rl(l,y,b,T),transcript:b=>sl(l,y,b),transcriptSync:b=>il(l,y,b),turn:()=>ol(l,y),prompts:{create:b=>al(l,y,b),list:()=>cl(l,y),remove:b=>ll(l,y,b),retry:b=>ul(l,y,b),hold:b=>pl(l,y,b)},ensureReady:j,health:b=>od(F()?.runtimeUrl??null,b),previewUrl:(b,T="/")=>Se(b,T,r(K("previewUrl").sandboxId)),proxyUrl:b=>gd(b,r(K("proxyUrl").sandboxId)),setModel:b=>{A=b},changeModel:async b=>{let T=await xl(l,y,b);return R=null,T},scope:()=>hl(l,y),providerSecretPool:{list:()=>Da(l,y),get:b=>Ma(l,y,b),set:(b,T)=>Oa(l,y,b,T)},rescope:b=>bl(l,y,b),setAgent:b=>{I=b},send:async(b,T)=>{let{opencodeSessionId:q,runtimeUrl:N}=await j(),B=T?.model??A,Q=T?.agent??I,W=B&&Q?{}:await k(),Z=B??W.model,ee=Q??W.agent;return pe(N).session.prompt({sessionID:q,parts:[{type:"text",text:b}],...Z?{model:Z}:{},...ee?{agent:ee}:{}})},abort:async()=>{let{opencodeSessionId:b,runtimeUrl:T}=await j();return pe(T).session.abort({sessionID:b})},rewind:async b=>{let{opencodeSessionId:T,runtimeUrl:q}=await j();return pe(q).session.revert({sessionID:T,messageID:b})},restoreRewind:async()=>{let{opencodeSessionId:b,runtimeUrl:T}=await j();return pe(T).session.unrevert({sessionID:b})},stream:async b=>{let{runtimeUrl:T}=await j();return Gs({client:pe(T),onEvent:b.onEvent,onGapRehydrate:b.onGapRehydrate,signal:b.signal})},get runtime(){return pe(K("runtime").runtimeUrl)},files:{list:async b=>$t(b,(await j()).runtimeUrl),read:async b=>Ye(b,(await j()).runtimeUrl),readBlob:async b=>Ze(b,(await j()).runtimeUrl),status:async()=>Mt((await j()).runtimeUrl),findFiles:async(b,T)=>Dt(b,T,(await j()).runtimeUrl),findText:async b=>Ot(b,(await j()).runtimeUrl),upload:async(b,T,q,N)=>et(b,T,q,(await j()).runtimeUrl,N),write:async(b,T)=>tt(b,T,(await j()).runtimeUrl),create:async b=>qt(b,(await j()).runtimeUrl),copy:async(b,T)=>Ut(b,T,(await j()).runtimeUrl),remove:async b=>we(b,(await j()).runtimeUrl),mkdir:async b=>nt(b,(await j()).runtimeUrl),rename:async(b,T)=>ke(b,T,(await j()).runtimeUrl)}}}return{config:e,auth:s,accounts:o,iam:u,accountInvites:d,projects:f,connectors:v(),project:M,session:$,github:m,gitBackend:h,billing:p,sandboxShares:P,connectStatus:x,marketplace:_,validateToken:Ao,runtime:Cf}}function Tf(){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 If(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Fe(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function Ef(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function jf(e){if(Fe(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 $f(e){let t=Fe(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function Mf(e,t){let n=Fe(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function Df(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function Of(e,t){return Fe(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 qf(e,t,n){return Fe(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 Uf(e,t,n){let r=Fe(e);if(r.includes(t))return e;let s=e.pending.findIndex(f=>f.id===t);if(s===-1)return e;let o=r.length,u=Math.min(Math.max(n,o),e.pending.length-1);if(u===s)return e;let p=[...e.pending],[d]=p.splice(s,1);return p.splice(u,0,d),{...e,pending:p}}var bd={thinking:!1,toolDetails:!0,assistantMetadata:!0};function Ff(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function Lf(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 Bf(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
19
+ `);let _=Im(x);if(_){if(r(_),_.type==="error")throw new S(_.error,{status:_.status,code:_.code,data:{reason:_.reason}});_.type==="done"&&(f=_.result)}}}}finally{u.cancel().catch(()=>{})}if(!f)throw new Error("Reload stream ended without a result");return f}async function xl(e,t){return c(await i.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function _l(e,t,n){return c(await i.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function Pl(e,t,n){return c(await i.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{opencode_model:n}))}async function wl(e){return c(await i.get(`/projects/${e}/triggers`))}async function kl(e,t){return c(await i.post(`/projects/${e}/triggers`,t))}async function Sl(e,t,n){return c(await i.patch(`/projects/${e}/triggers/${t}`,n))}async function vl(e,t){return c(await i.delete(`/projects/${e}/triggers/${t}`))}async function Al(e,t){return c(await i.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function Cl(e,t){return c(await i.post(`/projects/${e}/triggers/${t}/fire`,{}))}var de=new Map;function ys(e,t){return`${e}::${t}`}function Rl(e,t){de.delete(e),de.set(e,t)}function Tl(e,t){let n=ys(e,t),r=de.get(n);return r&&Rl(n,r),r}function Il(e,t,n){let r=ys(e,t);if(!de.has(r)&&de.size>=512){let s=de.keys().next().value;s!==void 0&&de.delete(s)}Rl(r,n)}function El(e,t){de.delete(ys(e,t))}function Ww(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!e.opencode_session_id)return null;let t=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return t?{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:t,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},opencode_session_id:e.opencode_session_id,runtime_url:e.sandbox_url}:null}var hs=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 zw(e){return e instanceof Error&&e.name==="SessionStartError"}function Em(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,s=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new hs(s,{status:n,code:r,terminal:!0}):null}async function Ue(e,t,n){let r=n&&n>0?`?wait_ms=${Math.floor(n)}`:"",s=await i.post(`/projects/${e}/sessions/${t}/start${r}`,{},{showErrors:!1});if(!s.success||!s.data){let p=Em(s.error);if(p&&!(p.status===404&&Xc(t)))throw p;return null}let o=s.data,u=o.sandbox?.external_id;return o.stage==="ready"&&u&&o.opencode_session_id&&Il(e,t,{opencodeSessionId:o.opencode_session_id,runtimeUrl:wt(u),sandboxId:u}),o}function Vw(e,t){return["session-start",e,t]}async function jl(e){return c(await i.get(`/projects/${e}/model-defaults`))}async function $l(e,t){return c(await i.put(`/projects/${e}/model-defaults`,t))}async function Ml(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return c(await i.delete(`/projects/${e}/model-defaults?${n}`))}async function tk(e,t){return c(await i.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}async function Ol(e,t,n){let r=$m(n);return c(await i.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}function Dl(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function jm(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function $m(e){let t=e.connectors_required?Dl(e.connectors_required):void 0,n=e.connectors_personal?Dl(e.connectors_personal):void 0;if(t&&n&&!jm(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 ck(e,t){let n=c(await i.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?bs(n.block):null}}async function lk(e,t,n){let r=bs(n,!0),s=c(await i.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?bs(s.block):null}}function bs(e,t=!1){let n=Dm(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}function ql(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Mm(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Dm(e){let t=e.connectors_required?ql(e.connectors_required):void 0,n=e.connectors_personal?ql(e.connectors_personal):void 0;if(t&&n&&!Mm(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 uk(e,t,n){return c(await i.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Ul(e,t){return c(await i.put(`/projects/${e}/default-agent`,{agent:t}))}function xs(){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 Om(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function mk(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??xs(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:Om(r),label:s,sublabel:null,isGrandfathered:!1}}async function Fl(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString(),r=n?`?${n}`:"",s=await i.get(`/billing/account-state${r}`,{showErrors:!1}),o=s.error?.status===404&&/billing is not enabled/i.test(s.error.message||"");if(s.error&&s.error.status!==401&&!o)throw s.error;return s.error?xs():s.data}async function Ll(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString(),r=n?`?${n}`:"",s=await i.get(`/billing/account-state/minimal${r}`,{showErrors:!1}),o=s.error?.status===404&&/billing is not enabled/i.test(s.error.message||"");if(s.error&&s.error.status!==401&&!o)throw s.error;return s.error?xs():s.data}async function Bl(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 c(await i.get(`/billing/transactions${n?`?${n}`:""}`))}async function Gl(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 c(await i.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function Nl(){return c(await i.get("/billing/credit-breakdown"))}async function Kl(e){let t=e!=null?`?days=${e}`:"";return c(await i.get(`/billing/usage-history${t}`))}async function Hl(){return c(await i.get("/billing/tier-configurations"))}async function fk(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return De(e,`/v1/billing/account-state${t}`)}async function Wl(e){return c(await i.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 zl(e,t){return c(await i.post("/billing/confirm-checkout-session",{account_id:t,session_id:e}),"Failed to confirm checkout session")}async function Vl(e,t){return c(await i.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Xl(e,t){return c(await i.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Jl(e){return c(await i.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Ql(e,t,n){return c(await i.post("/billing/schedule-downgrade",{account_id:n,target_tier_key:e,commitment_type:t}),"Failed to schedule downgrade")}async function Yl(e){return c(await i.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function Zl(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),c(await i.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function eu(e){return c(await i.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 tu(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return c(await i.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function nu(e){return c(await i.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 yk(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return c(await i.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function hk(e){return c(await i.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 bk(e){return c(await i.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function xk(e){return c(await i.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function ru(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 c(await i.get(`/usage${n?`?${n}`:""}`))}function _s(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Xt(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Jt(e){return e.size>0?`?${e}`:""}async function iu(e={}){let t=new URLSearchParams;return _s(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Xt(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)),c(await i.get(`/usage/session-costs${Jt(t)}`))}async function Ps(e,t={}){let n=new URLSearchParams;return _s(n,t),c(await i.get(`/usage/session-costs/${encodeURIComponent(e)}${Jt(n)}`))}async function vk(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Xt(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)),c(await i.get(`/usage/cost-by-project${Jt(t)}`))}async function Ak(e={}){let t=new URLSearchParams;return _s(t,e),e.sessionId&&t.set("session_id",e.sessionId),Xt(t,e),c(await i.get(`/usage/cost-summary${Jt(t)}`))}function su(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),e==="sessions"){let s=t;s.projectId&&n.set("project_id",s.projectId),s.ownerId&&n.set("owner_id",s.ownerId)}Xt(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`${O().backendUrl||""}${r}?${n}`}async function Ck(e,t={}){let n=su(e==="projects"?"projects":"sessions",t),r=await ae(),s=await fetch(n,{method:"GET",headers:r?{Authorization:`Bearer ${r}`}:{}});if(!s.ok){let d=await s.text().catch(()=>"");throw new Error(d||`Failed to export CSV (HTTP ${s.status})`)}let o=s.headers.get("x-kortix-row-cap"),u=o!=null?Number(o):NaN;return{blob:await s.blob(),rowCap:Number.isFinite(u)?u:null}}async function ou(e,t){return c(await i.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function Ek(e){return ou("slack",e)}function jk(e){return ou("teams",e)}async function au(e){let t=await i.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function cu(e,t){return c(await i.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var qm={oauth_available:!1,install_url:null};async function lu(e){let t=await i.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?qm:t.data}async function uu(e){return c(await i.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function pu(e){let t=await i.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 c(await i.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function gu(e,t){return c(await i.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 ws(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 Um={provider:"agentmail",managed_available:!1};async function mu(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await i.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?ws(r.data):null}async function fu(e){let t=await i.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Um:t.data}async function yu(e,t){let n=c(await i.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return ws(n)}async function hu(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await i.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 bu(e,t,n){let r=c(await i.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return ws(r)}async function $k(e){return c(await i.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function Mk(e,t,n){return c(await i.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function xu(e){return c(await i.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function _u(e,t){return c(await i.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Pu(e){return c(await i.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function wu(e,t){return c(await i.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function ku(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 c(await i.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function Su(e,t){return c(await i.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function vu(e,t){return c(await i.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Au(e,t){return c(await i.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Cu(e,t){return c(await i.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ru(e,t){return c(await i.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Tu(e,t){return c(await i.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Iu(e){return c(await i.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Eu(e,t){return c(await i.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function ju(e,t){return c(await i.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function $u(e){return c(await i.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Mu(e,t){return c(await i.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Du(e,t){return c(await i.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Ou(e,t,n,r,s){return c(await i.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function Uk(e,t){return c(await i.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function Gk(){return c(await i.get("/referrals/code"),"GET_CODE_FAILED")}async function Nk(){return c(await i.post("/referrals/code/refresh",{}),"REFRESH_CODE_FAILED")}async function Kk(e){return c(await i.post("/referrals/validate",{referral_code:e}),"VALIDATE_CODE_FAILED")}async function Hk(){return c(await i.get("/referrals/stats"),"GET_STATS_FAILED")}async function Wk(e={}){let t=new URLSearchParams({limit:String(e.limit??50),offset:String(e.offset??0)});return c(await i.get(`/referrals/list?${t}`),"GET_REFERRALS_FAILED")}async function zk(e){return c(await i.post("/referrals/email",{emails:e}),"SEND_EMAILS_FAILED")}function C(e){if(!e.success||e.data===void 0)throw e.error||new Error("Unexpected empty response");return e.data}function L(e){return i.get(e,{showErrors:!1})}async function qu(e){return C(await L(`/accounts/${e}/iam/groups`)).groups}async function Uu(e,t){return C(await L(`/accounts/${e}/iam/groups/${t}`))}async function Fu(e,t){return C(await i.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Lu(e,t,n){return C(await i.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function Bu(e,t){return C(await i.delete(`/accounts/${e}/iam/groups/${t}`))}async function Gu(e,t){return C(await L(`/accounts/${e}/iam/groups/${t}/members`)).members}async function Nu(e,t,n){return C(await i.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function Jk(e,t){return C(await L(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function Ku(e,t,n){return C(await i.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function Qk(e,t){return C(await L(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function Yk(e,t){let n=C(await L(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}async function Zk(e,t={}){let n=new URLSearchParams;t.resourceType&&n.set("resourceType",t.resourceType),t.principalType&&n.set("principalType",t.principalType),t.principalId&&n.set("principalId",t.principalId),t.projectId&&n.set("projectId",t.projectId);let r=n.toString();return C(await L(`/accounts/${e}/iam/resource-grants${r?`?${r}`:""}`)).grants}async function eS(e,t={}){let n=new URLSearchParams;t.principalType&&n.set("principalType",t.principalType),t.principalId&&n.set("principalId",t.principalId),t.scopeType&&n.set("scopeType",t.scopeType),t.scopeId!==void 0&&n.set("scopeId",t.scopeId===null?"null":t.scopeId);let r=n.toString();return C(await L(`/accounts/${e}/iam/policies${r?`?${r}`:""}`)).policies}async function tS(e,t){return C(await i.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function nS(e,t,n){return C(await i.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function rS(e,t){return C(await i.delete(`/accounts/${e}/iam/policies/${t}`))}async function sS(e,t){return C(await i.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function iS(e,t){return C(await i.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function Hu(e){return C(await L(`/accounts/${e}/iam/roles`)).roles}async function Wu(e){return C(await L(`/accounts/${e}/iam/agent-identities`)).agents}async function zu(e,t){return C(await L(`/accounts/${e}/iam/roles/${t}/permissions`))}async function oS(e){return C(await L(`/accounts/${e}/iam/actions`)).actions}async function Vu(e,t){return C(await L(`/accounts/${e}/iam/roles/${t}/usage`))}async function Xu(e,t){return C(await i.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Ju(e,t,n){return C(await i.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Qu(e,t,n){return C(await i.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Yu(e,t){return C(await i.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function aS(e,t,n){return C(await i.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function cS(e){return C(await L(`/accounts/${e}/iam/scim/tokens`)).tokens}async function lS(e,t){return C(await i.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function uS(e,t){return C(await i.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function pS(e){return C(await L(`/accounts/${e}/iam/mfa-required`))}async function dS(e){return C(await L(`/accounts/${e}/iam/mfa-required/preview`))}async function gS(e,t){return C(await i.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function mS(e){return C(await L(`/accounts/${e}/iam/sso/provider`)).provider}async function fS(e,t){return C(await i.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function yS(e,t){return C(await i.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function hS(e){return C(await i.delete(`/accounts/${e}/iam/sso/provider`))}async function bS(e){return C(await L(`/accounts/${e}/iam/sso/mappings`)).mappings}async function xS(e,t){return C(await i.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function _S(e,t){return C(await i.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function PS(e){return C(await L(`/accounts/${e}/iam/session-policy`))}async function wS(e,t){return C(await i.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function kS(e){return C(await L(`/accounts/${e}/iam/sessions`)).sessions}async function SS(e,t){return C(await i.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function vS(e){return C(await L(`/accounts/${e}/iam/pat-policy`))}async function AS(e,t){return C(await i.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function CS(e){return C(await L(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function RS(e,t){return C(await i.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function TS(e,t){return C(await i.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function IS(e,t){return C(await i.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function ES(e){return C(await L(`/accounts/${e}/audit/webhooks`)).webhooks}async function jS(e,t){return C(await i.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function $S(e,t,n){return C(await i.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function MS(e,t){return C(await i.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function DS(e,t={}){let n=new URLSearchParams;t.action&&n.set("action",t.action),t.actor&&n.set("actor",t.actor),t.project_id&&n.set("project_id",t.project_id),t.session_id&&n.set("session_id",t.session_id),t.actor_type&&n.set("actor_type",t.actor_type),t.source&&n.set("source",t.source),t.phase&&n.set("phase",t.phase),t.outcome&&n.set("outcome",t.outcome),t.request_id&&n.set("request_id",t.request_id),t.correlation_id&&n.set("correlation_id",t.correlation_id),t.resource_type&&n.set("resource_type",t.resource_type),t.since&&n.set("since",t.since),t.until&&n.set("until",t.until),t.q&&n.set("q",t.q),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString();return C(await L(`/accounts/${e}/audit${r?`?${r}`:""}`))}async function Zu(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),C(await L(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function ep(e,t,n){return n.length===0?[]:C(await i.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function OS(e){return C(await L(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function qS(e,t){return C(await i.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function tp(e){return c(await i.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function np(e,t){return c(await i.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function rp(e,t){return c(await i.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function sp(e,t,n){return c(await i.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function ip(e,t){return c(await i.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function op(e,t){return c(await i.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function ap(e){return i.get(e,{showErrors:!1})}function Fm(e){let t=new URLSearchParams;e?.principalType&&t.set("principal_type",e.principalType),e?.principalId&&t.set("principal_id",e.principalId),e?.scopeType&&t.set("scope_type",e.scopeType),e?.scopeId&&t.set("scope_id",e.scopeId),e?.objectType&&t.set("object_type",e.objectType),e?.objectId&&t.set("object_id",e.objectId),e?.roleId&&t.set("role_id",e.roleId),e?.includeExpired&&t.set("include_expired","true");let n=t.toString();return n?`?${n}`:""}async function cp(e,t){return c(await ap(`/accounts/${e}/iam/assignments${Fm(t)}`)).assignments}async function lp(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),c(await i.post(`/accounts/${e}/iam/assignments`,n))}async function up(e,t){return c(await i.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function pp(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return c(await ap(`/accounts/${e}/iam/permissions${n}`)).permissions}async function zS(){let e=await i.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:c(e,"Failed to load account deletion status")}async function VS(e="User requested deletion"){return c(await i.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function XS(){return c(await i.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function JS(){return c(await i.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function QS(){return(await i.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function tv(){return i.get("/admin/api/provider-distribution").then(e=>c(e))}function nv(e=300){return i.get(`/admin/api/sandboxes?limit=${e}`).then(t=>c(t))}function rv(e){return i.put("/admin/api/provider-distribution",e).then(t=>c(t))}function sv(e){return i.get(`/admin/api/provider-analytics?days=${e}`).then(t=>c(t))}function iv(e,t){return i.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>c(n))}function ov(){return i.get("/admin/api/provider-fallback").then(e=>c(e))}function av(e){return i.put("/admin/api/provider-fallback",{enabled:e}).then(t=>c(t))}async function pv(e){return c(await i.get(`/google/auth-url?return_url=${encodeURIComponent(e)}`),"Failed to get Google auth URL")}async function dv(e,t){return c(await i.post("/presentation-tools/convert-and-upload-to-slides",{presentation_path:e,sandbox_url:t},{timeout:18e4}),"Failed to upload to Google Slides")}async function dp(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 c(await i.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function gp(e,t){return c(await i.get(`/projects/${e}/review/items/${t}`))}async function mp(e,t){return c(await i.post(`/projects/${e}/review/items`,t))}async function fp(e,t,n){return c(await i.post(`/projects/${e}/review/items/${t}/act`,n))}async function yp(e,t){return c(await i.post(`/projects/${e}/review/bulk`,t))}async function hp(e){return c(await i.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function bp(e){return c(await i.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function xp(e,t){let n=await i.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var ks=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function _p(e,t=""){return`${ze()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Pp(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let s=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new ks(s,t.status)}return r}async function Pv(e){return Pp(_p(e))}async function wv(e){return Pp(_p(e,"/messages"))}async function wp(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 c(await i.get(`/accounts/tokens${r}`))}async function kp(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return c(await i.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function Sp(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return c(await i.delete(`/accounts/tokens/${e}${n}`))}async function vp(e){return c(await i.get(`/projects/${e}/cli-token`))}async function Ap(e,t){return c(await i.post(`/projects/${e}/cli-token`,t??{}))}async function Cp(e,t){return c(await i.delete(`/projects/${e}/cli-token/${t}`))}async function Rp(e,t){let n=new URLSearchParams;t?.action&&n.set("action",t.action),t?.actor&&n.set("actor",t.actor),t?.actorType&&n.set("actor_type",t.actorType),t?.projectId&&n.set("project_id",t.projectId),t?.sessionId&&n.set("session_id",t.sessionId),t?.source&&n.set("source",t.source),t?.phase&&n.set("phase",t.phase),t?.outcome&&n.set("outcome",t.outcome),t?.resourceType&&n.set("resource_type",t.resourceType),t?.requestId&&n.set("request_id",t.requestId),t?.correlationId&&n.set("correlation_id",t.correlationId),t?.since&&n.set("since",t.since),t?.until&&n.set("until",t.until),t?.q&&n.set("q",t.q),t?.cursor&&n.set("cursor",t.cursor),t?.limit!=null&&n.set("limit",String(t.limit));let r=n.toString();return c(await i.get(`/accounts/${e}/audit${r?`?${r}`:""}`))}async function Tp(e,t){let n=new URLSearchParams;t?.action&&n.set("action",t.action),t?.actor&&n.set("actor",t.actor),t?.actorType&&n.set("actor_type",t.actorType),t?.sessionId&&n.set("session_id",t.sessionId),t?.source&&n.set("source",t.source),t?.phase&&n.set("phase",t.phase),t?.outcome&&n.set("outcome",t.outcome),t?.resourceType&&n.set("resource_type",t.resourceType),t?.requestId&&n.set("request_id",t.requestId),t?.correlationId&&n.set("correlation_id",t.correlationId),t?.since&&n.set("since",t.since),t?.until&&n.set("until",t.until),t?.q&&n.set("q",t.q),t?.cursor&&n.set("cursor",t.cursor),t?.limit!=null&&n.set("limit",String(t.limit));let r=n.toString();return c(await i.get(`/projects/${e}/audit${r?`?${r}`:""}`))}async function Ip(e,t){let n=new URLSearchParams;t?.format&&n.set("format",t.format),t?.action&&n.set("action",t.action),t?.actor&&n.set("actor",t.actor),t?.actorType&&n.set("actor_type",t.actorType),t?.projectId&&n.set("project_id",t.projectId),t?.sessionId&&n.set("session_id",t.sessionId),t?.source&&n.set("source",t.source),t?.phase&&n.set("phase",t.phase),t?.outcome&&n.set("outcome",t.outcome),t?.resourceType&&n.set("resource_type",t.resourceType),t?.requestId&&n.set("request_id",t.requestId),t?.correlationId&&n.set("correlation_id",t.correlationId),t?.since&&n.set("since",t.since),t?.until&&n.set("until",t.until),t?.q&&n.set("q",t.q),t?.cursor&&n.set("cursor",t.cursor),t?.limit!=null&&n.set("limit",String(t.limit));let r=n.toString();return c(await i.get(`/accounts/${e}/audit/export${r?`?${r}`:""}`))}async function Ep(e){return c(await i.get(`/accounts/${e}/audit/webhooks`))}async function jp(e,t){return c(await i.post(`/accounts/${e}/audit/webhooks`,t))}async function $p(e,t,n){return c(await i.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function Mp(e,t){return c(await i.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function Dp(e,t){return c(await i.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function Op(e,t){return c(await i.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function jv(e){return c(await i.get(`/approval-links/${e}`),"Failed to load approval")}async function qp(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 c(await i.get(`/marketplace/items${n}`))}async function Up(){return c(await i.get("/marketplace/marketplaces"))}async function Fp(){return c(await i.get("/marketplace/marketplaces/featured"))}async function Lp(e){return c(await i.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function Bp(e,t){return c(await i.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function Gp(){return c(await i.get("/marketplace/sources"))}async function Np(e){return c(await i.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Kp(e){return c(await i.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function Ov(e,t){return c(await i.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function Lv(e){return c(await i.get(`/templates/${encodeURIComponent(e)}`))}async function Bv(e,t){return c(await i.post(`/templates/${encodeURIComponent(e)}/install`,t))}async function Hp(e){return c(await i.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Wp(e,t){return c(await i.post(`/projects/${e}/apps`,t),"Failed to create App")}async function zp(e,t){return c(await i.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Vp(e,t,n){return c(await i.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Xp(e,t){return c(await i.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Jp(e,t){return c(await i.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Qp(e,t,n){return c(await i.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Yp(e,t){return c(await i.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Ss(e,t){return c(await i.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function vs(e,t,n){return c(await i.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function Lm(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function Bm(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 Zp(e,t,n={}){let r=await Lm(t),s=n.mediaType??"application/gzip",o=await Ss(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let u=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!u.ok){let p=await u.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${u.status}${p?`: ${p}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),vs(e,o.artifact.artifact_id,{sha256:await Bm(r),size_bytes:r.byteLength})}async function ed(e,t,n){return c(await i.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function td(e,t){return c(await i.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function nd(e,t,n){return c(await i.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function rd(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return c(await i.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function sd(e,t){return c(await i.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function id(e,t){return c(await i.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function od(e,t,n){return c(await i.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}async function As(e){return c(await i.get(`/projects/${e}/model-access`))}async function Cs(e,t){return c(await i.put(`/projects/${e}/model-access`,t))}var ct=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};function Gm(e){let t=ue(e?.backendUrl??O().backendUrl??"");if(!t)throw new ct("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);return t.endsWith("/v1")?t:`${t}/v1`}async function V(e,t,n){let r=n?.fetch??O().fetch??((d,f)=>fetch(d,f)),s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let o=await r(`${Gm(n)}${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}:{}}),u=await o.text().catch(()=>""),p=null;try{p=u?JSON.parse(u):null}catch{p=u}if(!o.ok){let d=p&&typeof p=="object"?p:{};throw new ct(typeof d.error=="string"?d.error:"auth_error",typeof d.error_description=="string"&&d.error_description?d.error_description:typeof d.error=="string"?d.error:o.statusText||`HTTP ${o.status}`,o.status)}return p}function Rs(e,t){return V("/auth/signup",{body:e},t)}function Ts(e,t){return V("/auth/sign-in/password",{body:e},t)}function Is(e,t){return V("/auth/sign-in/magic-link",{body:e},t)}function Es(e,t){return V("/auth/verify-otp",{body:e},t)}function js(e,t){return V("/auth/sign-in/oauth",{body:e},t)}function $s(e,t){return V("/auth/oauth/exchange",{body:e},t)}function lt(e,t){return V("/auth/refresh",{body:e},t)}function Ms(e,t){return V("/auth/password/reset",{body:e},t)}function Ds(e,t,n){return V("/auth/password/update",{body:e,bearer:t},n)}function Os(e,t){return V("/auth/user",{bearer:e},t)}function qs(e,t,n){return V("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function Us(e,t){return V("/auth/sign-in/sso",{body:e},t)}var Fs={enroll:(e,t,n)=>V("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>V(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>V(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>V(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function Ls(e,t={},n){return V("/auth/sign-out",{body:t,bearer:e},n)}function Bs(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,u=null,p=new Set,d=x=>(x.expires_at??0)*1e3,f=x=>d(x)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let x of[...p])try{x(r)}catch{}try{e.onChange?.(r)}catch{}}async function h(){if(o)return r;o=!0;let x=await e.storage.get();if(x)try{let _=JSON.parse(x);_.session?.access_token&&_.session?.refresh_token&&(r=_.session,s=_.user??null)}catch{r=null}return r}async function P(){if(await h(),!r)return null;if(!u){let x=r.refresh_token;u=lt({refresh_token:x},e.request).then(async _=>(r=_.session,_.user&&(s=_.user),await m(),r)).catch(async _=>{let v=_&&typeof _=="object"&&"status"in _?_.status:0;if(v>=400&&v<500)return r=null,s=null,await m(),null;throw _}).finally(()=>{u=null})}return u}return{subscribe(x){return p.add(x),()=>{p.delete(x)}},current:()=>r,user:()=>s,load:h,async set(x,_){await h(),r=x,_!==void 0&&(s=_),x||(s=null),await m()},async getToken(){return await h(),r?f(r)?(await P().catch(()=>r))?.access_token??null:r.access_token:null},refresh:P,async clear(){r=null,s=null,o=!0,await m()}}}var Km=["control_plane","provider_ingress","daemon","upstream_port"];function ad(e){return typeof e=="string"&&Km.includes(e)?e:null}function tA(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function cd(e,t){let n=(e===void 0?re():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await U(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let u=o,p=ad(r.headers.get("X-Kortix-Proxy-Hop"))??ad(o?.hop),d=Number(r.headers.get("X-Kortix-Upstream-Status")),f=o?.upstream_status,m=Number.isFinite(d)&&d>0?d:typeof f=="number"?f:null;return{status:r.status,ok:r.ok,health:u,body:s,hop:p,upstreamStatus:m}}var ge={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};var ld=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,ud=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,pd=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,dd=new Set([22,4096,parseInt(ge.KORTIX_MASTER,10)]);function Hm(e){return ud.test(e)}function Qt(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 Wm(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var zm=new Set(["'",'"',"`","<","(","["]),Vm=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function Xm(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&&zm.has(e[t]);)t++;for(;n>t&&Vm.has(e[n-1]);)n--;return e.slice(t,n)}function Jm(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var Qm=/^\/proxy\/(\d{1,5})(\/.*)?$/,Ym=/^\/(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 Zm(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:Ym.test(t.pathname)}catch{return!1}}function Yt(e){if(!e)return null;let t=Xm(Wm(e.trim())),n=hd(t);if(n){let r=Qt(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,u=parseInt(ge.KORTIX_MASTER,10);if(s===u){let d=r.pathname.match(Qm);if(d){let f=parseInt(d[1],10);if(f>=1&&f<=65535)return s=f,o=Qt(`${d[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let p=Qt(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${p}`,port:s,path:p}}catch{let r=Jm(e);return r&&r!==e?Yt(r):null}}function ef(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,u=o+r[0].length;t.some(([d,f])=>o>=d&&u<=f)||t.push([o,u])}return t}function tf(e,t){return t.some(([n,r])=>e>=n&&e<r)}function nf(e){let t=[],n=new Set,r=ef(e);ld.lastIndex=0;let s;for(;(s=ld.exec(e))!==null;){let o=Yt(s[0]);if(!o)continue;let{originalUrl:u,port:p,path:d}=o;p<1||p>65535||dd.has(p)||n.has(u)||(n.add(u),t.push({originalUrl:u,port:p,path:d,startIndex:s.index,endIndex:s.index+u.length,inCodeBlock:tf(s.index,r)}))}return t}function iA(e){return nf(e).length>0}function rf(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function gd(e){return e.trim().toLowerCase().split("_").join("-")}function md(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function sf(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let s=r.split("{port}").join(String(e)).split("{sandbox}").join(gd(n.sandboxId));return`${md(s)}${t}`}function of(e){return e.sandboxId.trim().length>0}function Se(e,t,n){let r=Qt(t);if(!of(n))return uf(e,r);let s=sf(e,r,n);return s||(rf(n.apiBaseUrl)?`http://p${e}-${gd(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${md(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function oA(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return Se(3211,`/open?path=/workspace/${r}`,t)}function af(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function aA(e){return`http://localhost:3211${af(e)}`}function cf(){return"/health"}function cA(e){return Se(3211,cf(),e)}function lA(e,t){return Se(e,"/",t)}function lf(e){let t=Yt(e);return!(!t||dd.has(t.port)||Zm(e))}function fd(e,t){if(!e)return e;let n=Yt(e);return n?lf(n.originalUrl)?Se(n.port,n.path,t):n.originalUrl:e}function uf(e,t="/"){return`http://localhost:${e}${t}`}var yd=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function hd(e){let t=e.match(ud);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(pd);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(yd);if(r)try{let s=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(s.port,10)||(s.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function uA(e){try{let t=hd(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function pA(e){return Hm(e)||pd.test(e)||yd.test(e)}function dA(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var ut="/web-proxy/";function gA(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${ut}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(ge.KORTIX_MASTER,10);return`${Se(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function mA(e){try{let t=new URL(e),n=t.pathname.indexOf(ut);if(n===-1)return null;let s=t.pathname.slice(n+ut.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],u=s[2],p=s[3]||"/";return`${o}://${u}${p}${t.search}${t.hash}`}catch{return null}}function fA(e){try{return new URL(e).pathname.includes(ut)}catch{return e.includes(ut)}}function yA(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 hA(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}var bd="frontend";function Zt(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${bd}] ${t}`,...n?[n]:[]);try{Pe().app.log({service:bd,level:e,message:t,extra:n})}catch{}}var me={debug:(e,t)=>Zt("debug",e,t),info:(e,t)=>Zt("info",e,t),warn:(e,t)=>Zt("warn",e,t),error:(e,t)=>Zt("error",e,t)};function pf(e){return{type:"heartbeat-gap",gapMs:e}}function df(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 gf={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},mf=16,ff=8,yf=6e4,hf=5e3,bf=250,xf=1e3,_f=3e4,Pf=5,wf=3e3,kf=3e4,Sf=2e4,vf=2e3,Af=8;function Cf(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function xd(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 en=new WeakMap;function Rf(e,t,n){let r=t.timers??gf,s=t.connectTimeoutMs??Sf,o=t.heartbeatTimeoutMs??yf,u=t.maxConsecutiveHardFailures??Af,p=new AbortController;function d(M,...$){for(let l of n){let y=M(l);if(y)try{y(...$)}catch(a){console.warn("[opencode-events] subscriber handler threw, skipping",a)}}}let f=r.now(),m=[],h,P=0,x=new Map,_=()=>{if(h&&r.clearTimeout(h),h=void 0,m.length===0)return;let M=m;m=[],x.clear(),P=r.now(),f=r.now();for(let $ of M)$&&d(l=>l.onEvent,$.event)},v=()=>{if(h)return;let M=r.now()-P;h=r.setTimeout(_,Math.max(0,mf-M))};return(async()=>{let M=0,$=0;for(;!p.signal.aborted;){let l=!1,y=!1,a,A,I=null,R=r.now(),w=new AbortController,F=xd(p.signal);F.promise.then(()=>w.abort());try{let q=await new Promise((Z,ee)=>{let G=!1;A=r.setTimeout(()=>{G||(G=!0,me.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:s}),w.abort(),ee(new Error(`SSE connect timed out after ${s}ms`)))},s),e.global.event({signal:w.signal,sseDefaultRetryDelay:wf,sseMaxRetryDelay:kf,sseMaxRetryAttempts:1}).then(J=>{G||(G=!0,r.clearTimeout(A),Z(J))},J=>{G||(G=!0,r.clearTimeout(A),ee(J))})}),{stream:N}=q;f=r.now();let B=()=>{r.clearTimeout(a),a=r.setTimeout(()=>{me.warn("SSE heartbeat timeout, forcing reconnect"),w.abort()},o)};B();let Q=r.now(),W=N[Symbol.asyncIterator]();for(;!w.signal.aborted;){let Z=W.next().then(oe=>({kind:"next",result:oe}),oe=>({kind:"error",error:oe})),ee=xd(w.signal),G=await Promise.race([Z,ee.promise.then(()=>({kind:"aborted"}))]);if(ee.cleanup(),G.kind==="aborted")break;if(G.kind==="error")throw G.error;if(G.result.done)break;l=!0,B();let J=G.result.value,he=J&&typeof J=="object"&&"payload"in J?J.payload:J;if(!he?.type)continue;let Ge=Cf(he);if(Ge){let oe=x.get(Ge);oe!==void 0&&(m[oe]=void 0),x.set(Ge,m.length)}m.push({type:he.type,event:he}),v(),!(r.now()-Q<ff)&&(Q=r.now(),await new Promise(oe=>r.setTimeout(oe,0)))}y=l}catch(q){if(p.signal.aborted)break;I=q;let N=String(q),B=N.includes("401")||N.includes("403")||N.includes("Unauthorized")||N.includes("Token refresh failed");if(me.error("SSE event stream error",{error:N,retryCount:M,isAuthError:B}),B)try{Pt(),await Fr(),me.info("SSE: refreshed auth token after auth error")}catch(Q){me.error("SSE: failed to refresh auth token",{error:String(Q)})}}finally{r.clearTimeout(a),r.clearTimeout(A),w.abort(),F.cleanup(),_()}if(p.signal.aborted)break;let j=r.now()-R,K=I?.cause?.status;if($=!l&&(typeof K=="number"&&K>=400||j<vf)?$+1:0,$>=u){me.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:$,lastError:String(I)}),d(q=>q.onParked,{consecutiveFailures:$,lastError:I});break}let b=r.now()-f;b>hf&&d(q=>q.onGapRehydrate,b),y?M=0:(M++,M>1&&me.warn("SSE event stream reconnecting",{retryCount:M}));let T=y?bf:Math.min(xf*2**Math.min(M-1,Pf),_f);await new Promise(q=>{let N=r.setTimeout(q,T),B=()=>{r.clearTimeout(N),q()};p.signal.addEventListener("abort",B,{once:!0})})}})(),{subscribers:n,teardown:()=>{p.abort(),h&&r.clearTimeout(h)}}}function Gs(e){let{client:t,onEvent:n,onGapRehydrate:r,onParked:s,signal:o}=e,u={onEvent:n,onGapRehydrate:r,onParked:s},p=en.get(t);p?p.subscribers.add(u):(p=Rf(t,e,new Set([u])),en.set(t,p));let d=p,f=!1,m=()=>{f||(f=!0,o&&o.removeEventListener("abort",h),d.subscribers.delete(u),d.subscribers.size===0&&(d.teardown(),en.get(t)===d&&en.delete(t)))},h=()=>m();return o&&(o.aborted?m():o.addEventListener("abort",h,{once:!0})),{close:m}}function Tf(){return Pe()}var tn=new Map,nn=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function If(e,t){hn(e,t);function n(l){try{return new URL(l)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(l,window.location.origin)}catch{return null}throw new S(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(l)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}function r(l){let y=O().backendUrl??e.backendUrl,a=80,A=n(y);return A&&(a=A.port?Number(A.port):A.protocol==="https:"?443:80),$i({sandboxId:l,apiBaseUrl:y,backendPort:a})}let s={signUp:Rs,signInWithPassword:Ts,sendMagicLink:Is,verifyOtp:Es,signInWithProvider:js,exchangeCode:$s,refresh:lt,resetPassword:Ms,updatePassword:Ds,updateUserMetadata:qs,signInWithSso:Us,mfa:Fs,user:Os,signOut:Ls,session:Bs},o={list:io,get:ao,create:oo,secretResources:{list:Ra,create:Ta,rotate:Ia,remove:Ea,grant:ja,revoke:$a,setAccess:Ma},updateName:co,branding:{get:lo,update:uo,uploadAsset:po,removeAsset:go,reset:mo},leave:vo,members:fo,invite:yo,removeMember:ko,updateMemberRole:So,invites:ho,cancelInvite:bo,resendInvite:xo,tokens:{list:wp,create:kp,revoke:Sp},audit:{log:Rp,export:Ip,webhooks:{list:Ep,create:jp,update:$p,remove:Mp}}},u={assignments:{list:cp,create:lp,revoke:up},permissions:{list:pp,forRole:zu},roles:{list:Hu,create:Xu,update:Ju,setPermissions:Qu,remove:Yu,usage:Vu},groups:{list:qu,get:Uu,create:Fu,update:Lu,remove:Bu,members:{list:Gu,add:Nu,remove:Ku}},agentIdentities:Wu,oauthClients:{list:tp,get:np,create:rp,update:sp,rotateSecret:ip,remove:op},can:Zu,canBatch:ep},p={accountState:Fl,accountStateMinimal:Ll,transactions:Bl,transactionsSummary:Gl,creditBreakdown:Nl,usageHistory:Kl,usageRollup:ru,sessionCosts:{list:iu,get:Ps},tierConfigurations:Hl,checkout:{createSession:l=>Wl(l),confirmSession:(l,y)=>zl(l,y)},subscription:{createPortalSession:(l,y)=>Vl(l,y),cancel:(l,y)=>Xl(l,y),reactivate:l=>Jl(l),scheduleDowngrade:(l,y,a)=>Ql(l,y,a),cancelScheduledChange:l=>Yl(l),prorationPreview:(l,y)=>Zl(l,y)},credits:{purchase:l=>eu(l),autoTopupSettings:l=>tu(l),configureAutoTopup:l=>nu(l)}},d={describe:_o,accept:Po,decline:wo},f={list:qe,listForAccount:Ro,get:rs,detail:ss,create:jo,createRepo:$o,provision:Mo,update:as,archive:cs,llmCatalog:is,modelPicker:os,modelAccess:As,setModelAccess:Cs,sandboxHealth:gs,sandboxTemplates:_c,sessions:ot,createSession:at},m={linkRepository:Fo,getInstallation:Lo,listInstallations:Bo,listLinkableInstallations:Go,listRepositories:No,listRepositoryBranches:Ko,linkInstallation:Wo,saveInstallation:Ho,deleteInstallation:zo},h={get:Vo,repositories:Xo},P={list:hp,create:bp,revoke:xp},x=fc,_={items:l=>qp(l),item:l=>Lp(l),itemFile:(l,y)=>Bp(l,y),marketplaces:()=>Up(),featured:()=>Fp(),sources:{list:()=>Gp(),add:l=>Np(l),remove:l=>Kp(l)}};function v(l){return{catalog:()=>us(l),tools:()=>Ht(l),search:(...y)=>Ua(l,...y),describe:(...y)=>Fa(l,...y),call:(...y)=>La(l,...y),accounts:(...y)=>Ba(l,...y),uploadAttachment:(...y)=>Ga(l,...y)}}function M(l){let y={list:()=>Na(l),listAll:()=>Ka(l),reconcile:(...a)=>Ha(l,...a),reconcileMember:(...a)=>Wa(l,...a),updateCredential:(...a)=>za(l,...a),revoke:(...a)=>Va(l,...a),activate:(...a)=>Xa(l,...a),setDefault:(...a)=>Ja(l,...a),pipedreamConnect:(...a)=>Qa(l,...a),pipedreamFinalize:(...a)=>Ya(l,...a)};return{attachments:{upload:(...a)=>Nt(l,...a),delete:(...a)=>Oe(l,...a),createController:a=>so(l,a)},get:a=>rs(l,a),detail:()=>ss(l),audit:a=>Tp(l,a),update:a=>as(l,a),archive:()=>cs(l),llmCatalog:()=>is(l),modelPicker:()=>os(l),modelAccess:()=>As(l),setModelAccess:a=>Cs(l,a),sandboxHealth:()=>gs(l),onboardingComplete:(...a)=>Uo(l,...a),apps:{list:()=>Hp(l),create:a=>Wp(l,a),get:a=>zp(l,a),update:(...a)=>Vp(l,...a),access:{get:(...a)=>Jp(l,...a),update:(...a)=>Qp(l,...a),session:(...a)=>Yp(l,...a)},remove:a=>Xp(l,a),artifacts:{register:a=>Ss(l,a),uploadArchive:(...a)=>Zp(l,...a),finalize:(...a)=>vs(l,...a)},deployments:{create:(...a)=>ed(l,...a),list:a=>td(l,a),get:(...a)=>nd(l,...a),logs:(...a)=>rd(l,...a)},start:a=>sd(l,a),stop:a=>id(l,a),rollback:(...a)=>od(l,...a)},tokens:{list:()=>vp(l),create:a=>Ap(l,a),revoke:a=>Cp(l,a)},setupLinks:{requestSecret:a=>Dp(l,a),requestConnector:a=>Op(l,a)},validateManifest:a=>Io(l,a),gitToken:()=>Eo(l),secrets:{list:()=>ya(l),upsert:a=>ha(l,a),setStrategy:(...a)=>ba(l,...a),broker:(...a)=>xa(l,...a),remove:a=>Sa(l,a),setPersonal:(...a)=>va(l,...a),removePersonal:a=>Aa(l,a),setGitCredential:a=>ka(l,a),startProviderOAuth:(...a)=>_a(l,...a),pollProviderOAuth:(...a)=>Pa(l,...a),removeProviderOAuth:a=>wa(l,a)},access:{list:()=>Zo(l),invite:(...a)=>na(l,...a),update:(...a)=>ea(l,...a),revoke:a=>ta(l,a),pendingInvites:()=>ra(l),resendInvite:(...a)=>ia(l,...a),revokeInvite:(...a)=>sa(l,...a),requests:()=>Jo(l),approveRequest:(...a)=>Qo(l,...a),rejectRequest:(...a)=>Yo(l,...a),groupGrants:()=>oa(l),attachGroupGrant:(...a)=>aa(l,...a),updateGroupGrant:(...a)=>ca(l,...a),detachGroupGrant:a=>la(l,a),resourceGrants:{list:()=>ua(l),create:a=>pa(l,a),remove:a=>da(l,a)}},connectors:{...v(l),list:()=>Za(l),config:(...a)=>oc(l,...a),create:(...a)=>lc(l,...a),remove:(...a)=>pc(l,...a),sync:()=>ec(l),auth:{discover:(...a)=>uc(l,...a)},setName:(...a)=>ac(l,...a),setCredentialMode:(...a)=>tc(l,...a),setAuthorizationStrategy:(...a)=>nc(l,...a),setCredential:(...a)=>yc(l,...a),setSensitive:(...a)=>rc(l,...a),connections:y,policies:{get:(...a)=>sc(l,...a),set:(...a)=>ic(l,...a)},pipedream:{listApps:(...a)=>dc(l,...a),listSections:(...a)=>gc(l,...a),connect:(...a)=>cc(l,...a),finalize:(...a)=>hc(l,...a)},discover:{list:(...a)=>ps(l,...a),sections:(...a)=>mc(l,...a),detail:(...a)=>ds(l,...a)}},policies:{list:()=>bc(l),set:(...a)=>xc(l,...a)},triggers:{list:()=>wl(l),create:(...a)=>kl(l,...a),update:(...a)=>Sl(l,...a),remove:(...a)=>vl(l,...a),fire:(...a)=>Cl(l,...a),setActivation:(...a)=>Al(l,...a)},files:{list:a=>Tc(l,a),read:(a,A)=>Ec(l,a,A),search:(...a)=>Ic(l,...a),archive:(...a)=>jc(l,...a),history:(...a)=>qc(l,...a)},git:{commits:()=>Mc(l),commit:a=>Dc(l,a),commitDiff:a=>Oc(l,a),branches:()=>$c(l),versionDiff:(...a)=>Uc(l,...a),inviteCollaborator:(...a)=>To(l,...a)},changeRequests:{list:()=>Fc(l),get:a=>Lc(l,a),diff:a=>Bc(l,a),mergePreview:a=>Gc(l,a),open:(...a)=>Nc(l,...a),merge:(...a)=>Kc(l,...a),close:(...a)=>Hc(l,...a),reopen:(...a)=>Wc(l,...a),requestChanges:(...a)=>zc(l,...a)},sessions:{list:a=>ot(l,a),listPage:a=>Qc(l,a),create:a=>at(l,a),ensureWarm:()=>rl(l),claimWarm:a=>sl(l,a)},review:{list:a=>dp(l,a),get:a=>gp(l,a),submit:a=>mp(l,a),act:(...a)=>fp(l,...a),bulkAct:a=>yp(l,a)},approvals:{list:a=>ga(l,a),resolve:(...a)=>fa(l,...a),sessionsNeedingInput:a=>ma(l,a)},gateway:{logs:a=>ku(l,a),log:a=>Su(l,a),overview:a=>vu(l,a),series:a=>Au(l,a),breakdown:a=>Cu(l,a),sessions:a=>Ru(l,a),errors:a=>Tu(l,a),budgets:()=>Iu(l),setBudget:a=>Eu(l,a),deleteBudget:a=>ju(l,a),keys:()=>$u(l),createKey:a=>Mu(l,a),revokeKey:a=>Du(l,a),routing:{get:()=>xu(l),set:a=>_u(l,a),reset:()=>Pu(l),preview:a=>wu(l,a)},playground:(a,A,I)=>Ou(l,a,A,I)},channels:{slack:{installation:()=>au(l),connect:a=>cu(l,a),mode:()=>lu(l),manifest:()=>uu(l),disconnect:()=>pu(l),getFile:a=>du(l,a),uploadFile:a=>gu(l,a)},email:{installation:a=>mu(l,a),mode:()=>fu(l),connect:a=>yu(l,a),disconnect:a=>hu(l,a),updatePolicy:(...a)=>bu(l,...a)}},updateFeatureFlag:(...a)=>Do(l,...a),updateExperimentalFeature:(...a)=>Oo(l,...a),modelDefaults:{get:()=>jl(l),set:a=>$l(l,a),clear:a=>Ml(l,a)},setDefaultAgent:a=>Ul(l,a),sandbox:{list:()=>Rc(l),snapshots:()=>Pc(l),rebuildSnapshot:a=>wc(l,a),fixWithAgent:()=>kc(l),createTemplate:a=>Sc(l,a),updateTemplate:(...a)=>vc(l,...a),removeTemplate:a=>Ac(l,a),buildTemplate:a=>Cc(l,a),setProvider:a=>qo(l,a)},setAgentScope:(...a)=>Ol(l,...a),session:a=>$(l,a)}}function $(l,y){let a=null,A,I,R=null;async function w(){R||(R=fs(l,y,{showErrors:!1}).then(b=>{let T=typeof b.metadata?.opencode_model=="string"?b.metadata.opencode_model.trim():"",q=T.indexOf("/"),N=q>0&&q<T.length-1?{providerID:T.slice(0,q),modelID:T.slice(q+1)}:void 0,B=b.agent_name?.trim()||void 0;return{model:N,agent:B}}));try{return await R}catch(b){throw R=null,b}}function F(){if(a)return a;let b=Tl(l,y);return b&&(a=b),a}async function j(b){let T=F();if(T)return T;let q=b?.readyTimeoutMs??18e4,N=Ct(O().backendUrl??e.backendUrl).catch(()=>null),B=`${l}
20
+ ${y}`,Q=tn.get(B);if(Q)return a=await Q,await N,a;let W=(async()=>{let Z=Date.now()+q,ee=()=>Math.max(0,Z-Date.now()),G=await Ue(l,y,Math.min(3e4,ee()));for(;Date.now()<Z&&(G==null||(G.stage==="provisioning"||G.stage==="starting")&&G.retriable);)await new Promise(Ge=>setTimeout(Ge,Math.min(1e3,ee()))),G=await Ue(l,y,Math.min(3e4,ee()));if(!G||G.stage!=="ready"||!G.sandbox||!G.opencode_session_id)throw new S(`Session runtime not ready (stage: ${G?.stage??"unknown"})`,{code:"RUNTIME_UNAVAILABLE"});let J=G.sandbox.external_id;if(!J)throw new S("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let he=wt(J);return _i(he,J),{opencodeSessionId:G.opencode_session_id,runtimeUrl:he,sandboxId:J}})();tn.set(B,W);try{return a=await W,await N,a}finally{tn.get(B)===W&&tn.delete(B)}}function K(b){let T=F();if(!T)throw new nn(b);return T}function D(){a=null,El(l,y)}return{get:b=>fs(l,y,b),cost:()=>Ps(y,{projectId:l}),update:b=>ml(l,y,b),delete:()=>(D(),fl(l,y)),start:(...b)=>Ue(l,y,...b),restart:()=>(D(),zt(l,y)),stop:()=>(D(),Vt(l,y)),configState:()=>yl(l,y),reloadConfig:b=>(D(),hl(l,y,b)),reloadConfigStream:(...b)=>(D(),bl(l,y,...b)),setSharing:b=>Yc(l,y,b),previews:()=>Zc(l,y),commit:b=>Vc(l,y,b),publicShares:{list:()=>el(l,y),create:(...b)=>tl(l,y,...b),revoke:(...b)=>nl(l,y,...b)},audit:(b,T)=>il(l,y,b,T),transcript:b=>ol(l,y,b),transcriptSync:b=>al(l,y,b),turn:()=>cl(l,y),prompts:{create:b=>ll(l,y,b),list:()=>ul(l,y),remove:b=>pl(l,y,b),retry:b=>dl(l,y,b),hold:b=>gl(l,y,b)},ensureReady:j,health:b=>cd(F()?.runtimeUrl??null,b),previewUrl:(b,T="/")=>Se(b,T,r(K("previewUrl").sandboxId)),proxyUrl:b=>fd(b,r(K("proxyUrl").sandboxId)),setModel:b=>{A=b},changeModel:async b=>{let T=await Pl(l,y,b);return R=null,T},scope:()=>xl(l,y),providerSecretPool:{list:()=>Oa(l,y),get:b=>Da(l,y,b),set:(b,T)=>qa(l,y,b,T)},rescope:b=>_l(l,y,b),setAgent:b=>{I=b},send:async(b,T)=>{let{opencodeSessionId:q,runtimeUrl:N}=await j(),B=T?.model??A,Q=T?.agent??I,W=B&&Q?{}:await w(),Z=B??W.model,ee=Q??W.agent;return pe(N).session.prompt({sessionID:q,parts:[{type:"text",text:b}],...Z?{model:Z}:{},...ee?{agent:ee}:{}})},abort:async()=>{let{opencodeSessionId:b,runtimeUrl:T}=await j();return pe(T).session.abort({sessionID:b})},rewind:async b=>{let{opencodeSessionId:T,runtimeUrl:q}=await j();return pe(q).session.revert({sessionID:T,messageID:b})},restoreRewind:async()=>{let{opencodeSessionId:b,runtimeUrl:T}=await j();return pe(T).session.unrevert({sessionID:b})},stream:async b=>{let{runtimeUrl:T}=await j();return Gs({client:pe(T),onEvent:b.onEvent,onGapRehydrate:b.onGapRehydrate,signal:b.signal})},get runtime(){return pe(K("runtime").runtimeUrl)},files:{list:async b=>Mt(b,(await j()).runtimeUrl),read:async b=>Ye(b,(await j()).runtimeUrl),readBlob:async b=>Ze(b,(await j()).runtimeUrl),status:async()=>Dt((await j()).runtimeUrl),findFiles:async(b,T)=>Ot(b,T,(await j()).runtimeUrl),findText:async b=>qt(b,(await j()).runtimeUrl),upload:async(b,T,q,N)=>et(b,T,q,(await j()).runtimeUrl,N),write:async(b,T)=>tt(b,T,(await j()).runtimeUrl),create:async b=>Ut(b,(await j()).runtimeUrl),copy:async(b,T)=>Ft(b,T,(await j()).runtimeUrl),remove:async b=>ke(b,(await j()).runtimeUrl),mkdir:async b=>nt(b,(await j()).runtimeUrl),rename:async(b,T)=>we(b,T,(await j()).runtimeUrl)}}}return{config:e,auth:s,accounts:o,iam:u,accountInvites:d,projects:f,connectors:v(),project:M,session:$,github:m,gitBackend:h,billing:p,sandboxShares:P,connectStatus:x,marketplace:_,validateToken:Ao,runtime:Tf}}function Ef(){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 jf(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Fe(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function $f(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function Mf(e){if(Fe(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 Df(e){let t=Fe(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function Of(e,t){let n=Fe(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function qf(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function Uf(e,t){return Fe(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 Ff(e,t,n){return Fe(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 Lf(e,t,n){let r=Fe(e);if(r.includes(t))return e;let s=e.pending.findIndex(f=>f.id===t);if(s===-1)return e;let o=r.length,u=Math.min(Math.max(n,o),e.pending.length-1);if(u===s)return e;let p=[...e.pending],[d]=p.splice(s,1);return p.splice(u,0,d),{...e,pending:p}}var _d={thinking:!1,toolDetails:!0,assistantMetadata:!0};function Bf(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function Gf(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 Nf(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
21
21
 
22
22
  `;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
23
23
  >
@@ -50,15 +50,15 @@ ${s}
50
50
  ${e.state.error}
51
51
  \`\`\`
52
52
  `),n+=`
53
- `,n}return""}function Gf(e,t){if(!t)return`## Assistant
53
+ `,n}return""}function Kf(e,t){if(!t)return`## Assistant
54
54
 
55
- `;let n=e.agent?Ff(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=Lf(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
55
+ `;let n=e.agent?Bf(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=Gf(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
56
56
 
57
57
  `:`## ${n}
58
58
 
59
- `}function Nf(e,t,n){let r="";e.role==="user"?r+=`## User
59
+ `}function Hf(e,t,n){let r="";e.role==="user"?r+=`## User
60
60
 
61
- `:r+=Gf(e,n.assistantMetadata);for(let s of t)r+=Bf(s,n);return r}function Kf(e,t,n=bd){let r=`# ${e.title||"Untitled Session"}
61
+ `:r+=Kf(e,n.assistantMetadata);for(let s of t)r+=Nf(s,n);return r}function Wf(e,t,n=_d){let r=`# ${e.title||"Untitled Session"}
62
62
 
63
63
  `;r+=`**Session ID:** \`${e.id}\`
64
64
  `,r+=`**Created:** ${new Date(e.time.created).toLocaleString()}
@@ -66,14 +66,14 @@ ${e.state.error}
66
66
 
67
67
  `,r+=`---
68
68
 
69
- `;for(let s of t)r+=Nf(s.info,s.parts,n),r+=`---
69
+ `;for(let s of t)r+=Hf(s.info,s.parts,n),r+=`---
70
70
 
71
- `;return r}function Hf(e,t){return`session-${e}.md`}var Ns="An error occurred";var Wf=["message","error","detail","error_description","msg","errors","data"];function kd(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 Le(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function zf(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=Le(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function Vf(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=Xf(e,t);if(n)return n;let r=Qf(e,t);return r?r.slice(0,200):void 0}function wd(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function xd(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function Xf(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!wd(t.charCodeAt(s))){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return;let u=e.indexOf("<",o+1);if(u!==-1&&t.startsWith("</title",u)){let p=e.slice(o+1,u).trim();if(p)return p}n=o+1}}var Jf=["script","style"];function Qf(e,t){let n=[],r=0;for(;r<e.length;){let s=e.indexOf("<",r);if(s===-1){n.push(e.slice(r));break}n.push(e.slice(r,s));let o=Jf.find(u=>t.startsWith(`<${u}`,s)&&wd(t.charCodeAt(s+u.length+1)));if(o){let u=t.indexOf(`</${o}`,s);r=u===-1?e.length:xd(e,u);continue}r=xd(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function Yf(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function _d(e,t,n){if(typeof e=="string")return nn(e,t,n);if(e&&typeof e=="object")return rn(e,t,n)}function nn(e,t,n=new WeakSet){let r=kd(e);if(!r)return;if(t>=4)return r;let s=Le(r);if(s!==void 0)return typeof s=="string"?nn(s,t+1,n):s&&typeof s=="object"?rn(s,t+1,n):String(s);let o=Sd(r);if(o){let u=Le(o);if(u&&typeof u=="object"){let p=rn(u,t+1,n);if(p)return p}}if(r.includes("{")){let u=zf(r);if(u)return nn(u,t+1,n)??u}return Vf(r)??r}function rn(e,t,n=new WeakSet){if(t>=4||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let u of e){let p=_d(u,t,n);if(p)return p}return}let r=e;for(let u of Wf){let p=_d(r[u],t,n);if(p)return p}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return Yf(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function ne(e){return e?typeof e=="string"?nn(e,0)??Ns:typeof e=="object"?rn(e,0)??Ns:String(e):Ns}function Sd(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function Zf(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 ey(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 Pd(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,s=typeof e.upstream_status=="number"?e.upstream_status:void 0,o=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,u=ey(e.attempt_failures);return!t&&!n&&!r&&s===void 0&&!o&&!u?void 0:{message:typeof e.message=="string"&&e.message||Zf(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:u}}function ie(e){if(e==null)return;if(typeof e=="string"){let u=kd(e),p=Le(u)??Le(Sd(u));return p!==void 0?ie(p):void 0}if(typeof e!="object")return;let t=e,n=Pd(t);if(n)return n;let r=t.error;if(r&&typeof r=="object"&&!Array.isArray(r)){let u=Pd(r);if(u)return u}let s=t.data;if(s&&typeof s.responseBody=="string"){let u=Le(s.responseBody);if(u!==void 0){let p=ie(u);if(p)return p}}if(s&&typeof s.message=="string"){let u=ie(s.message);if(u)return u}let o=t.cause;if(o&&typeof o=="object"){let u=o.body;if(u!==void 0){let p=ie(u);if(p)return p}}}var ty={bash:{label:"Shell",category:"shell"},pty_spawn:{label:"Spawn Terminal",category:"shell"},pty_read:{label:"Terminal Output",category:"shell"},pty_write:{label:"Terminal Input",category:"shell"},pty_input:{label:"Terminal Input",category:"shell"},pty_kill:{label:"Kill Process",category:"shell"},read:{label:"Read File",category:"files"},list:{label:"List Directory",category:"files"},ls:{label:"List Directory",category:"files"},write:{label:"Write File",category:"edit"},edit:{label:"Edit File",category:"edit"},multiedit:{label:"Edit File",category:"edit"},morph_edit:{label:"Edit File",category:"edit"},apply_patch:{label:"Apply Patch",category:"edit"},patch:{label:"Apply Patch",category:"edit"},grep:{label:"Search Code",category:"search"},glob:{label:"Find Files",category:"search"},image_search:{label:"Image Search",category:"search"},session_search:{label:"Search Sessions",category:"search"},webfetch:{label:"Fetch Page",category:"web"},scrape_webpage:{label:"Scrape Page",category:"web"},websearch:{label:"Web Search",category:"web"},web_search:{label:"Web Search",category:"web"},image_gen:{label:"Generate Image",category:"web"},video_gen:{label:"Generate Video",category:"web"},task:{label:"Delegate to Agent",category:"task"},todowrite:{label:"Plan Tasks",category:"task"},todoread:{label:"Read Plan",category:"task"},question:{label:"Ask Question",category:"task"},presentation_gen:{label:"Presentation",category:"task"},show:{label:"Show Output",category:"task"},show_user:{label:"Show Output",category:"task"},prune:{label:"Prune Context",category:"other"},distill:{label:"Distill Context",category:"other"},compress:{label:"Compress Context",category:"other"},context_info:{label:"Context Info",category:"other"}},ny=[{prefix:"pty_",category:"shell"},{prefix:"agent_",category:"task"},{prefix:"session_",category:"task"},{prefix:"task_",category:"task"},{prefix:"trigger_",category:"task"},{prefix:"project_",category:"task"}];function ry(e){return e.replace(/^oc[-_]/,"")}function sn(e){return ry(e).replace(/-/g,"_")}function Ks(e){return sn(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Hs(e){let t=sn(e),n=ty[t];if(n)return n;for(let{prefix:r,category:s}of ny)if(t.startsWith(r))return{label:Ks(e),category:s};return{label:Ks(e),category:"other"}}var sy=256*1024;function iy(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function oy(e){if(e===void 0)return{};if(e.length>sy)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function ay(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,s=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!s))return s?ne(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}function cy(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=oy(r),u=iy(t),p=t.status==="error"?t.error:void 0;if(u==="done"){let d=ay(s);d&&(u="error",p=d)}return{name:e,title:n||Hs(e).label,status:u,input:t.input,output:r,outputParsed:s,outputText:o,error:p}}function ly(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function uy(e){return{kind:"reasoning",id:e.id,text:e.text}}function py(e){return{kind:"tool",id:e.id,tool:cy(e.tool,e.state)}}function dy(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 gy(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function my(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function fy(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function yy(e){return{kind:"agent",id:e.id,name:e.name}}function hy(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:ne(e.error),createdAt:e.time.created}}function by(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function xy(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function _y(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function vd(e){switch(e.type){case"text":return ly(e);case"reasoning":return uy(e);case"tool":return py(e);case"file":return dy(e);case"subtask":return gy(e);case"patch":return my(e);case"snapshot":return fy(e);case"agent":return yy(e);case"retry":return hy(e);case"compaction":return by(e);case"step-start":return xy(e);case"step-finish":return _y(e);default:return{kind:"unknown",raw:e}}}function Py(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=ie(e);return{name:t,message:n?.message||ne(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function ky(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function wy(e){let t=e.parts.map(vd),n=e.info.role==="assistant"?e.info.error:void 0,r=Py(n),s=!r&&!t.some(ky);return{parts:t,error:r,isEmpty:s}}function ve(e){return e.type==="text"}function Ws(e){return e.type==="reasoning"}function fe(e){return e.type==="tool"}function Cd(e){return e.type==="file"}function zA(e){return e.type==="agent"}function VA(e){return e.type==="compaction"}function XA(e){return e.type==="snapshot"}function JA(e){return e.type==="patch"}function QA(e){if(ve(e)||Ws(e))return e.text}function YA(e){if(!Cd(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function ZA(e){let t=[],n=[];for(let r of e)Cd(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function eC(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function tC(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var Sy=new Set(["todoread","context_info"]);function vy(e){return!Sy.has(e.tool)}function nC(e){let t=e.tool||"";if(t==="task"||t==="agent_spawn"||t==="agent-spawn"||t==="agent_message"||t==="agent-message"||t==="agent_task"||t==="agent-task"||t==="agent_task_update"||t==="agent-task-update"||t==="agent_task_message"||t==="agent-task-message"||t==="agent_task_start"||t==="agent-task-start"||t==="task_create"||t==="task-create"||t==="task_start"||t==="task-start"||t==="task_update"||t==="task-update"||t==="task_message"||t==="task-message"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r;let s=e.state?.title;if(s){let u=s.match(/\bses_[a-zA-Z0-9]+/);if(u)return u[0]}let o=e.state?.output;if(o){let u=o.match(/\bses_[a-zA-Z0-9]+/);if(u)return u[0]}return}let n=e.tool?.replace(/-/g,"_")||"";if(n==="session_spawn"||n==="session_start_background"){let r=e.state?.output;if(r){let s=r.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/);if(s)return s[1]}return}}function rC(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return ne(n.error)}}function sC(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)fe(r)&&vy(r)&&t.push(r);return t}function iC(e,t={}){switch(e){case"read":return{icon:"glasses",title:"Read",subtitle:Ay(t.filePath)};case"list":return{icon:"list",title:"List",subtitle:Cy(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web-search":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:Ry(t)};case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":case"oc-session_spawn":case"oc-session-spawn":case"oc-session_start_background":case"oc-session-start-background":return{icon:"square-kanban",title:`Worker (${t.agent||"KortixWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":case"morph_edit":return{icon:"file-pen",title:"Edit",subtitle:Ad(t.filePath)};case"write":return{icon:"file-pen",title:"Write",subtitle:Ad(t.filePath)};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"todowrite":return{icon:"check-square",title:"Todos"};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"question":return{icon:"message-circle",title:"Questions"};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":case"session-read":case"oc-session_read":case"oc-session-read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":case"session-search":case"oc-session_search":case"oc-session-search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":case"session-message":case"oc-session_message":case"oc-session-message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":case"session-lineage":case"oc-session_lineage":case"oc-session-lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session-list-background":case"session_list_spawned":case"session-list-spawned":case"oc-session_list_background":case"oc-session-list-background":case"oc-session_list_spawned":case"oc-session-list-spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":case"session-stats":case"oc-session_stats":case"oc-session-stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":case"session-list":case"oc-session_list":case"oc-session-list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":case"session-get":case"oc-session_get":case"oc-session-get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":case"session-context":case"oc-session_context":case"oc-session-context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":case"project-delete":case"oc-project_delete":case"oc-project-delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":case"project-list":case"oc-project_list":case"oc-project-list":return{icon:"folder",title:"Projects"};case"project_get":case"project-get":case"oc-project_get":case"oc-project-get":case"project_update":case"project-update":case"oc-project_update":case"oc-project-update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":case"project-select":case"oc-project_select":case"oc-project-select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":case"project-create":case"oc-project_create":case"oc-project-create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":case"trigger-create":case"oc-trigger_create":case"oc-trigger-create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":case"trigger-list":case"oc-trigger_list":case"oc-trigger-list":return{icon:"clock",title:"List Triggers"};case"trigger_get":case"trigger-get":case"oc-trigger_get":case"oc-trigger-get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":case"trigger-delete":case"oc-trigger_delete":case"oc-trigger-delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":case"trigger-update":case"oc-trigger_update":case"oc-trigger-update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":case"trigger-test":case"oc-trigger_test":case"oc-trigger-test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":case"trigger-pause":case"oc-trigger_pause":case"oc-trigger-pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":case"trigger-resume":case"oc-trigger_resume":case"oc-trigger-resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":case"agent-spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":case"agent-message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":case"agent-stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":case"agent-status":return{icon:"layers",title:"Agent Status"};case"agent_task":case"agent-task":case"oc-agent_task":case"oc-agent-task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":case"agent-task-update":case"oc-agent_task_update":case"oc-agent-task-update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":case"agent-task-list":case"oc-agent_task_list":case"oc-agent-task-list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":case"agent-task-get":case"oc-agent_task_get":case"oc-agent-task-get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":case"task-create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":case"task-list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":case"task-update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":case"task-done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":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{icon:"cpu",title:e}}}function Ay(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Ad(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 Cy(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function oC(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function ut(e,t=120){if(typeof e!="string")return"";let n=e.split(`
72
- `).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function Ry(e){let t=ut(e.description);if(t)return t;let n=ut(e.title,80);if(n)return n;let r=ut(e.message);if(r)return r;let s=ut(e.prompt);if(s)return s;let o=ut(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function aC(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function cC(e,t){return e.find(n=>n.tool?.callID===t)}function lC(e,t){return e.find(n=>n.tool?.callID===t)}var Ty=/\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 uC(e){return e?e.replace(Ty,""):""}var Iy=/^msg_[0-9a-f]{12}/;function Rd(e){return Iy.test(e)?0:1}function Td(e,t){return e<t?-1:e>t?1:0}function Ey(e,t){let n=Rd(e.info.id),r=Rd(t.info.id);if(n!==r)return n-r;if(n===0)return Td(e.info.id,t.info.id);let s=typeof e.info.time?.created=="number"?e.info.time.created:null,o=typeof t.info.time?.created=="number"?t.info.time.created:null;return s===null&&o===null?0:s===null?1:o===null?-1:s!==o?s<o?-1:1:Td(e.info.id,t.info.id)}function gC(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((p,d)=>[p,d])),r=[...e].sort((p,d)=>{let f=n.get(p.info.id),m=n.get(d.info.id);return f!==void 0&&m!==void 0?f-m:f!==void 0?1:m!==void 0?-1:Ey(p,d)}),s=[],o=new Map;for(let p of r)if(p.info.role==="user"){if(o.has(p.info.id))continue;let d={userMessage:p,assistantMessages:[]};s.push(d),o.set(p.info.id,d)}let u=null;for(let p of r){if(p.info.role==="user"){u=o.get(p.info.id)??null;continue}if(p.info.role!=="assistant")continue;let d=p.info,f=d.tokens;if(!d.error&&p.parts.length===0&&f?.input===0&&f.output===0&&f.reasoning===0)continue;if(d.parentID){let h=o.get(d.parentID);if(h){h.assistantMessages.push(p);continue}}if(u){u.assistantMessages.push(p);continue}if(s.length>0){s[0].assistantMessages.unshift(p);continue}let m={userMessage:p,assistantMessages:[]};s.push(m)}return s}function mC(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function fC(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(ve(n)&&n.text?.trim())return n}}function yC(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function hC(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!fe(o))continue;let u=o,p=u.state?.metadata?.answers;u.tool==="question"&&(p?.length??0)>0&&r.push({part:o,message:s})}return r}function bC(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 xC(e){let t=e-6e4;return(n,r)=>{let s=n.time.updated??n.time.created,o=r.time.updated??r.time.created,u=s>t,p=o>t;return u&&p?n.id<r.id?-1:n.id>r.id?1:0:u&&!p?-1:!u&&p?1:o-s}}function jy(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let s of n)r.push(s),r.push(...jy(e,s));return r}function $y(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function PC(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&&$y(n.error)}return!1}function My(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>ve(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return fe(s)&&s.tool==="bash"}function SC(e){if(My(e))return e.assistantMessages[0].parts[0]}function RC(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 TC(e,t){return!t||!e?!1:e.type!=="idle"}function IC(e,t){return!e&&!!t}function EC(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ne(n.error)}}function jC(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ie(n.error)}}function Id(e){if(e){if(fe(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(Ws(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(ve(e))return"Gathering thoughts..."}}function $C(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,s=fe(r)?r:void 0;if(s&&(s.tool==="task"||s.tool==="agent_task"||s.tool==="agent-task"||s.tool==="task_create"||s.tool==="task-create"||s.tool==="task_start"||s.tool==="task-start")&&s.state.status==="running"&&t&&t.length>0){for(let u=t.length-1;u>=0;u--){let p=t[u];if(p.info.role==="assistant")for(let d=p.parts.length-1;d>=0;d--){let f=Id(p.parts[d]);if(f)return f}}return"Handing off to an agent..."}let o=Id(r);if(o)return o}return"Figuring out what\u2019s next..."}function MC(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 Ed=1.2;function jd(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),s=e.cache?.read??0,o=e.cache?.write??0,u=Math.max(0,n-s-o),d=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(m=>n>m.contextThreshold).sort((m,h)=>h.contextThreshold-m.contextThreshold)[0]??t,f=u/1e6*d.inputPer1M;return f+=r/1e6*d.outputPer1M,s>0&&(f+=s/1e6*(d.cacheReadPer1M??d.inputPer1M)),o>0&&(f+=o/1e6*(d.cacheWritePer1M??d.inputPer1M)),f}function zs(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function $d(e,t,n,r){if(zs(t,n))return 0;let s=e.cost||0;if(s>0)return s;if(!r||!t||!n)return 0;let o=r(t,n);return o?jd(e.tokens,o):0}function Md(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function DC(e,t){let n=0,r=0,s=0,o=0,u=0,p=0,d=!1;for(let{part:f,message:m}of e)if(f.type==="step-finish"){d=!0;let h=f,{providerID:P,modelID:x}=Md(m.info);n+=$d(h,P,x,t),r+=h.tokens?.input||0,s+=h.tokens?.output||0,o+=h.tokens?.reasoning||0,u+=h.tokens?.cache?.read||0,p+=h.tokens?.cache?.write||0}if(!d){let f=new Set;for(let{message:m}of e){if(m.info.role!=="assistant")continue;let h=m.info;if(f.has(h.id))continue;f.add(h.id);let P=Dd(h,t),x=h.tokens&&zs(h.providerID,h.modelID);if(P<=0&&!x)continue;d=!0,n+=P;let _=h.tokens;_&&(r+=_.input??0,s+=_.output??0,o+=_.reasoning??0,u+=_.cache?.read??0,p+=_.cache?.write??0)}}if(d)return{cost:n*Ed,tokens:{input:r,output:s,reasoning:o,cacheRead:u,cacheWrite:p}}}function Dd(e,t){if(zs(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?jd({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function OC(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:u}=Md(s),p=0,d=!1;for(let f of r.parts)f.type==="step-finish"&&(d=!0,p+=$d(f,o,u,t));d||(p+=Dd(s,t)),n+=p}return n*Ed}function qC(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function UC(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function FC(e){if(!e||e.type!=="retry")return;let t=e,n=ne(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:ie(t.message)}}function LC(e){if(!(!e||e.type!=="retry"))return ne(e.message)}function BC(e){return(e.info.summary?.diffs?.length??0)>0}var Dy=4e3;function pt(e,t=Dy){return e.length>t?`${e.slice(0,t)}
73
- \u2026`:e}function Od(e){if(e!==void 0)try{return pt(JSON.stringify(e,null,2))}catch{return}}function H(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function Be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Oy(e){let t=H(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=Be(e.outputParsed);if(!n)return{kind:"web-search",query:t};let s=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(o=>{let u=Be(o)??{};return{title:H(u.title)??"",url:H(u.url,u.link)??"",snippet:H(u.snippet,u.description,u.source)}});return{kind:"web-search",query:H(n.query)??t,results:s.length>0?s:void 0,answer:H(n.answer)}}var qy=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Ud(e){let t=e.match(qy);return t?Number(t[1]):void 0}function Uy(e,t,n){let r="",s=0;for(;;){let o=e.indexOf(t,s);if(o===-1)return r+e.slice(s);let u=e.indexOf(n,o+t.length);if(u===-1)return r+e.slice(s);r+=e.slice(s,o),s=u+n.length}}var Fy=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function Ly(e){let t=-1;for(let n of Fy){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var By=/\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 Gy(e){return e.replace(By,"")}function Ny(e){let t=H(e.input?.command)??"",n=e.output??"",r=Ud(n),o=Gy(Ly(Uy(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:o||void 0,exitCode:r}}function Xs(e){return H(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function Ky(e){let t=e.status==="error"?e.error:e.output&&pt(e.output)||void 0;return{kind:"file-read",path:Xs(e),preview:t}}function Hy(e){let t=H(e.input?.content),n=e.status==="error"?e.error:pt(t??e.output??"")||void 0;return{kind:"file-write",path:Xs(e),preview:n}}var Wy=256*1024;function zy(e,t){if(e.length+t.length>Wy)return;let n=e.split(`
71
+ `;return r}function zf(e,t){return`session-${e}.md`}var Ns="An error occurred";var Vf=["message","error","detail","error_description","msg","errors","data"];function Sd(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 Le(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function Xf(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=Le(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function Jf(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=Qf(e,t);if(n)return n;let r=Zf(e,t);return r?r.slice(0,200):void 0}function vd(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function Pd(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function Qf(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!vd(t.charCodeAt(s))){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return;let u=e.indexOf("<",o+1);if(u!==-1&&t.startsWith("</title",u)){let p=e.slice(o+1,u).trim();if(p)return p}n=o+1}}var Yf=["script","style"];function Zf(e,t){let n=[],r=0;for(;r<e.length;){let s=e.indexOf("<",r);if(s===-1){n.push(e.slice(r));break}n.push(e.slice(r,s));let o=Yf.find(u=>t.startsWith(`<${u}`,s)&&vd(t.charCodeAt(s+u.length+1)));if(o){let u=t.indexOf(`</${o}`,s);r=u===-1?e.length:Pd(e,u);continue}r=Pd(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function ey(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function wd(e,t,n){if(typeof e=="string")return rn(e,t,n);if(e&&typeof e=="object")return sn(e,t,n)}function rn(e,t,n=new WeakSet){let r=Sd(e);if(!r)return;if(t>=4)return r;let s=Le(r);if(s!==void 0)return typeof s=="string"?rn(s,t+1,n):s&&typeof s=="object"?sn(s,t+1,n):String(s);let o=Ad(r);if(o){let u=Le(o);if(u&&typeof u=="object"){let p=sn(u,t+1,n);if(p)return p}}if(r.includes("{")){let u=Xf(r);if(u)return rn(u,t+1,n)??u}return Jf(r)??r}function sn(e,t,n=new WeakSet){if(t>=4||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let u of e){let p=wd(u,t,n);if(p)return p}return}let r=e;for(let u of Vf){let p=wd(r[u],t,n);if(p)return p}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return ey(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function ne(e){return e?typeof e=="string"?rn(e,0)??Ns:typeof e=="object"?sn(e,0)??Ns:String(e):Ns}function Ad(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function ty(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 ny(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 kd(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,s=typeof e.upstream_status=="number"?e.upstream_status:void 0,o=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,u=ny(e.attempt_failures);return!t&&!n&&!r&&s===void 0&&!o&&!u?void 0:{message:typeof e.message=="string"&&e.message||ty(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:u}}function ie(e){if(e==null)return;if(typeof e=="string"){let u=Sd(e),p=Le(u)??Le(Ad(u));return p!==void 0?ie(p):void 0}if(typeof e!="object")return;let t=e,n=kd(t);if(n)return n;let r=t.error;if(r&&typeof r=="object"&&!Array.isArray(r)){let u=kd(r);if(u)return u}let s=t.data;if(s&&typeof s.responseBody=="string"){let u=Le(s.responseBody);if(u!==void 0){let p=ie(u);if(p)return p}}if(s&&typeof s.message=="string"){let u=ie(s.message);if(u)return u}let o=t.cause;if(o&&typeof o=="object"){let u=o.body;if(u!==void 0){let p=ie(u);if(p)return p}}}var ry={bash:{label:"Shell",category:"shell"},pty_spawn:{label:"Spawn Terminal",category:"shell"},pty_read:{label:"Terminal Output",category:"shell"},pty_write:{label:"Terminal Input",category:"shell"},pty_input:{label:"Terminal Input",category:"shell"},pty_kill:{label:"Kill Process",category:"shell"},read:{label:"Read File",category:"files"},list:{label:"List Directory",category:"files"},ls:{label:"List Directory",category:"files"},write:{label:"Write File",category:"edit"},edit:{label:"Edit File",category:"edit"},multiedit:{label:"Edit File",category:"edit"},morph_edit:{label:"Edit File",category:"edit"},apply_patch:{label:"Apply Patch",category:"edit"},patch:{label:"Apply Patch",category:"edit"},grep:{label:"Search Code",category:"search"},glob:{label:"Find Files",category:"search"},image_search:{label:"Image Search",category:"search"},session_search:{label:"Search Sessions",category:"search"},webfetch:{label:"Fetch Page",category:"web"},scrape_webpage:{label:"Scrape Page",category:"web"},websearch:{label:"Web Search",category:"web"},web_search:{label:"Web Search",category:"web"},image_gen:{label:"Generate Image",category:"web"},video_gen:{label:"Generate Video",category:"web"},task:{label:"Delegate to Agent",category:"task"},todowrite:{label:"Plan Tasks",category:"task"},todoread:{label:"Read Plan",category:"task"},question:{label:"Ask Question",category:"task"},presentation_gen:{label:"Presentation",category:"task"},show:{label:"Show Output",category:"task"},show_user:{label:"Show Output",category:"task"},prune:{label:"Prune Context",category:"other"},distill:{label:"Distill Context",category:"other"},compress:{label:"Compress Context",category:"other"},context_info:{label:"Context Info",category:"other"}},sy=[{prefix:"pty_",category:"shell"},{prefix:"agent_",category:"task"},{prefix:"session_",category:"task"},{prefix:"task_",category:"task"},{prefix:"trigger_",category:"task"},{prefix:"project_",category:"task"}];function iy(e){return e.replace(/^oc[-_]/,"")}function on(e){return iy(e).replace(/-/g,"_")}function Ks(e){return on(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function Hs(e){let t=on(e),n=ry[t];if(n)return n;for(let{prefix:r,category:s}of sy)if(t.startsWith(r))return{label:Ks(e),category:s};return{label:Ks(e),category:"other"}}var oy=256*1024;function ay(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function cy(e){if(e===void 0)return{};if(e.length>oy)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function ly(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,s=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!s))return s?ne(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}function uy(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=cy(r),u=ay(t),p=t.status==="error"?t.error:void 0;if(u==="done"){let d=ly(s);d&&(u="error",p=d)}return{name:e,title:n||Hs(e).label,status:u,input:t.input,output:r,outputParsed:s,outputText:o,error:p}}function py(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function dy(e){return{kind:"reasoning",id:e.id,text:e.text}}function gy(e){return{kind:"tool",id:e.id,tool:uy(e.tool,e.state)}}function my(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 fy(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function yy(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function hy(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function by(e){return{kind:"agent",id:e.id,name:e.name}}function xy(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:ne(e.error),createdAt:e.time.created}}function _y(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function Py(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function wy(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Cd(e){switch(e.type){case"text":return py(e);case"reasoning":return dy(e);case"tool":return gy(e);case"file":return my(e);case"subtask":return fy(e);case"patch":return yy(e);case"snapshot":return hy(e);case"agent":return by(e);case"retry":return xy(e);case"compaction":return _y(e);case"step-start":return Py(e);case"step-finish":return wy(e);default:return{kind:"unknown",raw:e}}}function ky(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=ie(e);return{name:t,message:n?.message||ne(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function Sy(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function vy(e){let t=e.parts.map(Cd),n=e.info.role==="assistant"?e.info.error:void 0,r=ky(n),s=!r&&!t.some(Sy);return{parts:t,error:r,isEmpty:s}}function ve(e){return e.type==="text"}function Ws(e){return e.type==="reasoning"}function fe(e){return e.type==="tool"}function Td(e){return e.type==="file"}function XA(e){return e.type==="agent"}function JA(e){return e.type==="compaction"}function QA(e){return e.type==="snapshot"}function YA(e){return e.type==="patch"}function ZA(e){if(ve(e)||Ws(e))return e.text}function eC(e){if(!Td(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function tC(e){let t=[],n=[];for(let r of e)Td(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function nC(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function rC(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var Ay=new Set(["todoread","context_info"]);function Cy(e){return!Ay.has(e.tool)}function sC(e){let t=e.tool||"";if(t==="task"||t==="agent_spawn"||t==="agent-spawn"||t==="agent_message"||t==="agent-message"||t==="agent_task"||t==="agent-task"||t==="agent_task_update"||t==="agent-task-update"||t==="agent_task_message"||t==="agent-task-message"||t==="agent_task_start"||t==="agent-task-start"||t==="task_create"||t==="task-create"||t==="task_start"||t==="task-start"||t==="task_update"||t==="task-update"||t==="task_message"||t==="task-message"){let r=e.state?.metadata?.sessionId;if(typeof r=="string"&&r)return r;let s=e.state?.title;if(s){let u=s.match(/\bses_[a-zA-Z0-9]+/);if(u)return u[0]}let o=e.state?.output;if(o){let u=o.match(/\bses_[a-zA-Z0-9]+/);if(u)return u[0]}return}let n=e.tool?.replace(/-/g,"_")||"";if(n==="session_spawn"||n==="session_start_background"){let r=e.state?.output;if(r){let s=r.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/);if(s)return s[1]}return}}function iC(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return ne(n.error)}}function oC(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)fe(r)&&Cy(r)&&t.push(r);return t}function aC(e,t={}){switch(e){case"read":return{icon:"glasses",title:"Read",subtitle:Ry(t.filePath)};case"list":return{icon:"list",title:"List",subtitle:Ty(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"webfetch":return{icon:"globe",title:"Web Fetch",subtitle:t.url};case"websearch":case"web-search":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:Iy(t)};case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":case"oc-session_spawn":case"oc-session-spawn":case"oc-session_start_background":case"oc-session-start-background":return{icon:"square-kanban",title:`Worker (${t.agent||"KortixWorker"})`,subtitle:t.description||t.prompt?.slice(0,60)};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":case"morph_edit":return{icon:"file-pen",title:"Edit",subtitle:Rd(t.filePath)};case"write":return{icon:"file-pen",title:"Write",subtitle:Rd(t.filePath)};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"todowrite":return{icon:"check-square",title:"Todos"};case"todoread":return{icon:"check-square",title:"Todos (read)"};case"question":return{icon:"message-circle",title:"Questions"};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":case"session-read":case"oc-session_read":case"oc-session-read":return{icon:"glasses",title:`Session Read (${t.mode||"summary"})`,subtitle:t.session_id?.slice(-12)};case"session_search":case"session-search":case"oc-session_search":case"oc-session-search":return{icon:"search",title:"Session Search",subtitle:t.query};case"session_message":case"session-message":case"oc-session_message":case"oc-session-message":return{icon:"message-circle",title:"Message \u2192 Session",subtitle:t.session_id?.slice(-12)};case"session_lineage":case"session-lineage":case"oc-session_lineage":case"oc-session-lineage":return{icon:"list-tree",title:"Session Lineage",subtitle:t.session_id?.slice(-12)};case"session_list_background":case"session-list-background":case"session_list_spawned":case"session-list-spawned":case"oc-session_list_background":case"oc-session-list-background":case"oc-session_list_spawned":case"oc-session-list-spawned":return{icon:"layers",title:"Background Sessions",subtitle:t.project||"all"};case"session_stats":case"session-stats":case"oc-session_stats":case"oc-session-stats":return{icon:"layers",title:"Session Stats",subtitle:t.session_id?.slice(-12)||"current"};case"session_list":case"session-list":case"oc-session_list":case"oc-session-list":return{icon:"list",title:"Session List",subtitle:t.search};case"session_get":case"session-get":case"oc-session_get":case"oc-session-get":return{icon:"book-open",title:"Session Get",subtitle:t.session_id?.slice(-12)};case"session_context":case"session-context":case"oc-session_context":case"oc-session-context":return{icon:"book-open",title:"Session Context",subtitle:t.session_id?.slice(-12)};case"project_delete":case"project-delete":case"oc-project_delete":case"oc-project-delete":return{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:t.project};case"project_list":case"project-list":case"oc-project_list":case"oc-project-list":return{icon:"folder",title:"Projects"};case"project_get":case"project-get":case"oc-project_get":case"oc-project-get":case"project_update":case"project-update":case"oc-project_update":case"oc-project-update":return{icon:"folder",title:"Project",subtitle:t.name||t.project};case"project_select":case"project-select":case"oc-project_select":case"oc-project-select":return{icon:"folder",title:"Project Select",subtitle:t.project};case"project_create":case"project-create":case"oc-project_create":case"oc-project-create":return{icon:"folder-plus",title:"Project Create",subtitle:t.name};case"triggers":case"trigger_create":case"trigger-create":case"oc-trigger_create":case"oc-trigger-create":return{icon:"clock",title:"Create Trigger",subtitle:t.name};case"trigger_list":case"trigger-list":case"oc-trigger_list":case"oc-trigger-list":return{icon:"clock",title:"List Triggers"};case"trigger_get":case"trigger-get":case"oc-trigger_get":case"oc-trigger-get":return{icon:"clock",title:"Trigger Details",subtitle:t.name||t.id};case"trigger_delete":case"trigger-delete":case"oc-trigger_delete":case"oc-trigger-delete":return{icon:"clock",title:"Delete Trigger",subtitle:t.name||t.id};case"trigger_update":case"trigger-update":case"oc-trigger_update":case"oc-trigger-update":return{icon:"clock",title:"Update Trigger",subtitle:t.name||t.id};case"trigger_test":case"trigger-test":case"oc-trigger_test":case"oc-trigger-test":return{icon:"clock",title:"Test Trigger",subtitle:t.name||t.id};case"trigger_pause":case"trigger-pause":case"oc-trigger_pause":case"oc-trigger-pause":return{icon:"clock",title:"Pause Trigger",subtitle:t.name||t.id};case"trigger_resume":case"trigger-resume":case"oc-trigger_resume":case"oc-trigger-resume":return{icon:"clock",title:"Resume Trigger",subtitle:t.name||t.id};case"agent_spawn":case"agent-spawn":return{icon:"cpu",title:`Agent (${t.agent_type||"worker"})`,subtitle:t.description};case"agent_message":case"agent-message":return{icon:"message-circle",title:"Agent Message",subtitle:t.agent_id};case"agent_stop":case"agent-stop":return{icon:"ban",title:"Agent Stop",subtitle:t.agent_id};case"agent_status":case"agent-status":return{icon:"layers",title:"Agent Status"};case"agent_task":case"agent-task":case"oc-agent_task":case"oc-agent-task":return{icon:"check-square",title:"Create Task",subtitle:t.title};case"agent_task_update":case"agent-task-update":case"oc-agent_task_update":case"oc-agent-task-update":return{icon:"check-square",title:"Update Task",subtitle:t.task_id};case"agent_task_list":case"agent-task-list":case"oc-agent_task_list":case"oc-agent-task-list":return{icon:"check-square",title:"List Tasks"};case"agent_task_get":case"agent-task-get":case"oc-agent_task_get":case"oc-agent-task-get":return{icon:"check-square",title:"Task Details",subtitle:t.task_id};case"task_create":case"task-create":return{icon:"plus",title:"Create Task",subtitle:t.title};case"task_list":case"task-list":return{icon:"list",title:"Tasks",subtitle:t.status||"all"};case"task_update":case"task-update":return{icon:"refresh-cw",title:"Update Task",subtitle:t.id};case"task_done":case"task-done":return{icon:"check-circle",title:"Task Done",subtitle:t.id};case"task_delete":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{icon:"cpu",title:e}}}function Ry(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Rd(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 Ty(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function cC(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 pt(e,t=120){if(typeof e!="string")return"";let n=e.split(`
72
+ `).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function Iy(e){let t=pt(e.description);if(t)return t;let n=pt(e.title,80);if(n)return n;let r=pt(e.message);if(r)return r;let s=pt(e.prompt);if(s)return s;let o=pt(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function lC(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function uC(e,t){return e.find(n=>n.tool?.callID===t)}function pC(e,t){return e.find(n=>n.tool?.callID===t)}var Ey=/\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 dC(e){return e?e.replace(Ey,""):""}var jy=/^msg_[0-9a-f]{12}/;function Id(e){return jy.test(e)?0:1}function Ed(e,t){return e<t?-1:e>t?1:0}function $y(e,t){let n=Id(e.info.id),r=Id(t.info.id);if(n!==r)return n-r;if(n===0)return Ed(e.info.id,t.info.id);let s=typeof e.info.time?.created=="number"?e.info.time.created:null,o=typeof t.info.time?.created=="number"?t.info.time.created:null;return s===null&&o===null?0:s===null?1:o===null?-1:s!==o?s<o?-1:1:Ed(e.info.id,t.info.id)}function fC(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((p,d)=>[p,d])),r=[...e].sort((p,d)=>{let f=n.get(p.info.id),m=n.get(d.info.id);return f!==void 0&&m!==void 0?f-m:f!==void 0?1:m!==void 0?-1:$y(p,d)}),s=[],o=new Map;for(let p of r)if(p.info.role==="user"){if(o.has(p.info.id))continue;let d={userMessage:p,assistantMessages:[]};s.push(d),o.set(p.info.id,d)}let u=null;for(let p of r){if(p.info.role==="user"){u=o.get(p.info.id)??null;continue}if(p.info.role!=="assistant")continue;let d=p.info,f=d.tokens;if(!d.error&&p.parts.length===0&&f?.input===0&&f.output===0&&f.reasoning===0)continue;if(d.parentID){let h=o.get(d.parentID);if(h){h.assistantMessages.push(p);continue}}if(u){u.assistantMessages.push(p);continue}if(s.length>0){s[0].assistantMessages.unshift(p);continue}let m={userMessage:p,assistantMessages:[]};s.push(m)}return s}function yC(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function hC(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(ve(n)&&n.text?.trim())return n}}function bC(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function xC(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!fe(o))continue;let u=o,p=u.state?.metadata?.answers;u.tool==="question"&&(p?.length??0)>0&&r.push({part:o,message:s})}return r}function _C(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 PC(e){let t=e-6e4;return(n,r)=>{let s=n.time.updated??n.time.created,o=r.time.updated??r.time.created,u=s>t,p=o>t;return u&&p?n.id<r.id?-1:n.id>r.id?1:0:u&&!p?-1:!u&&p?1:o-s}}function My(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let s of n)r.push(s),r.push(...My(e,s));return r}function Dy(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function kC(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&&Dy(n.error)}return!1}function Oy(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>ve(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return fe(s)&&s.tool==="bash"}function AC(e){if(Oy(e))return e.assistantMessages[0].parts[0]}function IC(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 EC(e,t){return!t||!e?!1:e.type!=="idle"}function jC(e,t){return!e&&!!t}function $C(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ne(n.error)}}function MC(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return ie(n.error)}}function jd(e){if(e){if(fe(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(Ws(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(ve(e))return"Gathering thoughts..."}}function DC(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n].part,s=fe(r)?r:void 0;if(s&&(s.tool==="task"||s.tool==="agent_task"||s.tool==="agent-task"||s.tool==="task_create"||s.tool==="task-create"||s.tool==="task_start"||s.tool==="task-start")&&s.state.status==="running"&&t&&t.length>0){for(let u=t.length-1;u>=0;u--){let p=t[u];if(p.info.role==="assistant")for(let d=p.parts.length-1;d>=0;d--){let f=jd(p.parts[d]);if(f)return f}}return"Handing off to an agent..."}let o=jd(r);if(o)return o}return"Figuring out what\u2019s next..."}function OC(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 $d=1.2;function Md(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),s=e.cache?.read??0,o=e.cache?.write??0,u=Math.max(0,n-s-o),d=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(m=>n>m.contextThreshold).sort((m,h)=>h.contextThreshold-m.contextThreshold)[0]??t,f=u/1e6*d.inputPer1M;return f+=r/1e6*d.outputPer1M,s>0&&(f+=s/1e6*(d.cacheReadPer1M??d.inputPer1M)),o>0&&(f+=o/1e6*(d.cacheWritePer1M??d.inputPer1M)),f}function zs(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function Dd(e,t,n,r){if(zs(t,n))return 0;let s=e.cost||0;if(s>0)return s;if(!r||!t||!n)return 0;let o=r(t,n);return o?Md(e.tokens,o):0}function Od(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function qC(e,t){let n=0,r=0,s=0,o=0,u=0,p=0,d=!1;for(let{part:f,message:m}of e)if(f.type==="step-finish"){d=!0;let h=f,{providerID:P,modelID:x}=Od(m.info);n+=Dd(h,P,x,t),r+=h.tokens?.input||0,s+=h.tokens?.output||0,o+=h.tokens?.reasoning||0,u+=h.tokens?.cache?.read||0,p+=h.tokens?.cache?.write||0}if(!d){let f=new Set;for(let{message:m}of e){if(m.info.role!=="assistant")continue;let h=m.info;if(f.has(h.id))continue;f.add(h.id);let P=qd(h,t),x=h.tokens&&zs(h.providerID,h.modelID);if(P<=0&&!x)continue;d=!0,n+=P;let _=h.tokens;_&&(r+=_.input??0,s+=_.output??0,o+=_.reasoning??0,u+=_.cache?.read??0,p+=_.cache?.write??0)}}if(d)return{cost:n*$d,tokens:{input:r,output:s,reasoning:o,cacheRead:u,cacheWrite:p}}}function qd(e,t){if(zs(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?Md({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function UC(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:u}=Od(s),p=0,d=!1;for(let f of r.parts)f.type==="step-finish"&&(d=!0,p+=Dd(f,o,u,t));d||(p+=qd(s,t)),n+=p}return n*$d}function FC(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function LC(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function BC(e){if(!e||e.type!=="retry")return;let t=e,n=ne(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:ie(t.message)}}function GC(e){if(!(!e||e.type!=="retry"))return ne(e.message)}function NC(e){return(e.info.summary?.diffs?.length??0)>0}var qy=4e3;function dt(e,t=qy){return e.length>t?`${e.slice(0,t)}
73
+ \u2026`:e}function Ud(e){if(e!==void 0)try{return dt(JSON.stringify(e,null,2))}catch{return}}function H(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function Be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function Uy(e){let t=H(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=Be(e.outputParsed);if(!n)return{kind:"web-search",query:t};let s=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(o=>{let u=Be(o)??{};return{title:H(u.title)??"",url:H(u.url,u.link)??"",snippet:H(u.snippet,u.description,u.source)}});return{kind:"web-search",query:H(n.query)??t,results:s.length>0?s:void 0,answer:H(n.answer)}}var Fy=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function Ld(e){let t=e.match(Fy);return t?Number(t[1]):void 0}function Ly(e,t,n){let r="",s=0;for(;;){let o=e.indexOf(t,s);if(o===-1)return r+e.slice(s);let u=e.indexOf(n,o+t.length);if(u===-1)return r+e.slice(s);r+=e.slice(s,o),s=u+n.length}}var By=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function Gy(e){let t=-1;for(let n of By){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}var Ny=/\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 Ky(e){return e.replace(Ny,"")}function Hy(e){let t=H(e.input?.command)??"",n=e.output??"",r=Ld(n),o=Ky(Gy(Ly(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:o||void 0,exitCode:r}}function Xs(e){return H(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function Wy(e){let t=e.status==="error"?e.error:e.output&&dt(e.output)||void 0;return{kind:"file-read",path:Xs(e),preview:t}}function zy(e){let t=H(e.input?.content),n=e.status==="error"?e.error:dt(t??e.output??"")||void 0;return{kind:"file-write",path:Xs(e),preview:n}}var Vy=256*1024;function Xy(e,t){if(e.length+t.length>Vy)return;let n=e.split(`
74
74
  `),r=t.split(`
75
- `),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,u=r.length;for(;o>s&&u>s&&n[o-1]===r[u-1];)o--,u--;let p=[];for(let d=0;d<s;d++)p.push({type:"unchanged",text:n[d]});for(let d=s;d<o;d++)p.push({type:"removed",text:n[d]});for(let d=s;d<u;d++)p.push({type:"added",text:r[d]});for(let d=o;d<n.length;d++)p.push({type:"unchanged",text:n[d]});return p}function Vy(e){let t=H(e.input?.oldString),n=H(e.input?.newString),r=t!==void 0&&n!==void 0?zy(t,n):void 0;return{kind:"file-edit",path:Xs(e),diff:r}}var Fd=/^Found\s+(\d+)\s+match/i,Xy=/^(\/[^:]+?):\s*/,qd=/Line\s+(\d+):/g;function Jy(e){let t=e.trim(),n=t.match(Fd),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let s=[];for(let o of r.split(/\n\n+/)){let u=o.trim();if(!u)continue;let p=u.match(Xy);if(!p)continue;let d=p[1],f=u.slice(p[0].length),m=[],h;for(qd.lastIndex=0;(h=qd.exec(f))!==null;)m.push({line:Number(h[1]),contentStart:h.index+h[0].length,headerStart:h.index});for(let P=0;P<m.length;P++){let x=P+1<m.length?m[P+1].headerStart:f.length,_=f.slice(m[P].contentStart,x).trim();s.push({path:d,line:m[P].line,content:_.endsWith(";")?_.slice(0,-1):_})}}return s}function Qy(e){return e.trim().split(`
76
- `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function Yy(e){let t=H(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=Fd.test(e.output.trim())?Jy(e.output):Qy(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function Zy(e){let t=H(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=H(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function Vs(e){let t=Be(e)??{};return{content:H(t.content)??"",status:H(t.status)??"pending",priority:H(t.priority)}}function eh(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(Vs)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(Vs)};let n=Be(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(Vs)}:{kind:"todo",items:[]}}function th(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=Be(r)??{},u=(Array.isArray(s.options)?s.options:[]).flatMap(p=>{let d=Be(p),f=d&&H(d.label);return f?[{label:f,description:d?H(d.description):void 0}]:[]});return{question:H(s.question)??"",header:H(s.header),options:u}})}}function nh(e){let n=e.input&&Object.keys(e.input).length>0?Od(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?pt(e.outputParsed):Od(e.outputParsed):e.outputText!==void 0?r=pt(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function rh(e){switch(sn(e.name)){case"web_search":case"websearch":case"image_search":return Oy(e);case"bash":return Ny(e);case"read":return Ky(e);case"write":return Hy(e);case"edit":case"morph_edit":return Vy(e);case"grep":case"glob":return Yy(e);case"task":return Zy(e);case"todowrite":return eh(e);case"question":case"ask":return th(e);default:return nh(e)}}var sh=new Set(["AbortError","MessageAbortedError"]),ih=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],oh=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function Ld(e){let t=e.toLowerCase();return oh.some(n=>t.includes(n))?!1:ih.some(n=>t.includes(n))}function ah(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 Bd(e){if(typeof e=="string")return Ld(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&sh.has(n))return!0;let r=ah(t);return typeof r=="string"?Ld(r):!1}var ch=["user","runtime-disposed","orphan-finalized","wake"],HC=["orphan-finalized","wake"];function WC(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 ch.includes(n)?n:void 0}function on(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function lh(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 QC(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 Js(e,t,n){return e!==void 0?e:lh(on(t),n)}var YC={get disableMobileAdvertising(){return Js(O().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Js(O().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Js(O().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var an="kortix-active-instance",uh=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function ph(e){return uh.some(t=>e===t||e.startsWith(`${t}/`))}function dt(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 eR(e){let t=dt(e);return!!t&&t.innerPath===""}function tR(e){let t=dt(e);return!t||!t.innerPath?e:t.innerPath}function dh(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=dt(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return ph(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function gh(e){return e?dt(e)?.instanceId??null:null}function nR(){return typeof window>"u"?null:gh(window.location.pathname)||mh()}function mh(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${an}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function rR(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${an}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${an}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${an}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function sR(e,t){return t?dh(t,e):e}function iR(e){let t=dt(e);return t?t.innerPath||"/dashboard":e}function Qs(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 fh(e){let t=Qs(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}function Gd(e){let t=fh(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}function aR(e){return Gd(e)!==null}var yh=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/];function ln(e){let t=Qs(e);return t?yh.some(n=>n.test(t)):!1}var cn=class extends Error{constructor(t){let n=t?.trim();super(n&&ln(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function hh(e){let t=Gd(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,u=t.data?.issues?.[0]?.path?.join("."),p=u?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${p}`,detail:o?`${u?`${u}: `:""}${o}`:void 0}}let n=Qs(e);return ln(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:"OpenCode failed to load",message:n||"The sandbox is running, but OpenCode returned an error."}}function Y(){let e=on("BACKEND_URL")||O().backendUrl;return e||"http://localhost:8008/v1"}function gt(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=gt(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return gt(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}var Nd=["http://localhost:8008/v1","http://127.0.0.1:8008/v1"];function Kd(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return`${e.slice(0,t)}/platform/local-bridge/status`}function bh(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 Ys(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?`${Y()}/p/${n.external_id}/${ge.KORTIX_MASTER}`:""),status:bh(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 Zs(){let e=await qe(),t=[];for(let n of e){let r=await it(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Ys(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Ae(e){let t=await Zs();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}async function un(e,t={}){let n={"Content-Type":"application/json",...t.headers},r=t.signal??AbortSignal.timeout(3e4),s=await U(`${Y()}${e}`,{...t,headers:n,signal:r}),o=await s.text().catch(()=>{}),u;if(o)try{u=JSON.parse(o)}catch{}if(!s.ok){let p=u?.error||u?.message||u?.detail||o||`Platform API error ${s.status}`,d=new S(p,{status:s.status,code:u?.code||u?.error_code||String(s.status),details:u??(o?{rawText:o}:void 0),response:s,endpoint:e});throw s.status===402&&(d=Ee(Object.assign(d,{response:s,status:s.status,data:u}))),d}return u}function Hd(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`${Y()}/p/${e.external_id}/${ge.KORTIX_MASTER}`}function bR(e,t){return e.external_id?`${Y()}/p/${e.external_id}/${t}`:null}async function SR(){let e=await i.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function xh(e){let t=await Ae();if(t)return{sandbox:t.sandbox,created:!1};let r=(await qe())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await ot(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await Ue(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Ys(r,s,o),created:!0}}async function vR(){return(await Ae().catch(()=>null))?.sandbox??null}async function AR(e){return{sandbox:(await xh(e)).sandbox}}async function CR(e){let t=gt(e);return t?(await Ae(t).catch(()=>null))?.sandbox??null:null}async function RR(e,t){throw await Ae(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function TR(e){let t=gt(e);return(await Zs().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function IR(){if(typeof window>"u")return null;let e=Y(),t=Array.from(new Set([e,...Nd]));for(let n of t)try{let r=await fetch(Kd(n),{method:"GET",signal:AbortSignal.timeout(1500),headers:{Accept:"application/json"}});if(!r.ok)continue;let s=await r.json();if(!s.success||s.status!=="ready"||!s.data?.sandbox_id)continue;return s.data}catch{continue}return null}async function ER(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Ae(e);if(!t)throw new Error("Project session sandbox not found");await Wt(t.project.project_id,t.session.session_id)}async function jR(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Ae(e);if(!t)throw new Error("Project session sandbox not found");await zt(t.project.project_id,t.session.session_id)}async function $R(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function MR(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function ei(e,t,n){let r=Hd(e),s=await U(`${ue(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function FR(e,t){return ei(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function LR(e,t,n,r="member"){await ei(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function BR(e,t,n){await ei(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}async function KR(e){let t=await un(`/platform/invites/${encodeURIComponent(e)}`,{method:"GET"});if(!t.success||!t.data)throw new Error(t.error||"Invite not found");return t.data}async function HR(e){let t=await un(`/platform/invites/${encodeURIComponent(e)}/accept`,{method:"POST"});if(!t.success||!t.data)throw new Error(t.error||"Failed to accept invite");return t.data}async function WR(e){let t=await un(`/platform/invites/${encodeURIComponent(e)}/decline`,{method:"POST"});if(!t.success)throw new Error(t.error||"Failed to decline invite")}async function VR(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function XR(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function JR(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function QR(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function ZR(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function eT(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var _h=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function rT(e){return _h.includes(e)}async function sT(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 iT(e){let t=e?`?channel=${e}`:"",n=await fetch(`${Y()}/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 s=await Ph(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function Ph(e){let t=e?`?channel=${e}`:"",n=await fetch(`${Y()}/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 oT(){let e=await fetch(`${Y()}/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 aT(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function cT(e){}async function lT(e){}async function gT(e){return{serverTypes:[],location:e||"hel1"}}async function mT(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function fT(e){let t=await i.delete(`/platform/sandbox?sandbox_id=${e}`);if(t.error)throw t.error;return t.data}async function yT(e,t){await i.post("/platform/sandbox/mark-error",{sandbox_id:e,error_message:t},{showErrors:!1,timeout:1e4})}async function hT(){let e=await i.post("/platform/sandbox/claim-computer",{},{timeout:6e4});if(e.error)throw e.error;return e.data}async function bT(e){let t=await i.get(`/platform/sandbox/${e}/status`,{showErrors:!1,timeout:1e4});return t.success?t.data??null:null}function xT(e,t){return`${Y()}/platform/sandbox/${e}/provision-stream?token=${encodeURIComponent(t)}`}var ye=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function pn(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return/\/v1$/.test(t)?t:`${t}/v1`}function ti(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 dn(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function gn(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function z(e,t,n){let r=n?.body!==void 0,s=await fetch(`${pn(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:ti(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await dn(s);if(!s.ok)throw new ye(gn(s,o),s.status,o);return o}function kh(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 PT(e,t){return z(`/marketplace/items${kh(t)}`,e)}function kT(e){return z("/marketplace/marketplaces",e)}function wT(e,t){return z(`/marketplace/items/${encodeURIComponent(e)}`,t)}function ST(e,t,n){return z(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function vT(e,t){return z("/access/check-email",t,{method:"POST",body:{email:e}})}function AT(e,t){return z("/access/request-access",t,{method:"POST",body:e})}function CT(e){return z("/auth/logout",e,{method:"POST",body:{}})}function RT(e,t){return z(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function TT(e,t){return z("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function IT(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function ET(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function jT(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:{}})}function $T(e,t){return z(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function MT(e,t,n){return z(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t}})}function DT(e,t){return z(`/p/public-share/${encodeURIComponent(e)}`,t)}function OT(e,t,n){return z(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function qT(e){return z("/system/maintenance",e)}function UT(e,t){return z("/system/maintenance",t,{method:"PUT",body:e})}function FT(e){return z("/user-roles",e)}function LT(e,t){return z("/system/demo-request",t,{method:"POST",body:e})}async function BT(e,t,n){let r=new URLSearchParams({format:t.format});t.action&&r.set("action",t.action),t.actor&&r.set("actor",t.actor),t.project_id&&r.set("project_id",t.project_id),t.session_id&&r.set("session_id",t.session_id),t.actor_type&&r.set("actor_type",t.actor_type),t.source&&r.set("source",t.source),t.phase&&r.set("phase",t.phase),t.outcome&&r.set("outcome",t.outcome),t.request_id&&r.set("request_id",t.request_id),t.correlation_id&&r.set("correlation_id",t.correlation_id),t.resource_type&&r.set("resource_type",t.resource_type),t.since&&r.set("since",t.since),t.until&&r.set("until",t.until),t.q&&r.set("q",t.q),t.cursor&&r.set("cursor",t.cursor),t.limit!=null&&r.set("limit",String(t.limit));let s=await fetch(`${pn(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${r}`,{headers:ti(n,!1),...n.signal?{signal:n.signal}:{}});if(!s.ok){let o=await dn(s);throw new ye(gn(s,o),s.status,o)}return{blob:await s.blob(),filename:s.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:s.headers.get("x-audit-capped")==="true",rowCount:s.headers.get("x-audit-row-count"),complete:s.headers.get("x-audit-complete")!=="false",nextCursor:s.headers.get("x-audit-next-cursor")||null}}async function GT(e,t){let n=await fetch(`${pn(t.backendUrl)}/admin/stress-test/run`,{method:"POST",headers:ti(t,!0),body:JSON.stringify(e),...t.signal?{signal:t.signal}:{}});if(!n.ok){let r=await dn(n);throw new ye(gn(n,r),n.status,r)}if(!n.body)throw new ye("No response body",n.status,null);return n.body}var wh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Sh(e,t){return wh.test(t)?new URL(`templates/public/${t.toLowerCase()}`,`${pn(e)}/`):null}async function NT(e,t,n){let r=Sh(e,t);if(!r)throw new ye("Invalid shareId parameter",400,null);let s=await fetch(r,{signal:n}),o=await dn(s);if(!s.ok)throw new ye(gn(s,o),s.status,o);return o}async function WT(){let e=await i.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 zT(e={}){let t=await i.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 VT(e){let t=await i.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 XT(e){let t=await i.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 JT(){let e=await i.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 vh="/kortix/part/";function Ah(e){return typeof e=="string"&&e.startsWith(vh)}async function eI(e){if(!Ah(e))throw new Error(`not an attachment part reference: ${e}`);let t=re();if(!t)throw new Error("runtime url not bound");let n=await U(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function Wd(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 Ch(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.size===0||o.has(n.origin)}catch{return!1}}function zd(e,t){return Ch(e,t)?(t?Wd(t):null)??Wd(e):null}function Vd(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 Xd(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}async function Rh(e,t={}){let n=zd(e,t.serverUrl);if(!n)return!1;let r=await We();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 iI(e,t={}){if(Vd(e)){let n=await We();return n?Xd(e,n):e}return await Rh(e,t),e}var aI=3e3;function Th(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 cI(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return Th(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function ni(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function uI(e,t){return`${ni(e)}/presentation-templates/${encodeURIComponent(t)}/pdf#toolbar=0&navpanes=0&scrollbar=0&view=FitH`}function pI(e,t){return`${ni(e)}/presentation-templates/${encodeURIComponent(t)}/image.png`}function Ih(e,t){return`${ni(e)}/presentation/convert-to-${t}`}async function dI(e,t,n,r){let s=Ih(t,e),o=r?.pollIntervalMs??2500,u=r?.timeoutMs??4*6e4,p=Date.now(),d=!1;for(;;){let f=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),m=f.headers.get("content-type")||"";if(f.ok&&(m.includes("pdf")||m.includes("presentation")||m.includes("octet-stream"))){let _=await f.blob();if(_.size===0)throw new Error("Downloaded file is empty");return _}if(f.status===202){if(d||(d=!0,r?.onGenerating?.()),Date.now()-p>u)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((_,v)=>{let M=setTimeout(_,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(M),v(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let P=await f.text().catch(()=>""),x=f.statusText;try{let _=JSON.parse(P);x=String(_.error||_.detail||_.message||x)}catch{P&&(x=P)}throw new Error(`Failed to download ${e.toUpperCase()}: ${x} (HTTP ${f.status})`)}}function mI(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 fI(e){return e==="unreachable"}var hI=6e4,bI=45e3,xI=45e3,_I=1e4,PI=3e3,kI=15e3;function wI(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function SI(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 ri(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function vI(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:u,nowMs:p}=e,d=!!t&&p-t.atMs<6e4,f=t?t.turnId===void 0?t.messageId:t.turnId:null,m=d?t.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,h=d?t.atMs:Number.NEGATIVE_INFINITY,P=!!n&&p-n.atMs<15e3,x=P?n.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,_=!!s&&p-s.atMs<=45e3,v=!!o&&p-o.atMs<=45e3,M=!!r&&p-r.atMs<=1e4,$=o&&o.type==="idle"&&o.origin!=="local"?o:null,y=!!u&&p-u.atMs<=45e3&&(!$||u.atMs>$.atMs),a=q=>{if(!$)return!1;let N=ri(q.started_at);return!(N===null||N>=$.atMs)};if(y&&u.atMs>=x)return{state:"working",source:"stream",turnId:_?s.turns.find(q=>q.state==="active"&&!a(q))?.message_id??null:null,since:u.atMs,serverOpenTurnToken:s?.turns[0]?.turn_token??null};let I=s?.turns[0]?.turn_token??null,R=_?s.turns.filter(q=>!a(q)):[],k=R.find(q=>q.state==="active")??R[0],F=!!o&&!(o.type==="idle"&&o.origin==="local");if(k&&s.atMs>=x&&(!F||s.atMs>=o.atMs))return{...k.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:k.message_id,since:ri(k.started_at)??s.atMs,serverOpenTurnToken:I};if(M&&r.pending>0&&r.atMs>=x)return{...v&&o.type!=="idle"&&(!_||o.atMs>s.atMs)&&o.atMs>=x?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?f:null,since:r.atMs,serverOpenTurnToken:I};let j=r?.drainedAtMs;if(M&&r.pending===0&&j!=null&&!P&&!(_&&s.atMs>=j))return{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:j,serverOpenTurnToken:I};let D=_&&!k&&s.atMs>=m,b=v&&o.atMs>=h&&(o.type==="idle"||o.atMs>=x);if(D&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:ri(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:I};if(b)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:I};if(d)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:f,since:t.atMs,serverOpenTurnToken:I};let T=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:p};return{state:"idle",source:T.source,turnId:null,since:T.atMs,serverOpenTurnToken:I}}function AI(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:u,nowMs:p}=e,d=[null,t?t.atMs+6e4:null,n?n.atMs+15e3:null,r?r.atMs+1e4:null,s?s.atMs+45e3:null,o?o.atMs+45e3:null,u?u.atMs+45e3:null],f=null;for(let m of d)m===null||m<=p||(f===null||m<f)&&(f=m);return f}var RI=6e4;function TI(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function II(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var Eh=9e4;function EI(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+Eh}var $I=75e3,MI=2,DI=2e4;function Jd(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function OI(e){return e.filter(t=>t!=null).join("|")}function jh(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function qI(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Jd(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Jd(),settled:!0};let u=e.lastProgressAtMs,p=u===null,d=t.progress!==e.fingerprint,f=u===null||d?t.nowMs:u,m=Math.max(0,t.nowMs-f),h={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:f,msSinceProgress:m,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...h,status:"exhausted"};let P=!p&&!d&&m>=r;if(!t.serverGaveUp&&!P||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return h;let x=jh(e.attempts,s);return x?{...h,status:"escalating",dispatch:x,attempts:[...e.attempts,{step:x,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...h,status:"exhausted"}}var $h={"retry-start":"retrying",restart:"restarting"};function UI(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${$h[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function Mh(e){return e===1?"once":e===2?"twice":`${e} times`}function FI(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(s=>s.step==="restart").length,n=e.attempts.some(s=>s.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${Mh(t)}`),`Tried: ${r.join(", then ")}.`}var Dh=1e3,Oh=15e3,Qd=100,qh=50,Uh=10;function Yd(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let u=new URLSearchParams({limit:String(r)});s&&u.set("before",s);let p=await e.getToken?.(),d=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${u}`,{headers:p?{Authorization:`Bearer ${p}`}:void 0,...o?{signal:o}:{}});if(!d.ok)throw d.status===503?new cn(`session ${d.status}`):new S(`Session synchronization failed: ${d.status}`,{status:d.status});return{messages:await d.json(),nextCursor:d.headers.get("x-next-cursor")||void 0}}}function Fh(e){return Bh(Yd(e))}function Lh(e){return new si({...e,loadPage:Yd(e)})}async function Bh(e){let t=[],n=new Set,r;do{let u=await e({limit:Qd,...r?{before:r}:{}});if(t.push(u.messages),r=u.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let u=t.length-1;u>=0;u--)for(let p of t[u])o.has(p.info.id)||(o.add(p.info.id),s.push(p));return s}var Gh={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},si=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;olderRequest;livenessTimer;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??Gh,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,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){if(!t){let n=this.livenessTimer!==void 0;this.stopLivenessTimer(),n&&!this.destroyed&&this.reconcile("turn-end");return}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()}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||Bd(n)||this.abortController.signal.aborted)return;if(this.update({freshness:ln(n)?"loading":"error"}),n instanceof S&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(Dh*2**this.retryAttempt,Oh);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.options.loadPage({limit:t==="tail"?qh:Qd,...r?{before:r}:{}},this.abortController.signal);return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let u=[...t.messages],p=new Set(this.knownUserMessageIds),d=new Set(s?[s]:[]),f=t.nextCursor,m=0;for(let h of t.messages)h.info.role==="user"&&p.add(h.info.id);for(;f&&m<Uh&&u.some(h=>h.info.role==="assistant"&&!!h.info.parentID&&!p.has(h.info.parentID));){if(d.has(f))throw new Error(`Session history cursor repeated: ${f}`);d.add(f);let h;try{h=await this.loadPage(n,r,f)}catch(P){throw o?.({messages:[...u],nextCursor:f}),P}if(this.destroyed)return{messages:u,nextCursor:f};m+=1,u.unshift(...h.messages);for(let P of h.messages)P.info.role==="user"&&p.add(P.info.id);f=h.nextCursor,o?.({messages:[...u],nextCursor:f})}return{messages:u,nextCursor:f}}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;!n&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,u=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(u,n),t.then(u,u)})}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 Nh(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return`${t}/tunnel/permission-requests/stream`}function Kh(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:u,onError:p,signal:d}=e,f=new Map,m=null,h=!1;function P($,l){o?.($,l);let y=f.get($);if(y)for(let a of y)try{a(l)}catch{}}async function x(){if(h)return;m=new AbortController;let $=d?AbortSignal.any([m.signal,d]):m.signal;try{let l={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(l["Content-Type"]="application/json");let y=await fetch(t,{method:r,headers:l,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:$,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");u?.();let a=y.body.getReader(),A=new TextDecoder,I="",R="message",k="";for(;!h;){let{done:F,value:j}=await a.read();if(F)break;I+=A.decode(j,{stream:!0});let K=I.split(`
77
- `);I=K.pop()||"";for(let D of K)D===""?k&&(P(R,k.trimEnd()),R="message",k=""):D.startsWith("event: ")?R=D.slice(7).trim():D.startsWith("data: ")?k+=(k?`
78
- `:"")+D.slice(6):D.startsWith("data:")&&(k+=(k?`
79
- `:"")+D.slice(5))}}catch(l){if(h||l instanceof DOMException&&l.name==="AbortError")return;p?.(l instanceof Error?l:new Error(String(l)))}}function _(){h=!0,m?.abort(),m=null,f.clear()}function v($,l){let y=f.get($)??new Set;y.add(l),f.set($,y)}function M($,l){f.get($)?.delete(l)}return{connect:x,close:_,addEventListener:v,removeEventListener:M}}function HI(e,t){return Kh({...t,url:Nh(e)})}var Hh="/_kortix/viewer";var mn=new Map;function Wh(){mn.clear()}async function zh(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 Zd(e={}){let t=e.path??Hh,n=e.fetch??((o,u)=>fetch(o,u)),r=mn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=zh(t,n).then(o=>{let u=o?.expires_at?Date.parse(o.expires_at):Number.NaN,p=Number.isFinite(u)?u-6e4:Date.now()+6e4;return mn.set(t,{session:o,expiresAt:p}),o});return mn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function Vh(e={}){return async()=>(await Zd(e))?.access_token??null}export{ch as ABORT_REASONS,HC as ABORT_REASONS_NOT_YET_EMITTED,an as ACTIVE_INSTANCE_COOKIE,vh as ATTACHMENT_PART_REF_PREFIX,S as ApiError,Te as AuthError,be as BillingError,Ed as COST_MARKUP,bd as DEFAULT_TRANSCRIPT_OPTIONS,_h as DESTRUCTIVE_PHASES,Fr as FEATURE_DISABLED_CODE,dP as FEATURE_FLAG_KEYS,Rg as FEATURE_NOT_SUPPORTED_CODE,at as HeadlessAuthError,ye as HostBoundaryError,kg as IMPERSONATION_HEADER,_I as INBOX_OBSERVATION_MAX_MS,uh as INSTANCE_SCOPED_ROUTES,im as MAX_PROMPT_ATTACHMENTS_BYTES,Zr as MAX_PROMPT_ATTACHMENT_BYTES,Ji as MAX_PROMPT_ATTACHMENT_FILES,Tg as MODEL_NOT_SERVABLE_CODE,kI as OPTIMISTIC_ABORT_MAX_MS,RI as OPTIMISTIC_COMPACTION_MAX_MS,hI as OPTIMISTIC_RECEIPT_MAX_MS,aI as PREVIEW_PROBE_TIMEOUT_MS,$k as PROJECT_SESSION_NAME_LOOKUP_LIMIT,jk as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,Cm as PROJECT_SESSION_PAGE_MAX_LIMIT,Ig as PROVISION_IN_FLIGHT_CODE,ws as PublicSessionShareError,Ie as RequestTooLargeError,Xe as RuntimeNotReadyError,Qr as SANDBOX_FS_ROOTS,ge as SANDBOX_PORTS,Eh as SERVER_COMPACTION_REVALIDATE_MS,bI as SERVER_OBSERVATION_MAX_MS,xI as STREAM_OBSERVATION_MAX_MS,cn as SandboxNotReadyError,tn as SessionNotReadyError,hs as SessionStartError,PI as TURN_END_LEDGER_LAG_MS,DI as WAKE_ESCALATION_COOLDOWN_MS,MI as WAKE_MAX_RESTARTS,$I as WAKE_NO_PROGRESS_MS,Jh as __getConfigResolver,Xh as __setConfigResolver,WC as abortErrorReason,Po as acceptAccountInvite,HR as acceptInvite,gp as actReviewItem,za as activateConnection,Bu as addGroupMembers,Bp as addMarketplaceSource,qI as advanceWakeEscalation,jy as allDescendantIds,Xd as appendPreviewToken,Qo as approveProjectAccessRequest,jx as approveTask,as as archiveProject,Lx as assignTicket,aa as attachGroupToProject,Fs as authMfa,Os as authUser,U as authenticatedFetch,iI as authorizePreviewUrl,i as backendApi,Tw as bindSlackIdentity,Iw as bindTeamsIdentity,xa as brokerProjectSecretRequest,dh as buildInstancePath,pI as buildPresentationTemplateImageUrl,uI as buildPresentationTemplatePdfUrl,zd as buildPreviewAuthEndpoint,Sh as buildPublicTemplateUrl,Ih as buildRuntimePresentationConversionUrl,vc as buildSandboxTemplate,oA as buildStaticFileHealthPreviewUrl,iA as buildStaticFileLocalUrl,sA as buildStaticFilePreviewUrl,sf as buildStaticFileServicePath,Nh as buildTunnelEventStreamUrl,pA as buildWebProxyUrl,mp as bulkActReviewItems,nS as bulkDeletePolicies,rS as bulkImportPolicies,Fa as callConnector,zS as cancelAccountDeletion,bo as cancelAccountInvite,$R as cancelSandbox,lT as cancelSandboxUpdate,Jl as cancelScheduledChange,zl as cancelSubscription,vT as checkAccessEmail,bC as childMapByParent,hT as claimComputer,jf as claimNext,yw as claimPerSeatBilling,nl as claimWarmProjectSession,vd as classifyPart,Th as classifyPreviewProbeStatus,wy as classifyTurn,Ti as clearImpersonationSession,Wh as clearKortixAppViewerCache,jl as clearModelDefault,Ck as clearSessionFresh,Nc as closeChangeRequest,m_ as closeMilestone,mC as collectTurnParts,Gx as commentTicket,Wc as commitSessionChanges,II as compactionExpiryAtMs,Ey as compareMessagesForDisplay,$f as completeInFlight,Id as computeStatusFromPart,eu as configureAutoTopup,yn as configureKortix,Hl as confirmCheckoutSession,mu as connectEmail,ou as connectSlack,fI as connectionIsFaulted,vm as connectorConnect,Am as connectorFinalize,uv as convertPresentationToGoogleSlides,dI as convertRuntimePresentation,Ut as copyFile,nu as costExportUrl,SI as countLiveInboxPrompts,oo as createAccount,Ip as createAccountAuditWebhook,Ta as createAccountSecretResource,Pp as createAccountToken,Kp as createApp,Jp as createAppAccessSession,Yp as createAppDeployment,ap as createAssignment,IS as createAuditWebhook,XR as createBackup,Kl as createCheckoutSession,ac as createConnector,qt as createFile,ju as createGatewayKey,qu as createGroup,Lh as createHttpSessionSyncController,mT as createInstance,Rf as createKortix,Ui as createKortixPty,Bs as createKortixSession,Mv as createMarketplaceInstallSession,d_ as createMilestone,tp as createOAuthClient,fw as createPerSeatCheckout,Zw as createPolicy,Wl as createPortalSession,jo as createProject,Yx as createProjectAgent,Sp as createProjectCliToken,$o as createProjectRepo,pa as createProjectResourceGrant,ot as createProjectSession,Pl as createProjectTrigger,so as createPromptAttachmentController,zu as createRole,Kh as createSSEStream,AR as createSandbox,yp as createSandboxShare,kc as createSandboxTemplate,aS as createScimToken,AS as createServiceAccountApi,al as createSessionPrompt,Zc as createSessionPublicShare,If as createSessionQueue,hS as createSsoGroupMapping,Tx as createTask,qx as createTicket,HI as createTunnelEventStream,ko as declineAccountInvite,WR as declineInvite,VS as deleteAccountImmediately,Ea as deleteAccountSecretResource,zp as deleteApp,jS as deleteAuditWebhook,QR as deleteBackup,lc as deleteConnector,P_ as deleteCredential,Oi as deleteEnv,we as deleteFile,Iu as deleteGatewayBudget,zo as deleteGitHubInstallation,Fu as deleteGroup,fT as deleteInstance,a_ as deleteKortixProject,y_ as deleteMilestone,sp as deleteOAuthClient,Aa as deletePersonalProjectSecret,tS as deletePolicy,e_ as deleteProjectAgent,ka as deleteProjectProviderOAuth,da as deleteProjectResourceGrant,Sa as deleteProjectSecret,gl as deleteProjectSession,wl as deleteProjectTrigger,Oe as deletePromptAttachment,Ju as deleteRole,Sc as deleteSandboxTemplate,RS as deleteServiceAccountApi,ll as deleteSessionPrompt,bS as deleteSsoGroupMapping,fS as deleteSsoProvider,$x as deleteTask,Nx as deleteTicket,_o as describeAccountInvite,Ua as describeConnectorTool,la as detachGroupFromProject,ef as detectLocalhostUrls,CS as disableServiceAccountApi,fu as disconnectEmail,JT as disconnectGitHubApp,lu as disconnectSlack,VP as discoverConnectionOAuth2,XP as discoverConnectionOAuth2Resource,cc as discoverConnectorAuth,IR as discoverLocalSandbox,BT as downloadAccountAudit,M_ as dropClientForUrl,q_ as dropPublicClientForUrl,qf as editQueued,Ef as enqueue,Jx as ensurePmSession,Rh as ensurePreviewSessionCookie,HP as ensureProjectConnectorConnection,xh as ensureSandbox,tl as ensureWarmProjectSession,Ug as env,$s as exchangeCode,Rp as exportAccountAudit,ie as extractGatewayErrorDetails,dt as extractInstanceRoute,Mf as failInFlight,vi as featureDisabledKey,YC as featureFlags,gw as fetchAccountStateWithToken,cP as fetchAccountsWithToken,eI as fetchAttachmentPart,vw as fetchCostExportCsv,Zd as fetchKortixAppViewer,Ic as fetchProjectArchive,_P as fetchProjectsForAccountWithToken,rm as files,vs as finalizeAppArtifact,jT as finalizeConnectorSetupLink,Dt as findFiles,fC as findLastTextPart,Ot as findText,vl as fireProjectTrigger,Pc as fixSandboxWithAgent,Ci as formatBillingErrorForUI,qC as formatCost,MC as formatDuration,hh as formatOpenCodeRuntimeError,hh as formatRuntimeError,UC as formatTokens,Kf as formatTranscript,Tf as generateSessionId,ao as getAccount,lo as getAccountBranding,HS as getAccountDeletionStatus,ql as getAccountState,Ul as getAccountStateMinimal,mh as getActiveInstanceIdFromCookie,nv as getAdminProviderAnalytics,ZS as getAdminProviderDistribution,sv as getAdminProviderFallback,XS as getAdminRole,Ry as getAgentCardLabel,ow as getAgentConfig,t_ as getAgentPersona,oT as getAllVersions,hC as getAnsweredQuestionParts,Hp as getApp,Vp as getAppAccess,ed as getAppDeployment,td as getAppDeploymentLogs,Iv as getApprovalLink,We as getAuthToken,bi as getAuthTokenWithRetry,Zl as getAutoTopupSettings,mw as getAutoTopupSetupStatus,Bl as getBillingCreditBreakdown,Nl as getBillingTierConfigurations,Ll as getBillingTransactionsSummary,Gl as getBillingUsageHistory,Uc as getChangeRequest,Fc as getChangeRequestDiff,Lc as getChangeRequestMergePreview,rC as getChildSessionError,nC as getChildSessionId,sC as getChildSessionToolParts,Pe as getClient,pe as getClientForUrl,gc as getConnectStatus,zP as getConnectionOAuth2Application,ek as getConnectionOAuth2Status,tk as getConnectionPolicies,us as getConnectorCatalog,sc as getConnectorConfig,nc as getConnectorPolicies,IT as getConnectorSetupLink,Sw as getCostSummary,gh as getCurrentInstanceIdFromPathname,nR as getCurrentInstanceIdFromWindow,Vi as getCurrentProject,xs as getDefaultAccountState,aC as getDiagnostics,Cy as getDirectory,ds as getDiscoverConnector,ak as getDiscoverIntegration,du as getEmailInstallation,gu as getEmailMode,MS as getEnterpriseDemo,Mt as getFileStatus,Ad as getFileWithDir,Ay as getFilename,Ph as getFullChangelog,vu as getGatewayBreakdown,Ru as getGatewayBudgets,Cu as getGatewayErrors,Eu as getGatewayKeys,ku as getGatewayLog,wu as getGatewayOverview,hu as getGatewayRoutingPolicy,Su as getGatewaySeries,Au as getGatewaySessions,WT as getGitHubAppStatus,Lo as getGitHubInstallation,lv as getGoogleAuthUrl,Ou as getGroup,eC as getHiddenToolParts,vg as getImpersonationSession,KR as getInvite,gT as getJustavpsServerTypes,s_ as getKortixProject,i_ as getKortixProjectBySession,Bi as getKortixPtyWebSocketUrl,iT as getLatestSandboxVersion,qT as getMaintenanceConfig,Vo as getManagedGitBackend,yP as getManagedGitStatus,Up as getMarketplaceCatalogItem,Fp as getMarketplaceCatalogItemFile,lS as getMfaRequired,u_ as getMilestone,Il as getModelDefaults,ep as getOAuthClient,RT as getOAuthConsentRequest,Gd as getOpenCodeConfigInvalidError,QA as getPartText,wS as getPatPolicy,cC as getPermissionForTool,ns as getProject,n_ as getProjectActivity,$c as getProjectCommit,Mc as getProjectCommitDiff,rs as getProjectDetail,Dc as getProjectFileHistory,Eo as getProjectGitToken,ss as getProjectLlmCatalog,mP as getProjectLlmCatalogProviders,As as getProjectModelAccess,is as getProjectModelPicker,gs as getProjectSandboxHealth,hP as getProjectSandboxProviderTransition,fs as getProjectSession,ml as getProjectSessionConfigState,hl as getProjectSessionScope,Ql as getProrationPreview,SR as getProviders,aA as getProxyBaseUrl,O_ as getPublicClientForUrl,wT as getPublicMarketplaceItem,ST as getPublicMarketplaceItemFile,xv as getPublicSessionShare,_v as getPublicSessionShareMessages,DT as getPublicShareByToken,NT as getPublicTemplate,lC as getQuestionForTool,Lw as getReferralCode,Nw as getReferralStats,FC as getRetryInfo,LC as getRetryMessage,pp as getReviewItem,Hu as getRolePermissions,Wu as getRoleUsage,eT as getSSHConnection,vR as getSandbox,CR as getSandboxById,bR as getSandboxPortUrl,bT as getSandboxProvisionStatus,xT as getSandboxProvisionStreamUrl,sT as getSandboxUpdateStatus,Hd as getSandboxUrl,$T as getSecretSetupLink,Yr as getServerHealth,S_ as getServiceLogs,rl as getSessionAudit,OC as getSessionCost,Ps as getSessionCostRecord,od as getSessionHealth,Mk as getSessionOpenBundle,xS as getSessionPolicy,Qc as getSessionPreviewCandidates,Ma as getSessionProviderSecretPool,sl as getSessionTranscript,il as getSessionTranscriptSync,ol as getSessionTurn,SC as getShellModePart,uu as getSlackChannelFile,iu as getSlackInstallation,cu as getSlackManifest,au as getSlackMode,dS as getSsoProvider,of as getStaticFileHealthPath,Ur as getSupabaseAccessToken,ae as getSupabaseAccessTokenWithRetry,Ax as getTask,Rx as getTaskStatus,Uv as getTemplate,Dx as getTicket,iC as getToolInfo,Hf as getTranscriptFilename,DC as getTurnCost,EC as getTurnError,jC as getTurnErrorDetails,$C as getTurnStatus,tu as getUsageRollup,FT as getUserRolesWithToken,Oc as getVersionDiff,TC as getWorkingState,ja as grantAccountSecretResource,LR as grantSandboxProjectAccess,cw as grantSecretToAgent,gC as groupMessagesIntoTurns,BC as hasDiffs,rA as hasLocalhostUrls,rf as hasPreviewTarget,PC as hasRetryingAssistantTurn,lf as heartbeatGapEvent,pl as holdSessionPrompts,Ks as humanizeToolName,Nr as impersonationHeaders,mS as importSsoProviderFromMetadata,wI as inboxObservationSupersedes,Jd as initialWakeEscalationState,Fv as installTemplate,_t as invalidateTokenCache,yo as inviteAccountMember,na as inviteProjectMember,To as inviteRepoCollaborator,Bd as isAbortError,nx as isAdminBypassEnabled,zA as isAgentPart,Qm as isAppRouteUrl,YA as isAttachment,Ah as isAttachmentPartRef,Ai as isBillingError,VA as isCompactionPart,hn as isConfigured,rT as isDestructivePhase,mA as isExternalUrl,Si as isFeatureDisabledError,Cd as isFilePart,wg as isImpersonationSessionLive,eR as isInstanceDetailPath,ph as isInstanceScopedAppPath,uA as isInternalLocalhostUrl,jP as isInviteSent,RC as isLastUserMessage,gP as isManagedGithubProject,aR as isOpenCodeConfigInvalidError,JA as isPatchPart,lA as isPreviewUrl,af as isProxiableLocalhostUrl,Ws as isReasoningPart,$y as isRetryableTurnError,Zv as isRuntimeReady,ln as isSandboxNotReadyError,Xi as isServerReachable,zc as isSessionFresh,Hk as isSessionStartError,My as isShellMode,XA as isSnapshotPart,Vd as isSubdomainPreviewUrl,ve as isTextPart,fe as isToolPart,tC as isToolPartHidden,Wi as isUnderSandboxRoot,gA as isWebProxyUrl,Vh as kortixAppViewerToken,Lg as kortixPty,vo as leaveAccount,Wo as linkGitHubInstallation,Fo as linkRepository,Ap as listAccountAudit,Tp as listAccountAuditWebhooks,ho as listAccountInvites,fo as listAccountMembers,Qw as listAccountResourceGrants,Ra as listAccountSecretResources,PS as listAccountSessions,_p as listAccountTokens,io as listAccounts,sS as listActions,ev as listAdminSandboxes,Ku as listAgentIdentities,Ga as listAllConnections,Zp as listAppDeployments,Np as listApps,op as listAssignments,$S as listAuditEvents,TS as listAuditWebhooks,VR as listBackups,Fl as listBillingTransactions,qc as listChangeRequests,Ew as listChannelBindings,Kx as listColumns,ik as listConnectSections,sk as listConnectToolkits,Ba as listConnections,Kt as listConnectorTools,Qa as listConnectors,ww as listCostByProject,b_ as listCredentialEvents,h_ as listCredentials,ps as listDiscoverConnectors,ok as listDiscoverIntegrations,dc as listDiscoverSections,Mi as listEnv,qp as listFeaturedMarketplaces,Wx as listFields,$t as listFiles,Pu as listGatewayLogs,Bo as listGitHubInstallations,No as listGitHubRepositories,Ko as listGitHubRepositoryBranches,Lu as listGroupMembers,Vw as listGroupProjectGrants,Du as listGroups,o_ as listKortixProjectSessions,r_ as listKortixProjects,qi as listKortixPty,Go as listLinkableGitHubInstallations,Xo as listManagedGitRepositories,Dp as listMarketplaceCatalogItems,Lp as listMarketplaceSources,Op as listMarketplaces,Xw as listMemberGroups,Jw as listMemberProjectAccess,p_ as listMilestoneEvents,l_ as listMilestones,Zu as listOAuthClients,ga as listPendingApprovals,ra as listPendingProjectInvites,lp as listPermissions,uc as listPipedreamApps,pc as listPipedreamSections,Yw as listPolicies,Zo as listProjectAccess,Jo as listProjectAccessRequests,Qx as listProjectAgents,Cp as listProjectAudit,Ec as listProjectBranches,wp as listProjectCliTokens,jc as listProjectCommits,Cc as listProjectFiles,oa as listProjectGroupGrants,yc as listProjectPolicies,ua as listProjectResourceGrants,bc as listProjectSandboxTemplates,Ac as listProjectSandboxes,ya as listProjectSecrets,it as listProjectSessions,Xc as listProjectSessionsPage,xc as listProjectSnapshots,_l as listProjectTriggers,qe as listProjects,Ro as listProjectsForAccount,PT as listPublicMarketplaceItems,kT as listPublicMarketplaces,Kw as listReferrals,up as listReviewItems,Nu as listRoles,FR as listSandboxProjectMembers,fp as listSandboxShares,TR as listSandboxes,oS as listScimTokens,vS as listServiceAccountsApi,w_ as listServiceTemplates,k_ as listServices,rk as listSessionConnectRequests,ru as listSessionCosts,cl as listSessionPrompts,Da as listSessionProviderSecretPools,Yc as listSessionPublicShares,ma as listSessionsNeedingInput,yS as listSsoGroupMappings,Cx as listTaskEvents,vx as listTasks,Vx as listTemplates,Ox as listTicketEvents,Mx as listTickets,Fh as loadHttpSessionHistory,yT as markInstanceError,Ht as markSessionFresh,Gc as mergeChangeRequest,rv as migrateAdminSandboxProvider,nt as mkdir,uf as narrowChatEvent,iR as normalizeAppPathname,fA as normalizeExternalInput,sn as normalizeToolName,Bc as openChangeRequest,Gs as openEventStream,GT as openStressTestStream,Ee as parseBillingError,QC as parseFlagOverride,Qt as parseLocalhostUrl,fh as parseOpenCodeErrorPayload,id as parseProxyHop,fd as parseSubdomainUrl,dA as parseWebProxyUrl,c_ as patchKortixProject,oc as pipedreamConnect,Xa as pipedreamConnectConnection,fc as pipedreamFinalize,Ja as pipedreamFinalizeConnection,O as platformConfig,ZP as pollConnectionOAuth2DeviceAuthorization,Pa as pollProjectProviderOAuth,_u as previewGatewayRoute,uS as previewMfaRequired,Qu as probeEffectivePermission,Yu as probeEffectivePermissions,cI as probePreviewPort,TI as projectCompacting,mI as projectSessionConnection,Kk as projectSessionStartSeed,vI as projectWorking,Mo as provisionProject,fP as provisionProjectStream,PP as provisionProjectWithToken,gd as proxyLocalhostUrl,cA as proxyUrlToInternal,Yl as purchaseCredits,WP as putConnectionOAuth2Application,MR as reactivateSandbox,Vl as reactivateSubscription,Ze as readBlob,Ye as readFile,Tc as readProjectFile,_c as rebuildProjectSnapshot,Na as reconcileConnection,Ka as reconcileMemberConnection,A_ as reconcileServices,CT as recordPlatformLogout,Bw as refreshReferralCode,ct as refreshSession,Ss as registerAppArtifact,JP as registerConnectionOAuth2Client,C_ as registerService,Yo as rejectProjectAccessRequest,oC as relativizePath,fl as reloadProjectSessionConfig,yl as reloadProjectSessionConfigStream,jp as removeAccountAuditWebhook,go as removeAccountBrandingAsset,wo as removeAccountMember,Gu as removeGroupMember,Li as removeKortixPty,Gp as removeMarketplaceSource,Of as removeQueued,ke as renameFile,RR as renameSandbox,Kc as reopenChangeRequest,f_ as reopenMilestone,Uf as reorderQueued,Hx as replaceColumns,zx as replaceFields,Xx as replaceTemplates,WS as requestAccountDeletion,Hc as requestChangesOnChangeRequest,EP as requestProjectAccess,Mp as requestProjectConnector,$p as requestProjectSecret,xo as resendAccountInvite,ia as resendPendingProjectInvite,mo as resetAccountBranding,D_ as resetClient,xu as resetGatewayRoutingPolicy,Ms as resetPassword,U_ as resetPublicClient,cT as resetSandboxUpdateStatus,fa as resolveApproval,dw as resolvedPlan,Wt as restartProjectSession,ER as restartSandbox,JR as restoreBackup,Df as retryFailed,ul as retrySessionPrompt,__ as revealCredential,$a as revokeAccountSecretResourceGrant,kS as revokeAccountSession,kp as revokeAccountToken,cp as revokeAssignment,Wa as revokeConnection,$u as revokeGatewayKey,sa as revokePendingProjectInvite,ta as revokeProjectAccess,vp as revokeProjectCliToken,BR as revokeSandboxProjectAccess,hp as revokeSandboxShare,cS as revokeScimToken,el as revokeSessionPublicShare,Se as rewriteLocalhostUrl,sd as rollbackApp,Ia as rotateAccountSecretResource,rp as rotateOAuthClientSecret,Mu as runGatewayPlayground,Ho as saveGitHubInstallation,Xl as scheduleDowngrade,qa as searchConnectorTools,Rc as searchProjectFiles,Is as sendMagicLink,Hw as sendReferralEmails,EI as serverCompactionRevalidateAtMs,v_ as serviceAction,Wk as sessionStartKey,rR as setActiveInstanceCookie,tx as setAdminBypass,tv as setAdminProviderDistribution,iv as setAdminProviderFallback,Ml as setAgentScope,Fb as setBootstrapAuthToken,Ub as setCachedAuthToken,nk as setConnectionPolicies,ec as setConnectorAuthorizationStrategy,mc as setConnectorCredential,Za as setConnectorCredentialMode,ic as setConnectorName,rc as setConnectorPolicies,ck as setConnectorSecretBinding,tc as setConnectorSensitive,Va as setDefaultConnection,DS as setEnterpriseDemo,Di as setEnv,Tu as setGatewayBudget,bu as setGatewayRoutingPolicy,VT as setGitHubAppFromExisting,XT as setGitHubAppPat,Hb as setImpersonationSession,UT as setMaintenanceConfig,iS as setMemberSuperAdmin,pS as setMfaRequired,El as setModelDefault,va as setPersonalProjectSecret,Cs as setProjectModelAccess,Zk as setProjectModelEnablement,Uo as setProjectOnboardingComplete,xP as setProjectOnboardingProfile,hc as setProjectPolicies,ba as setProjectSecretStrategy,xl as setProjectSessionModel,bl as setProjectSessionScope,Jc as setProjectSessionSharing,Sl as setProjectTriggersActivation,Oa as setSessionProviderSecretPool,ZR as setupSSH,Ud as shellExitCode,Cg as shouldAttachImpersonation,IC as shouldHideResponsePart,vy as shouldShowToolPart,Ts as signInWithPassword,js as signInWithProvider,Us as signInWithSso,Ls as signOut,Rs as signUp,xC as sortSessions,ZA as splitUserParts,nd as startApp,QP as startConnectionOAuth2Authorization,YP as startConnectionOAuth2DeviceAuthorization,ET as startConnectorSetupLink,zT as startGitHubAppManifest,_a as startProjectProviderOAuth,Ue as startProjectSession,OT as startSessionWithToken,Ex as startTask,rd as stopApp,zt as stopProjectSession,jR as stopSandbox,uC as stripAnsi,tR as stripInstancePrefix,ue as stripTrailingSlashes,AT as submitAccessRequest,LT as submitDemoRequest,TT as submitOAuthConsent,dp as submitReviewItem,MT as submitSecretSetupLink,Wb as subscribeToImpersonation,rx as supabaseClient,Ya as syncConnectors,hw as syncSubscription,F_ as systemReload,Me as toDaemonPath,sR as toInstanceAwarePath,cf as toInternalUrl,Et as toSandboxAbsolutePath,zi as toWorkspaceRelative,Hs as toolInfo,rh as toolViewModel,aT as triggerSandboxUpdate,Fg as triggersRequest,yC as turnHasSteps,Bx as unassignTicket,ne as unwrapError,Ep as updateAccountAuditWebhook,uo as updateAccountBranding,So as updateAccountMemberRole,co as updateAccountName,aw as updateAgentConfig,Wp as updateApp,Xp as updateAppAccess,ES as updateAuditWebhook,jw as updateChannelBinding,Ha as updateConnectionCredential,yu as updateEmailPolicy,Oo as updateExperimentalFeature,Do as updateFeatureFlag,Uu as updateGroup,Fi as updateKortixPty,g_ as updateMilestone,np as updateOAuthClient,Ds as updatePassword,SS as updatePatPolicy,eS as updatePolicy,os as updateProject,ea as updateProjectAccess,Zx as updateProjectAgent,Ol as updateProjectDefaultAgent,ca as updateProjectGroupGrant,qo as updateProjectSandboxProvider,dl as updateProjectSession,kl as updateProjectTrigger,Vu as updateRole,Xu as updateRolePermissions,wc as updateSandboxTemplate,_S as updateSessionPolicy,Ix as updateTask,bP as updateTemplateWarmPool,Ux as updateTicket,Fx as updateTicketStatus,qs as updateUserMetadata,po as uploadAccountBrandingAsset,Qp as uploadAppArtifactArchive,La as uploadConnectorAttachment,et as uploadFile,Gt as uploadPromptAttachment,pu as uploadSlackChannelFile,Qe as uploadTimeoutMsForBytes,x_ as upsertCredential,wa as upsertProjectGitCredential,ha as upsertProjectSecret,gS as upsertSsoProvider,Io as validateProjectManifest,Gw as validateReferralCode,Ao as validateToken,Ow as verifyGatewayProvider,Es as verifyOtp,FI as wakeEscalationAttemptSummary,UI as wakeEscalationNote,OI as wakeProgressFingerprint,AI as workingExpiryAtMs,tt as writeFile};
75
+ `),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,u=r.length;for(;o>s&&u>s&&n[o-1]===r[u-1];)o--,u--;let p=[];for(let d=0;d<s;d++)p.push({type:"unchanged",text:n[d]});for(let d=s;d<o;d++)p.push({type:"removed",text:n[d]});for(let d=s;d<u;d++)p.push({type:"added",text:r[d]});for(let d=o;d<n.length;d++)p.push({type:"unchanged",text:n[d]});return p}function Jy(e){let t=H(e.input?.oldString),n=H(e.input?.newString),r=t!==void 0&&n!==void 0?Xy(t,n):void 0;return{kind:"file-edit",path:Xs(e),diff:r}}var Bd=/^Found\s+(\d+)\s+match/i,Qy=/^(\/[^:]+?):\s*/,Fd=/Line\s+(\d+):/g;function Yy(e){let t=e.trim(),n=t.match(Bd),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let s=[];for(let o of r.split(/\n\n+/)){let u=o.trim();if(!u)continue;let p=u.match(Qy);if(!p)continue;let d=p[1],f=u.slice(p[0].length),m=[],h;for(Fd.lastIndex=0;(h=Fd.exec(f))!==null;)m.push({line:Number(h[1]),contentStart:h.index+h[0].length,headerStart:h.index});for(let P=0;P<m.length;P++){let x=P+1<m.length?m[P+1].headerStart:f.length,_=f.slice(m[P].contentStart,x).trim();s.push({path:d,line:m[P].line,content:_.endsWith(";")?_.slice(0,-1):_})}}return s}function Zy(e){return e.trim().split(`
76
+ `).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function eh(e){let t=H(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=Bd.test(e.output.trim())?Yy(e.output):Zy(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function th(e){let t=H(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=H(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function Vs(e){let t=Be(e)??{};return{content:H(t.content)??"",status:H(t.status)??"pending",priority:H(t.priority)}}function nh(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(Vs)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(Vs)};let n=Be(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(Vs)}:{kind:"todo",items:[]}}function rh(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=Be(r)??{},u=(Array.isArray(s.options)?s.options:[]).flatMap(p=>{let d=Be(p),f=d&&H(d.label);return f?[{label:f,description:d?H(d.description):void 0}]:[]});return{question:H(s.question)??"",header:H(s.header),options:u}})}}function sh(e){let n=e.input&&Object.keys(e.input).length>0?Ud(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?dt(e.outputParsed):Ud(e.outputParsed):e.outputText!==void 0?r=dt(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function ih(e){switch(on(e.name)){case"web_search":case"websearch":case"image_search":return Uy(e);case"bash":return Hy(e);case"read":return Wy(e);case"write":return zy(e);case"edit":case"morph_edit":return Jy(e);case"grep":case"glob":return eh(e);case"task":return th(e);case"todowrite":return nh(e);case"question":case"ask":return rh(e);default:return sh(e)}}var oh=new Set(["AbortError","MessageAbortedError"]),ah=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],ch=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function Gd(e){let t=e.toLowerCase();return ch.some(n=>t.includes(n))?!1:ah.some(n=>t.includes(n))}function lh(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 Nd(e){if(typeof e=="string")return Gd(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&oh.has(n))return!0;let r=lh(t);return typeof r=="string"?Gd(r):!1}var uh=["user","runtime-disposed","orphan-finalized","wake"],zC=["orphan-finalized","wake"];function VC(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 uh.includes(n)?n:void 0}function an(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function ph(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 ZC(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 Js(e,t,n){return e!==void 0?e:ph(an(t),n)}var eR={get disableMobileAdvertising(){return Js(O().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return Js(O().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return Js(O().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var cn="kortix-active-instance",dh=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function gh(e){return dh.some(t=>e===t||e.startsWith(`${t}/`))}function gt(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 nR(e){let t=gt(e);return!!t&&t.innerPath===""}function rR(e){let t=gt(e);return!t||!t.innerPath?e:t.innerPath}function mh(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=gt(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return gh(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function fh(e){return e?gt(e)?.instanceId??null:null}function sR(){return typeof window>"u"?null:fh(window.location.pathname)||yh()}function yh(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${cn}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function iR(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${cn}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${cn}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${cn}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function oR(e,t){return t?mh(t,e):e}function aR(e){let t=gt(e);return t?t.innerPath||"/dashboard":e}function Qs(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 hh(e){let t=Qs(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}function Kd(e){let t=hh(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}function lR(e){return Kd(e)!==null}var bh=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/];function un(e){let t=Qs(e);return t?bh.some(n=>n.test(t)):!1}var ln=class extends Error{constructor(t){let n=t?.trim();super(n&&un(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function xh(e){let t=Kd(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,u=t.data?.issues?.[0]?.path?.join("."),p=u?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${p}`,detail:o?`${u?`${u}: `:""}${o}`:void 0}}let n=Qs(e);return un(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:"OpenCode failed to load",message:n||"The sandbox is running, but OpenCode returned an error."}}function Y(){let e=an("BACKEND_URL")||O().backendUrl;return e||"http://localhost:8008/v1"}function mt(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=mt(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return mt(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}var Hd=["http://localhost:8008/v1","http://127.0.0.1:8008/v1"];function Wd(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return`${e.slice(0,t)}/platform/local-bridge/status`}function _h(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 Ys(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?`${Y()}/p/${n.external_id}/${ge.KORTIX_MASTER}`:""),status:_h(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 Zs(){let e=await qe(),t=[];for(let n of e){let r=await ot(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Ys(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Ae(e){let t=await Zs();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}async function pn(e,t={}){let n={"Content-Type":"application/json",...t.headers},r=t.signal??AbortSignal.timeout(3e4),s=await U(`${Y()}${e}`,{...t,headers:n,signal:r}),o=await s.text().catch(()=>{}),u;if(o)try{u=JSON.parse(o)}catch{}if(!s.ok){let p=u?.error||u?.message||u?.detail||o||`Platform API error ${s.status}`,d=new S(p,{status:s.status,code:u?.code||u?.error_code||String(s.status),details:u??(o?{rawText:o}:void 0),response:s,endpoint:e});throw s.status===402&&(d=Ee(Object.assign(d,{response:s,status:s.status,data:u}))),d}return u}function zd(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`${Y()}/p/${e.external_id}/${ge.KORTIX_MASTER}`}function _R(e,t){return e.external_id?`${Y()}/p/${e.external_id}/${t}`:null}async function AR(){let e=await i.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function Ph(e){let t=await Ae();if(t)return{sandbox:t.sandbox,created:!1};let r=(await qe())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await at(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await Ue(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Ys(r,s,o),created:!0}}async function CR(){return(await Ae().catch(()=>null))?.sandbox??null}async function RR(e){return{sandbox:(await Ph(e)).sandbox}}async function TR(e){let t=mt(e);return t?(await Ae(t).catch(()=>null))?.sandbox??null:null}async function IR(e,t){throw await Ae(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function ER(e){let t=mt(e);return(await Zs().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function jR(){if(typeof window>"u")return null;let e=Y(),t=Array.from(new Set([e,...Hd]));for(let n of t)try{let r=await fetch(Wd(n),{method:"GET",signal:AbortSignal.timeout(1500),headers:{Accept:"application/json"}});if(!r.ok)continue;let s=await r.json();if(!s.success||s.status!=="ready"||!s.data?.sandbox_id)continue;return s.data}catch{continue}return null}async function $R(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Ae(e);if(!t)throw new Error("Project session sandbox not found");await zt(t.project.project_id,t.session.session_id)}async function MR(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Ae(e);if(!t)throw new Error("Project session sandbox not found");await Vt(t.project.project_id,t.session.session_id)}async function DR(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function OR(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function ei(e,t,n){let r=zd(e),s=await U(`${ue(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function BR(e,t){return ei(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function GR(e,t,n,r="member"){await ei(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function NR(e,t,n){await ei(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}async function WR(e){let t=await pn(`/platform/invites/${encodeURIComponent(e)}`,{method:"GET"});if(!t.success||!t.data)throw new Error(t.error||"Invite not found");return t.data}async function zR(e){let t=await pn(`/platform/invites/${encodeURIComponent(e)}/accept`,{method:"POST"});if(!t.success||!t.data)throw new Error(t.error||"Failed to accept invite");return t.data}async function VR(e){let t=await pn(`/platform/invites/${encodeURIComponent(e)}/decline`,{method:"POST"});if(!t.success)throw new Error(t.error||"Failed to decline invite")}async function JR(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function QR(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function YR(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function ZR(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function tT(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function nT(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var wh=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function iT(e){return wh.includes(e)}async function oT(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 aT(e){let t=e?`?channel=${e}`:"",n=await fetch(`${Y()}/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 s=await kh(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function kh(e){let t=e?`?channel=${e}`:"",n=await fetch(`${Y()}/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 cT(){let e=await fetch(`${Y()}/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 lT(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function uT(e){}async function pT(e){}async function fT(e){return{serverTypes:[],location:e||"hel1"}}async function yT(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function hT(e){let t=await i.delete(`/platform/sandbox?sandbox_id=${e}`);if(t.error)throw t.error;return t.data}async function bT(e,t){await i.post("/platform/sandbox/mark-error",{sandbox_id:e,error_message:t},{showErrors:!1,timeout:1e4})}async function xT(){let e=await i.post("/platform/sandbox/claim-computer",{},{timeout:6e4});if(e.error)throw e.error;return e.data}async function _T(e){let t=await i.get(`/platform/sandbox/${e}/status`,{showErrors:!1,timeout:1e4});return t.success?t.data??null:null}function PT(e,t){return`${Y()}/platform/sandbox/${e}/provision-stream?token=${encodeURIComponent(t)}`}var ye=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function dn(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return/\/v1$/.test(t)?t:`${t}/v1`}function ti(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 gn(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function mn(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function z(e,t,n){let r=n?.body!==void 0,s=await fetch(`${dn(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:ti(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await gn(s);if(!s.ok)throw new ye(mn(s,o),s.status,o);return o}function Sh(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 kT(e,t){return z(`/marketplace/items${Sh(t)}`,e)}function ST(e){return z("/marketplace/marketplaces",e)}function vT(e,t){return z(`/marketplace/items/${encodeURIComponent(e)}`,t)}function AT(e,t,n){return z(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function CT(e,t){return z("/access/check-email",t,{method:"POST",body:{email:e}})}function RT(e,t){return z("/access/request-access",t,{method:"POST",body:e})}function TT(e){return z("/auth/logout",e,{method:"POST",body:{}})}function IT(e,t){return z(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function ET(e,t){return z("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function jT(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function $T(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function MT(e,t){return z(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:{}})}function DT(e,t){return z(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function OT(e,t,n){return z(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t}})}function qT(e,t){return z(`/p/public-share/${encodeURIComponent(e)}`,t)}function UT(e,t,n){return z(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function FT(e){return z("/system/maintenance",e)}function LT(e,t){return z("/system/maintenance",t,{method:"PUT",body:e})}function BT(e){return z("/user-roles",e)}function GT(e,t){return z("/system/demo-request",t,{method:"POST",body:e})}async function NT(e,t,n){let r=new URLSearchParams({format:t.format});t.action&&r.set("action",t.action),t.actor&&r.set("actor",t.actor),t.project_id&&r.set("project_id",t.project_id),t.session_id&&r.set("session_id",t.session_id),t.actor_type&&r.set("actor_type",t.actor_type),t.source&&r.set("source",t.source),t.phase&&r.set("phase",t.phase),t.outcome&&r.set("outcome",t.outcome),t.request_id&&r.set("request_id",t.request_id),t.correlation_id&&r.set("correlation_id",t.correlation_id),t.resource_type&&r.set("resource_type",t.resource_type),t.since&&r.set("since",t.since),t.until&&r.set("until",t.until),t.q&&r.set("q",t.q),t.cursor&&r.set("cursor",t.cursor),t.limit!=null&&r.set("limit",String(t.limit));let s=await fetch(`${dn(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${r}`,{headers:ti(n,!1),...n.signal?{signal:n.signal}:{}});if(!s.ok){let o=await gn(s);throw new ye(mn(s,o),s.status,o)}return{blob:await s.blob(),filename:s.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:s.headers.get("x-audit-capped")==="true",rowCount:s.headers.get("x-audit-row-count"),complete:s.headers.get("x-audit-complete")!=="false",nextCursor:s.headers.get("x-audit-next-cursor")||null}}async function KT(e,t){let n=await fetch(`${dn(t.backendUrl)}/admin/stress-test/run`,{method:"POST",headers:ti(t,!0),body:JSON.stringify(e),...t.signal?{signal:t.signal}:{}});if(!n.ok){let r=await gn(n);throw new ye(mn(n,r),n.status,r)}if(!n.body)throw new ye("No response body",n.status,null);return n.body}var vh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ah(e,t){return vh.test(t)?new URL(`templates/public/${t.toLowerCase()}`,`${dn(e)}/`):null}async function HT(e,t,n){let r=Ah(e,t);if(!r)throw new ye("Invalid shareId parameter",400,null);let s=await fetch(r,{signal:n}),o=await gn(s);if(!s.ok)throw new ye(mn(s,o),s.status,o);return o}async function VT(){let e=await i.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 XT(e={}){let t=await i.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 JT(e){let t=await i.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 QT(e){let t=await i.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 YT(){let e=await i.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 Ch="/kortix/part/";function Rh(e){return typeof e=="string"&&e.startsWith(Ch)}async function nI(e){if(!Rh(e))throw new Error(`not an attachment part reference: ${e}`);let t=re();if(!t)throw new Error("runtime url not bound");let n=await U(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function Vd(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 Th(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.size===0||o.has(n.origin)}catch{return!1}}function Xd(e,t){return Th(e,t)?(t?Vd(t):null)??Vd(e):null}function Jd(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 Qd(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}async function Ih(e,t={}){let n=Xd(e,t.serverUrl);if(!n)return!1;let r=await We();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 aI(e,t={}){if(Jd(e)){let n=await We();return n?Qd(e,n):e}return await Ih(e,t),e}var lI=3e3;function Eh(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 uI(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return Eh(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function ni(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function dI(e,t){return`${ni(e)}/presentation-templates/${encodeURIComponent(t)}/pdf#toolbar=0&navpanes=0&scrollbar=0&view=FitH`}function gI(e,t){return`${ni(e)}/presentation-templates/${encodeURIComponent(t)}/image.png`}function jh(e,t){return`${ni(e)}/presentation/convert-to-${t}`}async function mI(e,t,n,r){let s=jh(t,e),o=r?.pollIntervalMs??2500,u=r?.timeoutMs??4*6e4,p=Date.now(),d=!1;for(;;){let f=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),m=f.headers.get("content-type")||"";if(f.ok&&(m.includes("pdf")||m.includes("presentation")||m.includes("octet-stream"))){let _=await f.blob();if(_.size===0)throw new Error("Downloaded file is empty");return _}if(f.status===202){if(d||(d=!0,r?.onGenerating?.()),Date.now()-p>u)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((_,v)=>{let M=setTimeout(_,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(M),v(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let P=await f.text().catch(()=>""),x=f.statusText;try{let _=JSON.parse(P);x=String(_.error||_.detail||_.message||x)}catch{P&&(x=P)}throw new Error(`Failed to download ${e.toUpperCase()}: ${x} (HTTP ${f.status})`)}}function yI(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 hI(e){return e==="unreachable"}var xI=6e4,_I=45e3,PI=45e3,wI=1e4,kI=3e3,SI=15e3;function vI(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function AI(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 ri(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function CI(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:u,nowMs:p}=e,d=!!t&&p-t.atMs<6e4,f=t?t.turnId===void 0?t.messageId:t.turnId:null,m=d?t.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,h=d?t.atMs:Number.NEGATIVE_INFINITY,P=!!n&&p-n.atMs<15e3,x=P?n.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,_=!!s&&p-s.atMs<=45e3,v=!!o&&p-o.atMs<=45e3,M=!!r&&p-r.atMs<=1e4,$=o&&o.type==="idle"&&o.origin!=="local"?o:null,y=!!u&&p-u.atMs<=45e3&&(!$||u.atMs>$.atMs),a=q=>{if(!$)return!1;let N=ri(q.started_at);return!(N===null||N>=$.atMs)};if(y&&u.atMs>=x)return{state:"working",source:"stream",turnId:_?s.turns.find(q=>q.state==="active"&&!a(q))?.message_id??null:null,since:u.atMs,serverOpenTurnToken:s?.turns[0]?.turn_token??null};let I=s?.turns[0]?.turn_token??null,R=_?s.turns.filter(q=>!a(q)):[],w=R.find(q=>q.state==="active")??R[0],F=!!o&&!(o.type==="idle"&&o.origin==="local");if(w&&s.atMs>=x&&(!F||s.atMs>=o.atMs))return{...w.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:w.message_id,since:ri(w.started_at)??s.atMs,serverOpenTurnToken:I};if(M&&r.pending>0&&r.atMs>=x)return{...v&&o.type!=="idle"&&(!_||o.atMs>s.atMs)&&o.atMs>=x?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?f:null,since:r.atMs,serverOpenTurnToken:I};let j=r?.drainedAtMs;if(M&&r.pending===0&&j!=null&&!P&&!(_&&s.atMs>=j))return{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:j,serverOpenTurnToken:I};let D=_&&!w&&s.atMs>=m,b=v&&o.atMs>=h&&(o.type==="idle"||o.atMs>=x);if(D&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:ri(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:I};if(b)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:I};if(d)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:f,since:t.atMs,serverOpenTurnToken:I};let T=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:p};return{state:"idle",source:T.source,turnId:null,since:T.atMs,serverOpenTurnToken:I}}function RI(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:u,nowMs:p}=e,d=[null,t?t.atMs+6e4:null,n?n.atMs+15e3:null,r?r.atMs+1e4:null,s?s.atMs+45e3:null,o?o.atMs+45e3:null,u?u.atMs+45e3:null],f=null;for(let m of d)m===null||m<=p||(f===null||m<f)&&(f=m);return f}var II=6e4;function EI(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function jI(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var $h=9e4;function $I(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+$h}var DI=75e3,OI=2,qI=2e4;function Yd(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function UI(e){return e.filter(t=>t!=null).join("|")}function Mh(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function FI(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...Yd(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...Yd(),settled:!0};let u=e.lastProgressAtMs,p=u===null,d=t.progress!==e.fingerprint,f=u===null||d?t.nowMs:u,m=Math.max(0,t.nowMs-f),h={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:f,msSinceProgress:m,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...h,status:"exhausted"};let P=!p&&!d&&m>=r;if(!t.serverGaveUp&&!P||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return h;let x=Mh(e.attempts,s);return x?{...h,status:"escalating",dispatch:x,attempts:[...e.attempts,{step:x,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...h,status:"exhausted"}}var Dh={"retry-start":"retrying",restart:"restarting"};function LI(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${Dh[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function Oh(e){return e===1?"once":e===2?"twice":`${e} times`}function BI(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(s=>s.step==="restart").length,n=e.attempts.some(s=>s.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${Oh(t)}`),`Tried: ${r.join(", then ")}.`}var qh=1e3,Uh=15e3,Zd=100,Fh=50,Lh=10;function eg(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let u=new URLSearchParams({limit:String(r)});s&&u.set("before",s);let p=await e.getToken?.(),d=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${u}`,{headers:p?{Authorization:`Bearer ${p}`}:void 0,...o?{signal:o}:{}});if(!d.ok)throw d.status===503?new ln(`session ${d.status}`):new S(`Session synchronization failed: ${d.status}`,{status:d.status});return{messages:await d.json(),nextCursor:d.headers.get("x-next-cursor")||void 0}}}function Bh(e){return Nh(eg(e))}function Gh(e){return new si({...e,loadPage:eg(e)})}async function Nh(e){let t=[],n=new Set,r;do{let u=await e({limit:Zd,...r?{before:r}:{}});if(t.push(u.messages),r=u.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let u=t.length-1;u>=0;u--)for(let p of t[u])o.has(p.info.id)||(o.add(p.info.id),s.push(p));return s}var Kh={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},si=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;olderRequest;livenessTimer;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??Kh,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,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){if(!t){let n=this.livenessTimer!==void 0;this.stopLivenessTimer(),n&&!this.destroyed&&this.reconcile("turn-end");return}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()}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||Nd(n)||this.abortController.signal.aborted)return;if(this.update({freshness:un(n)?"loading":"error"}),n instanceof S&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(qh*2**this.retryAttempt,Uh);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.options.loadPage({limit:t==="tail"?Fh:Zd,...r?{before:r}:{}},this.abortController.signal);return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let u=[...t.messages],p=new Set(this.knownUserMessageIds),d=new Set(s?[s]:[]),f=t.nextCursor,m=0;for(let h of t.messages)h.info.role==="user"&&p.add(h.info.id);for(;f&&m<Lh&&u.some(h=>h.info.role==="assistant"&&!!h.info.parentID&&!p.has(h.info.parentID));){if(d.has(f))throw new Error(`Session history cursor repeated: ${f}`);d.add(f);let h;try{h=await this.loadPage(n,r,f)}catch(P){throw o?.({messages:[...u],nextCursor:f}),P}if(this.destroyed)return{messages:u,nextCursor:f};m+=1,u.unshift(...h.messages);for(let P of h.messages)P.info.role==="user"&&p.add(P.info.id);f=h.nextCursor,o?.({messages:[...u],nextCursor:f})}return{messages:u,nextCursor:f}}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;!n&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,u=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(u,n),t.then(u,u)})}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 Hh(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return`${t}/tunnel/permission-requests/stream`}function Wh(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:u,onError:p,signal:d}=e,f=new Map,m=null,h=!1;function P($,l){o?.($,l);let y=f.get($);if(y)for(let a of y)try{a(l)}catch{}}async function x(){if(h)return;m=new AbortController;let $=d?AbortSignal.any([m.signal,d]):m.signal;try{let l={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(l["Content-Type"]="application/json");let y=await fetch(t,{method:r,headers:l,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:$,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");u?.();let a=y.body.getReader(),A=new TextDecoder,I="",R="message",w="";for(;!h;){let{done:F,value:j}=await a.read();if(F)break;I+=A.decode(j,{stream:!0});let K=I.split(`
77
+ `);I=K.pop()||"";for(let D of K)D===""?w&&(P(R,w.trimEnd()),R="message",w=""):D.startsWith("event: ")?R=D.slice(7).trim():D.startsWith("data: ")?w+=(w?`
78
+ `:"")+D.slice(6):D.startsWith("data:")&&(w+=(w?`
79
+ `:"")+D.slice(5))}}catch(l){if(h||l instanceof DOMException&&l.name==="AbortError")return;p?.(l instanceof Error?l:new Error(String(l)))}}function _(){h=!0,m?.abort(),m=null,f.clear()}function v($,l){let y=f.get($)??new Set;y.add(l),f.set($,y)}function M($,l){f.get($)?.delete(l)}return{connect:x,close:_,addEventListener:v,removeEventListener:M}}function zI(e,t){return Wh({...t,url:Hh(e)})}var zh="/_kortix/viewer";var fn=new Map;function Vh(){fn.clear()}async function Xh(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 tg(e={}){let t=e.path??zh,n=e.fetch??((o,u)=>fetch(o,u)),r=fn.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=Xh(t,n).then(o=>{let u=o?.expires_at?Date.parse(o.expires_at):Number.NaN,p=Number.isFinite(u)?u-6e4:Date.now()+6e4;return fn.set(t,{session:o,expiresAt:p}),o});return fn.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function Jh(e={}){return async()=>(await tg(e))?.access_token??null}export{uh as ABORT_REASONS,zC as ABORT_REASONS_NOT_YET_EMITTED,cn as ACTIVE_INSTANCE_COOKIE,Ch as ATTACHMENT_PART_REF_PREFIX,S as ApiError,Te as AuthError,be as BillingError,$d as COST_MARKUP,_d as DEFAULT_TRANSCRIPT_OPTIONS,wh as DESTRUCTIVE_PHASES,Lr as FEATURE_DISABLED_CODE,mP as FEATURE_FLAG_KEYS,Ig as FEATURE_NOT_SUPPORTED_CODE,ct as HeadlessAuthError,ye as HostBoundaryError,Sg as IMPERSONATION_HEADER,wI as INBOX_OBSERVATION_MAX_MS,dh as INSTANCE_SCOPED_ROUTES,am as MAX_PROMPT_ATTACHMENTS_BYTES,es as MAX_PROMPT_ATTACHMENT_BYTES,Ji as MAX_PROMPT_ATTACHMENT_FILES,Eg as MODEL_NOT_SERVABLE_CODE,SI as OPTIMISTIC_ABORT_MAX_MS,II as OPTIMISTIC_COMPACTION_MAX_MS,xI as OPTIMISTIC_RECEIPT_MAX_MS,lI as PREVIEW_PROBE_TIMEOUT_MS,Dw as PROJECT_SESSION_NAME_LOOKUP_LIMIT,Mw as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,Tm as PROJECT_SESSION_PAGE_MAX_LIMIT,jg as PROVISION_IN_FLIGHT_CODE,ks as PublicSessionShareError,Ie as RequestTooLargeError,Xe as RuntimeNotReadyError,Yr as SANDBOX_FS_ROOTS,ge as SANDBOX_PORTS,$h as SERVER_COMPACTION_REVALIDATE_MS,_I as SERVER_OBSERVATION_MAX_MS,PI as STREAM_OBSERVATION_MAX_MS,ln as SandboxNotReadyError,nn as SessionNotReadyError,hs as SessionStartError,kI as TURN_END_LEDGER_LAG_MS,qI as WAKE_ESCALATION_COOLDOWN_MS,OI as WAKE_MAX_RESTARTS,DI as WAKE_NO_PROGRESS_MS,Yh as __getConfigResolver,Qh as __setConfigResolver,VC as abortErrorReason,Po as acceptAccountInvite,zR as acceptInvite,fp as actReviewItem,Xa as activateConnection,Nu as addGroupMembers,Np as addMarketplaceSource,FI as advanceWakeEscalation,My as allDescendantIds,Qd as appendPreviewToken,Qo as approveProjectAccessRequest,Mx as approveTask,cs as archiveProject,Gx as assignTicket,aa as attachGroupToProject,Fs as authMfa,Os as authUser,U as authenticatedFetch,aI as authorizePreviewUrl,i as backendApi,Ek as bindSlackIdentity,jk as bindTeamsIdentity,xa as brokerProjectSecretRequest,mh as buildInstancePath,gI as buildPresentationTemplateImageUrl,dI as buildPresentationTemplatePdfUrl,Xd as buildPreviewAuthEndpoint,Ah as buildPublicTemplateUrl,jh as buildRuntimePresentationConversionUrl,Cc as buildSandboxTemplate,cA as buildStaticFileHealthPreviewUrl,aA as buildStaticFileLocalUrl,oA as buildStaticFilePreviewUrl,af as buildStaticFileServicePath,Hh as buildTunnelEventStreamUrl,gA as buildWebProxyUrl,yp as bulkActReviewItems,sS as bulkDeletePolicies,iS as bulkImportPolicies,La as callConnector,XS as cancelAccountDeletion,bo as cancelAccountInvite,DR as cancelSandbox,pT as cancelSandboxUpdate,Yl as cancelScheduledChange,Xl as cancelSubscription,CT as checkAccessEmail,_C as childMapByParent,xT as claimComputer,Mf as claimNext,bk as claimPerSeatBilling,sl as claimWarmProjectSession,Cd as classifyPart,Eh as classifyPreviewProbeStatus,vy as classifyTurn,Ti as clearImpersonationSession,Vh as clearKortixAppViewerCache,Ml as clearModelDefault,Tw as clearSessionFresh,Hc as closeChangeRequest,y_ as closeMilestone,yC as collectTurnParts,Kx as commentTicket,Vc as commitSessionChanges,jI as compactionExpiryAtMs,$y as compareMessagesForDisplay,Df as completeInFlight,jd as computeStatusFromPart,nu as configureAutoTopup,hn as configureKortix,zl as confirmCheckoutSession,yu as connectEmail,cu as connectSlack,hI as connectionIsFaulted,Cm as connectorConnect,Rm as connectorFinalize,dv as convertPresentationToGoogleSlides,mI as convertRuntimePresentation,Ft as copyFile,su as costExportUrl,AI as countLiveInboxPrompts,oo as createAccount,jp as createAccountAuditWebhook,Ta as createAccountSecretResource,kp as createAccountToken,Wp as createApp,Yp as createAppAccessSession,ed as createAppDeployment,lp as createAssignment,jS as createAuditWebhook,QR as createBackup,Wl as createCheckoutSession,lc as createConnector,Ut as createFile,Mu as createGatewayKey,Fu as createGroup,Gh as createHttpSessionSyncController,yT as createInstance,If as createKortix,Ui as createKortixPty,Bs as createKortixSession,Ov as createMarketplaceInstallSession,m_ as createMilestone,rp as createOAuthClient,hk as createPerSeatCheckout,tS as createPolicy,Vl as createPortalSession,jo as createProject,e_ as createProjectAgent,Ap as createProjectCliToken,$o as createProjectRepo,pa as createProjectResourceGrant,at as createProjectSession,kl as createProjectTrigger,so as createPromptAttachmentController,Xu as createRole,Wh as createSSEStream,RR as createSandbox,bp as createSandboxShare,Sc as createSandboxTemplate,lS as createScimToken,RS as createServiceAccountApi,ll as createSessionPrompt,tl as createSessionPublicShare,jf as createSessionQueue,xS as createSsoGroupMapping,Ex as createTask,Fx as createTicket,zI as createTunnelEventStream,wo as declineAccountInvite,VR as declineInvite,JS as deleteAccountImmediately,Ea as deleteAccountSecretResource,Xp as deleteApp,MS as deleteAuditWebhook,ZR as deleteBackup,pc as deleteConnector,k_ as deleteCredential,Oi as deleteEnv,ke as deleteFile,ju as deleteGatewayBudget,zo as deleteGitHubInstallation,Bu as deleteGroup,hT as deleteInstance,l_ as deleteKortixProject,b_ as deleteMilestone,op as deleteOAuthClient,Aa as deletePersonalProjectSecret,rS as deletePolicy,n_ as deleteProjectAgent,wa as deleteProjectProviderOAuth,da as deleteProjectResourceGrant,Sa as deleteProjectSecret,fl as deleteProjectSession,vl as deleteProjectTrigger,Oe as deletePromptAttachment,Yu as deleteRole,Ac as deleteSandboxTemplate,IS as deleteServiceAccountApi,pl as deleteSessionPrompt,_S as deleteSsoGroupMapping,hS as deleteSsoProvider,Dx as deleteTask,Hx as deleteTicket,_o as describeAccountInvite,Fa as describeConnectorTool,la as detachGroupFromProject,nf as detectLocalhostUrls,TS as disableServiceAccountApi,hu as disconnectEmail,YT as disconnectGitHubApp,pu as disconnectSlack,JP as discoverConnectionOAuth2,QP as discoverConnectionOAuth2Resource,uc as discoverConnectorAuth,jR as discoverLocalSandbox,NT as downloadAccountAudit,O_ as dropClientForUrl,F_ as dropPublicClientForUrl,Ff as editQueued,$f as enqueue,Yx as ensurePmSession,Ih as ensurePreviewSessionCookie,zP as ensureProjectConnectorConnection,Ph as ensureSandbox,rl as ensureWarmProjectSession,Lg as env,$s as exchangeCode,Ip as exportAccountAudit,ie as extractGatewayErrorDetails,gt as extractInstanceRoute,Of as failInFlight,vi as featureDisabledKey,eR as featureFlags,fk as fetchAccountStateWithToken,uP as fetchAccountsWithToken,nI as fetchAttachmentPart,Ck as fetchCostExportCsv,tg as fetchKortixAppViewer,jc as fetchProjectArchive,wP as fetchProjectsForAccountWithToken,im as files,vs as finalizeAppArtifact,MT as finalizeConnectorSetupLink,Ot as findFiles,hC as findLastTextPart,qt as findText,Cl as fireProjectTrigger,kc as fixSandboxWithAgent,Ci as formatBillingErrorForUI,FC as formatCost,OC as formatDuration,xh as formatOpenCodeRuntimeError,xh as formatRuntimeError,LC as formatTokens,Wf as formatTranscript,Ef as generateSessionId,ao as getAccount,lo as getAccountBranding,zS as getAccountDeletionStatus,Fl as getAccountState,Ll as getAccountStateMinimal,yh as getActiveInstanceIdFromCookie,sv as getAdminProviderAnalytics,tv as getAdminProviderDistribution,ov as getAdminProviderFallback,QS as getAdminRole,Iy as getAgentCardLabel,ck as getAgentConfig,r_ as getAgentPersona,cT as getAllVersions,xC as getAnsweredQuestionParts,zp as getApp,Jp as getAppAccess,nd as getAppDeployment,rd as getAppDeploymentLogs,jv as getApprovalLink,We as getAuthToken,bi as getAuthTokenWithRetry,tu as getAutoTopupSettings,yk as getAutoTopupSetupStatus,Nl as getBillingCreditBreakdown,Hl as getBillingTierConfigurations,Gl as getBillingTransactionsSummary,Kl as getBillingUsageHistory,Lc as getChangeRequest,Bc as getChangeRequestDiff,Gc as getChangeRequestMergePreview,iC as getChildSessionError,sC as getChildSessionId,oC as getChildSessionToolParts,Pe as getClient,pe as getClientForUrl,fc as getConnectStatus,XP as getConnectionOAuth2Application,nw as getConnectionOAuth2Status,rw as getConnectionPolicies,us as getConnectorCatalog,oc as getConnectorConfig,sc as getConnectorPolicies,jT as getConnectorSetupLink,Ak as getCostSummary,fh as getCurrentInstanceIdFromPathname,sR as getCurrentInstanceIdFromWindow,Vi as getCurrentProject,xs as getDefaultAccountState,lC as getDiagnostics,Ty as getDirectory,ds as getDiscoverConnector,lw as getDiscoverIntegration,mu as getEmailInstallation,fu as getEmailMode,OS as getEnterpriseDemo,Dt as getFileStatus,Rd as getFileWithDir,Ry as getFilename,kh as getFullChangelog,Cu as getGatewayBreakdown,Iu as getGatewayBudgets,Tu as getGatewayErrors,$u as getGatewayKeys,Su as getGatewayLog,vu as getGatewayOverview,xu as getGatewayRoutingPolicy,Au as getGatewaySeries,Ru as getGatewaySessions,VT as getGitHubAppStatus,Lo as getGitHubInstallation,pv as getGoogleAuthUrl,Uu as getGroup,nC as getHiddenToolParts,Cg as getImpersonationSession,WR as getInvite,fT as getJustavpsServerTypes,o_ as getKortixProject,a_ as getKortixProjectBySession,Bi as getKortixPtyWebSocketUrl,aT as getLatestSandboxVersion,FT as getMaintenanceConfig,Vo as getManagedGitBackend,bP as getManagedGitStatus,Lp as getMarketplaceCatalogItem,Bp as getMarketplaceCatalogItemFile,pS as getMfaRequired,d_ as getMilestone,jl as getModelDefaults,np as getOAuthClient,IT as getOAuthConsentRequest,Kd as getOpenCodeConfigInvalidError,ZA as getPartText,vS as getPatPolicy,uC as getPermissionForTool,rs as getProject,s_ as getProjectActivity,Dc as getProjectCommit,Oc as getProjectCommitDiff,ss as getProjectDetail,qc as getProjectFileHistory,Eo as getProjectGitToken,is as getProjectLlmCatalog,yP as getProjectLlmCatalogProviders,As as getProjectModelAccess,os as getProjectModelPicker,gs as getProjectSandboxHealth,xP as getProjectSandboxProviderTransition,fs as getProjectSession,yl as getProjectSessionConfigState,xl as getProjectSessionScope,Zl as getProrationPreview,AR as getProviders,lA as getProxyBaseUrl,U_ as getPublicClientForUrl,vT as getPublicMarketplaceItem,AT as getPublicMarketplaceItemFile,Pv as getPublicSessionShare,wv as getPublicSessionShareMessages,qT as getPublicShareByToken,HT as getPublicTemplate,pC as getQuestionForTool,Gk as getReferralCode,Hk as getReferralStats,BC as getRetryInfo,GC as getRetryMessage,gp as getReviewItem,zu as getRolePermissions,Vu as getRoleUsage,nT as getSSHConnection,CR as getSandbox,TR as getSandboxById,_R as getSandboxPortUrl,_T as getSandboxProvisionStatus,PT as getSandboxProvisionStreamUrl,oT as getSandboxUpdateStatus,zd as getSandboxUrl,DT as getSecretSetupLink,Zr as getServerHealth,A_ as getServiceLogs,il as getSessionAudit,UC as getSessionCost,Ps as getSessionCostRecord,cd as getSessionHealth,Ow as getSessionOpenBundle,PS as getSessionPolicy,Zc as getSessionPreviewCandidates,Da as getSessionProviderSecretPool,ol as getSessionTranscript,al as getSessionTranscriptSync,cl as getSessionTurn,AC as getShellModePart,du as getSlackChannelFile,au as getSlackInstallation,uu as getSlackManifest,lu as getSlackMode,mS as getSsoProvider,cf as getStaticFileHealthPath,Fr as getSupabaseAccessToken,ae as getSupabaseAccessTokenWithRetry,Rx as getTask,Ix as getTaskStatus,Lv as getTemplate,qx as getTicket,aC as getToolInfo,zf as getTranscriptFilename,qC as getTurnCost,$C as getTurnError,MC as getTurnErrorDetails,DC as getTurnStatus,ru as getUsageRollup,BT as getUserRolesWithToken,Uc as getVersionDiff,EC as getWorkingState,ja as grantAccountSecretResource,GR as grantSandboxProjectAccess,uk as grantSecretToAgent,fC as groupMessagesIntoTurns,NC as hasDiffs,iA as hasLocalhostUrls,of as hasPreviewTarget,kC as hasRetryingAssistantTurn,pf as heartbeatGapEvent,gl as holdSessionPrompts,Ks as humanizeToolName,Kr as impersonationHeaders,yS as importSsoProviderFromMetadata,vI as inboxObservationSupersedes,Yd as initialWakeEscalationState,Bv as installTemplate,Pt as invalidateTokenCache,yo as inviteAccountMember,na as inviteProjectMember,To as inviteRepoCollaborator,Nd as isAbortError,sx as isAdminBypassEnabled,XA as isAgentPart,Zm as isAppRouteUrl,eC as isAttachment,Rh as isAttachmentPartRef,Ai as isBillingError,JA as isCompactionPart,bn as isConfigured,iT as isDestructivePhase,yA as isExternalUrl,Si as isFeatureDisabledError,Td as isFilePart,vg as isImpersonationSessionLive,nR as isInstanceDetailPath,gh as isInstanceScopedAppPath,dA as isInternalLocalhostUrl,MP as isInviteSent,IC as isLastUserMessage,fP as isManagedGithubProject,lR as isOpenCodeConfigInvalidError,YA as isPatchPart,pA as isPreviewUrl,lf as isProxiableLocalhostUrl,Ws as isReasoningPart,Dy as isRetryableTurnError,tA as isRuntimeReady,un as isSandboxNotReadyError,Xi as isServerReachable,Xc as isSessionFresh,zw as isSessionStartError,Oy as isShellMode,QA as isSnapshotPart,Jd as isSubdomainPreviewUrl,ve as isTextPart,fe as isToolPart,rC as isToolPartHidden,Wi as isUnderSandboxRoot,fA as isWebProxyUrl,Jh as kortixAppViewerToken,Gg as kortixPty,vo as leaveAccount,Wo as linkGitHubInstallation,Fo as linkRepository,Rp as listAccountAudit,Ep as listAccountAuditWebhooks,ho as listAccountInvites,fo as listAccountMembers,Zk as listAccountResourceGrants,Ra as listAccountSecretResources,kS as listAccountSessions,wp as listAccountTokens,io as listAccounts,oS as listActions,nv as listAdminSandboxes,Wu as listAgentIdentities,Ka as listAllConnections,td as listAppDeployments,Hp as listApps,cp as listAssignments,DS as listAuditEvents,ES as listAuditWebhooks,JR as listBackups,Bl as listBillingTransactions,Fc as listChangeRequests,$k as listChannelBindings,Wx as listColumns,aw as listConnectSections,ow as listConnectToolkits,Na as listConnections,Ba as listConnectorAccounts,Ht as listConnectorTools,Za as listConnectors,vk as listCostByProject,__ as listCredentialEvents,x_ as listCredentials,ps as listDiscoverConnectors,cw as listDiscoverIntegrations,mc as listDiscoverSections,Mi as listEnv,Fp as listFeaturedMarketplaces,Vx as listFields,Mt as listFiles,ku as listGatewayLogs,Bo as listGitHubInstallations,No as listGitHubRepositories,Ko as listGitHubRepositoryBranches,Gu as listGroupMembers,Jk as listGroupProjectGrants,qu as listGroups,c_ as listKortixProjectSessions,i_ as listKortixProjects,qi as listKortixPty,Go as listLinkableGitHubInstallations,Xo as listManagedGitRepositories,qp as listMarketplaceCatalogItems,Gp as listMarketplaceSources,Up as listMarketplaces,Qk as listMemberGroups,Yk as listMemberProjectAccess,g_ as listMilestoneEvents,p_ as listMilestones,tp as listOAuthClients,ga as listPendingApprovals,ra as listPendingProjectInvites,pp as listPermissions,dc as listPipedreamApps,gc as listPipedreamSections,eS as listPolicies,Zo as listProjectAccess,Jo as listProjectAccessRequests,Zx as listProjectAgents,Tp as listProjectAudit,$c as listProjectBranches,vp as listProjectCliTokens,Mc as listProjectCommits,Tc as listProjectFiles,oa as listProjectGroupGrants,bc as listProjectPolicies,ua as listProjectResourceGrants,_c as listProjectSandboxTemplates,Rc as listProjectSandboxes,ya as listProjectSecrets,ot as listProjectSessions,Qc as listProjectSessionsPage,Pc as listProjectSnapshots,wl as listProjectTriggers,qe as listProjects,Ro as listProjectsForAccount,kT as listPublicMarketplaceItems,ST as listPublicMarketplaces,Wk as listReferrals,dp as listReviewItems,Hu as listRoles,BR as listSandboxProjectMembers,hp as listSandboxShares,ER as listSandboxes,cS as listScimTokens,CS as listServiceAccountsApi,v_ as listServiceTemplates,S_ as listServices,iw as listSessionConnectRequests,iu as listSessionCosts,ul as listSessionPrompts,Oa as listSessionProviderSecretPools,el as listSessionPublicShares,ma as listSessionsNeedingInput,bS as listSsoGroupMappings,Tx as listTaskEvents,Cx as listTasks,Jx as listTemplates,Ux as listTicketEvents,Ox as listTickets,Bh as loadHttpSessionHistory,bT as markInstanceError,Wt as markSessionFresh,Kc as mergeChangeRequest,iv as migrateAdminSandboxProvider,nt as mkdir,df as narrowChatEvent,aR as normalizeAppPathname,hA as normalizeExternalInput,on as normalizeToolName,Nc as openChangeRequest,Gs as openEventStream,KT as openStressTestStream,Ee as parseBillingError,ZC as parseFlagOverride,Yt as parseLocalhostUrl,hh as parseOpenCodeErrorPayload,ad as parseProxyHop,hd as parseSubdomainUrl,mA as parseWebProxyUrl,u_ as patchKortixProject,cc as pipedreamConnect,Qa as pipedreamConnectConnection,hc as pipedreamFinalize,Ya as pipedreamFinalizeConnection,O as platformConfig,tw as pollConnectionOAuth2DeviceAuthorization,Pa as pollProjectProviderOAuth,wu as previewGatewayRoute,dS as previewMfaRequired,Zu as probeEffectivePermission,ep as probeEffectivePermissions,uI as probePreviewPort,EI as projectCompacting,yI as projectSessionConnection,Ww as projectSessionStartSeed,CI as projectWorking,Mo as provisionProject,hP as provisionProjectStream,kP as provisionProjectWithToken,fd as proxyLocalhostUrl,uA as proxyUrlToInternal,eu as purchaseCredits,VP as putConnectionOAuth2Application,OR as reactivateSandbox,Jl as reactivateSubscription,Ze as readBlob,Ye as readFile,Ec as readProjectFile,wc as rebuildProjectSnapshot,Ha as reconcileConnection,Wa as reconcileMemberConnection,R_ as reconcileServices,TT as recordPlatformLogout,Nk as refreshReferralCode,lt as refreshSession,Ss as registerAppArtifact,YP as registerConnectionOAuth2Client,T_ as registerService,Yo as rejectProjectAccessRequest,cC as relativizePath,hl as reloadProjectSessionConfig,bl as reloadProjectSessionConfigStream,Mp as removeAccountAuditWebhook,go as removeAccountBrandingAsset,ko as removeAccountMember,Ku as removeGroupMember,Li as removeKortixPty,Kp as removeMarketplaceSource,Uf as removeQueued,we as renameFile,IR as renameSandbox,Wc as reopenChangeRequest,h_ as reopenMilestone,Lf as reorderQueued,zx as replaceColumns,Xx as replaceFields,Qx as replaceTemplates,VS as requestAccountDeletion,zc as requestChangesOnChangeRequest,$P as requestProjectAccess,Op as requestProjectConnector,Dp as requestProjectSecret,xo as resendAccountInvite,ia as resendPendingProjectInvite,mo as resetAccountBranding,q_ as resetClient,Pu as resetGatewayRoutingPolicy,Ms as resetPassword,L_ as resetPublicClient,uT as resetSandboxUpdateStatus,fa as resolveApproval,mk as resolvedPlan,zt as restartProjectSession,$R as restartSandbox,YR as restoreBackup,qf as retryFailed,dl as retrySessionPrompt,w_ as revealCredential,$a as revokeAccountSecretResourceGrant,SS as revokeAccountSession,Sp as revokeAccountToken,up as revokeAssignment,Va as revokeConnection,Du as revokeGatewayKey,sa as revokePendingProjectInvite,ta as revokeProjectAccess,Cp as revokeProjectCliToken,NR as revokeSandboxProjectAccess,xp as revokeSandboxShare,uS as revokeScimToken,nl as revokeSessionPublicShare,Se as rewriteLocalhostUrl,od as rollbackApp,Ia as rotateAccountSecretResource,ip as rotateOAuthClientSecret,Ou as runGatewayPlayground,Ho as saveGitHubInstallation,Ql as scheduleDowngrade,Ua as searchConnectorTools,Ic as searchProjectFiles,Is as sendMagicLink,zk as sendReferralEmails,$I as serverCompactionRevalidateAtMs,C_ as serviceAction,Vw as sessionStartKey,Ma as setAccountSecretResourceAccess,iR as setActiveInstanceCookie,rx as setAdminBypass,rv as setAdminProviderDistribution,av as setAdminProviderFallback,Ol as setAgentScope,Bb as setBootstrapAuthToken,Lb as setCachedAuthToken,sw as setConnectionPolicies,nc as setConnectorAuthorizationStrategy,yc as setConnectorCredential,tc as setConnectorCredentialMode,ac as setConnectorName,ic as setConnectorPolicies,uw as setConnectorSecretBinding,rc as setConnectorSensitive,Ja as setDefaultConnection,qS as setEnterpriseDemo,Di as setEnv,Eu as setGatewayBudget,_u as setGatewayRoutingPolicy,JT as setGitHubAppFromExisting,QT as setGitHubAppPat,zb as setImpersonationSession,LT as setMaintenanceConfig,aS as setMemberSuperAdmin,gS as setMfaRequired,$l as setModelDefault,va as setPersonalProjectSecret,Cs as setProjectModelAccess,tk as setProjectModelEnablement,Uo as setProjectOnboardingComplete,PP as setProjectOnboardingProfile,xc as setProjectPolicies,ba as setProjectSecretStrategy,Pl as setProjectSessionModel,_l as setProjectSessionScope,Yc as setProjectSessionSharing,Al as setProjectTriggersActivation,qa as setSessionProviderSecretPool,tT as setupSSH,Ld as shellExitCode,Tg as shouldAttachImpersonation,jC as shouldHideResponsePart,Cy as shouldShowToolPart,Ts as signInWithPassword,js as signInWithProvider,Us as signInWithSso,Ls as signOut,Rs as signUp,PC as sortSessions,tC as splitUserParts,sd as startApp,ZP as startConnectionOAuth2Authorization,ew as startConnectionOAuth2DeviceAuthorization,$T as startConnectorSetupLink,XT as startGitHubAppManifest,_a as startProjectProviderOAuth,Ue as startProjectSession,UT as startSessionWithToken,$x as startTask,id as stopApp,Vt as stopProjectSession,MR as stopSandbox,dC as stripAnsi,rR as stripInstancePrefix,ue as stripTrailingSlashes,RT as submitAccessRequest,GT as submitDemoRequest,ET as submitOAuthConsent,mp as submitReviewItem,OT as submitSecretSetupLink,Vb as subscribeToImpersonation,ix as supabaseClient,ec as syncConnectors,xk as syncSubscription,B_ as systemReload,Me as toDaemonPath,oR as toInstanceAwarePath,uf as toInternalUrl,jt as toSandboxAbsolutePath,zi as toWorkspaceRelative,Hs as toolInfo,ih as toolViewModel,lT as triggerSandboxUpdate,Bg as triggersRequest,bC as turnHasSteps,Nx as unassignTicket,ne as unwrapError,$p as updateAccountAuditWebhook,uo as updateAccountBranding,So as updateAccountMemberRole,co as updateAccountName,lk as updateAgentConfig,Vp as updateApp,Qp as updateAppAccess,$S as updateAuditWebhook,Mk as updateChannelBinding,za as updateConnectionCredential,bu as updateEmailPolicy,Oo as updateExperimentalFeature,Do as updateFeatureFlag,Lu as updateGroup,Fi as updateKortixPty,f_ as updateMilestone,sp as updateOAuthClient,Ds as updatePassword,AS as updatePatPolicy,nS as updatePolicy,as as updateProject,ea as updateProjectAccess,t_ as updateProjectAgent,Ul as updateProjectDefaultAgent,ca as updateProjectGroupGrant,qo as updateProjectSandboxProvider,ml as updateProjectSession,Sl as updateProjectTrigger,Ju as updateRole,Qu as updateRolePermissions,vc as updateSandboxTemplate,wS as updateSessionPolicy,jx as updateTask,_P as updateTemplateWarmPool,Lx as updateTicket,Bx as updateTicketStatus,qs as updateUserMetadata,po as uploadAccountBrandingAsset,Zp as uploadAppArtifactArchive,Ga as uploadConnectorAttachment,et as uploadFile,Nt as uploadPromptAttachment,gu as uploadSlackChannelFile,Qe as uploadTimeoutMsForBytes,P_ as upsertCredential,ka as upsertProjectGitCredential,ha as upsertProjectSecret,fS as upsertSsoProvider,Io as validateProjectManifest,Kk as validateReferralCode,Ao as validateToken,Uk as verifyGatewayProvider,Es as verifyOtp,BI as wakeEscalationAttemptSummary,LI as wakeEscalationNote,UI as wakeProgressFingerprint,RI as workingExpiryAtMs,tt as writeFile};