@kortix/sdk 0.13.34 → 0.13.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/rest/projects-client/change-requests.d.ts +13 -1
- package/dist/core/rest/projects-client/change-requests.d.ts.map +1 -1
- package/dist/core/rest/projects-client/change-requests.js +9 -2
- package/dist/core/rest/projects-client/change-requests.js.map +1 -1
- package/dist/core/rest/projects-client/connectors.d.ts +24 -2
- package/dist/core/rest/projects-client/connectors.d.ts.map +1 -1
- package/dist/core/rest/projects-client/connectors.js +43 -7
- package/dist/core/rest/projects-client/connectors.js.map +1 -1
- package/dist/core/rest/projects-client/git-history.d.ts +13 -1
- package/dist/core/rest/projects-client/git-history.d.ts.map +1 -1
- package/dist/core/rest/projects-client/git-history.js +11 -2
- package/dist/core/rest/projects-client/git-history.js.map +1 -1
- package/dist/kortix.esm.min.js +3 -3
- package/dist/kortix.global.js +3 -3
- package/package.json +2 -2
package/dist/kortix.esm.min.js
CHANGED
|
@@ -10,14 +10,14 @@ var $f={backendUrl:"",getToken:async()=>null},ar=null,Vt=null;function Fk(e){Vt=
|
|
|
10
10
|
|
|
11
11
|
`);for(;m!==-1;){let h=o.slice(0,m);o=o.slice(m+2),m=o.indexOf(`
|
|
12
12
|
|
|
13
|
-
`);let _=ph(h);if(_){if(t(_),_.type==="error")throw new S(_.error,{status:_.status,code:_.code});_.type==="done"&&(a=_.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function mA(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function ti(e,t){return u(await c.patch(`/projects/${e}`,t))}async function ic(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function oc(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function ac(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function fA(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function yA(e,t){throw W("updateTemplateWarmPool")}async function cc(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function hA(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function ni(e){return u(await c.delete(`/projects/${e}`))}async function bA(e,t){return Je(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function _A(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Js(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 lc(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function uc(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function pc(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function dc(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function gc(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function mc(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await c.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function fc(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await c.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function yc(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function hc(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function bc(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await c.delete(`/projects/github/installation?${n.toString()}`))}async function _c(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function xc(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await c.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function TA(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function wc(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function kc(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Pc(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Sc(e){return u(await c.get(`/projects/${e}/access`))}async function vc(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function Ac(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function IA(e){return"status"in e&&e.status==="invited"}async function Rc(e,t,n,r){return u(await c.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Cc(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function Tc(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Ic(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Ec(e){return u(await c.get(`/projects/${e}/group-grants`))}async function jc(e,t,n,r){return u(await c.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function Mc(e,t,n,r){return u(await c.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function $c(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function Oc(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function Dc(e,t){return u(await c.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function qc(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function Uc(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Fc(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Lc(e,t,n){return u(await c.post(`/projects/${e}/approvals/${t}`,{decision:n}))}async function Bc(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Gc(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function Nc(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Wc(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Kc(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function Hc(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function zc(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}async function Vc(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function Jc(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Xc(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Qc(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var ri=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Tt=(e,t)=>`${ri(e)}/${encodeURIComponent(t)}`,Yc=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Zc(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${ri(e)}${n}`))}async function el(e,t){return u(await c.post(ri(e),t))}async function tl(e,t,n){return u(await c.put(`${Tt(e,t)}/value`,{value:n}))}async function nl(e,t){return u(await c.delete(Tt(e,t)))}async function rl(e,t,n,r){return u(await c.put(`${Tt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function sl(e,t,n,r){return u(await c.delete(`${Tt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function il(e,t,n,r){return u(await c.put(`${Tt(e,t)}/access`,{mode:n,user_ids:r}))}async function ol(e,t,n){return u(await c.get(Yc(e,t,n)))}async function al(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function cl(e,t,n,r){return u(await c.put(Yc(e,t,n),{secret_ids:r}))}function Pn(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function si(e){return u(await c.get(Pn(e,"catalog"))).connectors??[]}async function Sn(e){let t=[];for(let n of await si(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 ll(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),i=[],o=[];for(let a of await Sn(e)){let p=`${a.tool} ${a.description}`.toLowerCase();!r||p.includes(r)?i.push(a):s.every(g=>p.includes(g))&&o.push(a)}return[...i,...o].slice(0,n.limit??20)}async function ul(e,t){return(await Sn(e)).find(n=>n.tool===t)??null}function dh(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 pl(e,t,n={},r={}){let{connector:s,action:i}=dh(t),o=r.account?.trim();return u(await c.post(Pn(e,"call"),{connector:s,action:i,args:n,...o?{account:o}:{}}))}async function dl(e,t){let n=await c.get(Pn(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function gh(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 mh(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 gl(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 i={"Content-Type":s,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(i["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(i["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let o=mh($().backendUrl),a=Pn(e,"attachments"),p=await q(`${o}${a}`,{method:"POST",headers:i,body:t},{timeoutMs:6e4}),g=await p.text(),m=null;if(g)try{m=JSON.parse(g)}catch{m=g}if(!p.ok)throw new S(gh(m,p.status),{status:p.status,code:String(m&&typeof m=="object"?m.code??p.status:p.status),details:m,response:p,endpoint:a});return m}function NA(e){if(e.owner_type!=="project")return!1;let t=e.shared_with??[];return t.length===0||t.some(n=>n.principal_type==="project")}async function ml(e){return u(await c.get(`/projects/${e}/connections`))}async function fl(e){return u(await c.get(`/projects/${e}/connections/all`))}async function yl(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function hl(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function bl(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function he(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function WA(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function KA(e,t,n){return u(await c.put(he(e,t,"application"),n))}async function HA(e,t){return u(await c.get(he(e,t,"application")))}async function zA(e,t,n){return u(await c.post(he(e,t,"discover"),n))}async function VA(e,t,n={}){return u(await c.post(he(e,t,"discover-resource"),n))}async function JA(e,t,n){return u(await c.post(he(e,t,"register"),n))}async function XA(e,t,n){return u(await c.post(he(e,t,"authorize"),n))}async function QA(e,t,n){return u(await c.post(he(e,t,"device"),n))}async function YA(e,t,n){return u(await c.post(he(e,t,`device/${encodeURIComponent(n)}`),{}))}async function ZA(e,t){return u(await c.get(he(e,t,"status")))}async function _l(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function xl(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function wl(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function kl(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Pl(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Sl(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function vl(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Al(e){return u(await c.get(`/connectors/projects/${e}/connectors`,{showErrors:!1}))}async function Rl(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Cl(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Tl(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Il(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function El(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function jl(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function eR(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function tR(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Ml(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function $l(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function fh(e,t,n={}){return u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,n.owner?{owner:n.owner}:{}))}var Ol=fh;async function nR(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Dl(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function ql(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function Ul(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Fl(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 i=s.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/apps${i?`?${i}`:""}`))}async function Ll(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function rR(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=u(await c.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let i=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:i,hasMore:!!i}}async function sR(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function ii(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 i=s.toString();return u(await c.get(`/connectors/projects/${e}/discover/connectors${i?`?${i}`:""}`))}async function Bl(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function oi(e,t){let n=new URLSearchParams({id:t});return u(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var iR=ii,oR=oi;async function Gl(){return u(await c.get("/connectors/connect-status"))}async function Nl(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function aR(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function yh(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Wl=yh;async function Kl(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function Hl(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function zl(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Vl(e){return u(await c.get(`/projects/${e}/snapshots`))}async function ai(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Jl(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Xl(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Ql(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function Yl(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Zl(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function eu(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function tu(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function nu(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function ru(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await c.get(`/projects/${e}/files/search?${r.toString()}`))}async function su(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await c.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}async function iu(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",i=await pt(),o=`${$().backendUrl||""}/projects/${e}/files/archive${s}`,a=await fetch(o,{method:"GET",headers:i?{Authorization:`Bearer ${i}`}:{}});if(!a.ok){let p=await a.text().catch(()=>"");throw new Error(p||`Failed to download (HTTP ${a.status})`)}return await a.blob()}async function ou(e){return u(await c.get(`/projects/${e}/branches`))}async function au(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/commits${r}`))}async function cu(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function lu(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function uu(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await c.get(`/projects/${e}/files/history?${r.toString()}`))}async function pu(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await c.get(`/projects/${e}/version-diff?${n.toString()}`))}async function du(e,t){let n=t?`?status=${t}`:"";return u(await c.get(`/projects/${e}/change-requests${n}`,{showErrors:!1,timeout:15e3}))}async function gu(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function mu(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function fu(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function yu(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function hu(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function bu(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function _u(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function xu(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function wu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}var ci=new Set;function vn(e){e&&ci.add(e)}function ku(e){return!!e&&ci.has(e)}function AR(e){e&&ci.delete(e)}function ER(e){let t=e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var jR=50,hh=200,MR=hh;function Pu(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 Su(e,t){let n=await c.get(`/projects/${e}/sessions${Pu(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function It(e,t){return u(await c.get(`/projects/${e}/sessions${Pu(t)}`))}async function vu(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}function $R(e,t=new Date){let n=null;for(let r of e)r.resource_type!=="transcript"||r.revoked_at||r.expires_at&&Date.parse(r.expires_at)<=t.getTime()||(!n||Date.parse(r.created_at)>Date.parse(n.created_at))&&(n=r);return n}async function Au(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function Ru(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Cu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Tu(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Et(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||vn(n?.session_id),n}async function Iu(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await c.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||vn(r.session.session_id),r}async function Eu(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return vn(n.session_id),n}async function li(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function ju(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 i=s.toString();return u(await c.get(`/projects/${e}/sessions/${t}/audit${i?`?${i}`:""}`,{showErrors:r?.showErrors}))}async function Mu(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function $u(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),u(await c.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Ou(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/turn`))}async function OR(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}async function Du(e,t,n){return u(await c.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 qu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Uu(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Fu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Lu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Bu(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function Gu(e,t){return u(await c.delete(`/projects/${e}/sessions/${t}`))}async function An(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Rn(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}))}async function Nu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function bh(e){let t=e.split(`
|
|
13
|
+
`);let _=ph(h);if(_){if(t(_),_.type==="error")throw new S(_.error,{status:_.status,code:_.code});_.type==="done"&&(a=_.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new Error("Provision stream ended without a result");return a}async function mA(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function ti(e,t){return u(await c.patch(`/projects/${e}`,t))}async function ic(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function oc(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function ac(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function fA(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function yA(e,t){throw W("updateTemplateWarmPool")}async function cc(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function hA(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function ni(e){return u(await c.delete(`/projects/${e}`))}async function bA(e,t){return Je(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function _A(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=Js(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 lc(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function uc(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function pc(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function dc(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function gc(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function mc(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await c.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function fc(e,t,n){let r=new URLSearchParams({account_id:e,installation_id:t,repo_full_name:n});return u(await c.get(`/projects/github/repository-branches?${r.toString()}`,{showErrors:!1}))}async function yc(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function hc(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function bc(e,t){let n=new URLSearchParams({account_id:e});return t&&n.set("installation_id",t),u(await c.delete(`/projects/github/installation?${n.toString()}`))}async function _c(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function xc(e){let t=new URLSearchParams,n=e?.search?.trim();n&&t.set("search",n),e?.limit!==void 0&&t.set("limit",String(e.limit));let r=t.toString();return u(await c.get(`/projects/git/backend/repositories${r?`?${r}`:""}`,{showErrors:!1}))}async function TA(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function wc(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function kc(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function Pc(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function Sc(e){return u(await c.get(`/projects/${e}/access`))}async function vc(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function Ac(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function IA(e){return"status"in e&&e.status==="invited"}async function Rc(e,t,n,r){return u(await c.post(`/projects/${e}/access/invite`,{email:t,role:n,...r!==void 0?{expires_at:r}:{}}))}async function Cc(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function Tc(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function Ic(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function Ec(e){return u(await c.get(`/projects/${e}/group-grants`))}async function jc(e,t,n,r){return u(await c.post(`/projects/${e}/group-grants`,r===void 0?{group_id:t,role:n}:{group_id:t,role:n,expires_at:r}))}async function Mc(e,t,n,r){return u(await c.patch(`/projects/${e}/group-grants/${t}`,r===void 0?{role:n}:{role:n,expires_at:r}))}async function $c(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function Oc(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function Dc(e,t){return u(await c.post(`/projects/${e}/resource-grants`,{resource_type:t.resourceType,resource_id:t.resourceId,principal_type:t.principalType,principal_id:t.principalId,...t.expiresAt!==void 0?{expires_at:t.expiresAt}:{}}))}async function qc(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function Uc(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Fc(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function Lc(e,t,n){return u(await c.post(`/projects/${e}/approvals/${t}`,{decision:n}))}async function Bc(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function Gc(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function Nc(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Wc(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Kc(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/start`,{sharing:n?.sharing,...n?.resourceLabel===void 0?{}:{resource_label:n.resourceLabel},...n?.resourceId===void 0?{}:{resource_id:n.resourceId}}))}async function Hc(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function zc(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}async function Vc(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function Jc(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Xc(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Qc(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var ri=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Tt=(e,t)=>`${ri(e)}/${encodeURIComponent(t)}`,Yc=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Zc(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${ri(e)}${n}`))}async function el(e,t){return u(await c.post(ri(e),t))}async function tl(e,t,n){return u(await c.put(`${Tt(e,t)}/value`,{value:n}))}async function nl(e,t){return u(await c.delete(Tt(e,t)))}async function rl(e,t,n,r){return u(await c.put(`${Tt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function sl(e,t,n,r){return u(await c.delete(`${Tt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function il(e,t,n,r){return u(await c.put(`${Tt(e,t)}/access`,{mode:n,user_ids:r}))}async function ol(e,t,n){return u(await c.get(Yc(e,t,n)))}async function al(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function cl(e,t,n,r){return u(await c.put(Yc(e,t,n),{secret_ids:r}))}function Pn(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function Sn(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`${Pn(e,"catalog")}${r}`)).connectors??[]}async function si(e){let t=[];for(let n of await Sn(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 ll(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),i=[],o=[];for(let a of await si(e)){let p=`${a.tool} ${a.description}`.toLowerCase();!r||p.includes(r)?i.push(a):s.every(g=>p.includes(g))&&o.push(a)}return[...i,...o].slice(0,n.limit??20)}async function ul(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await Sn(e,{slug:r,includeSchemas:!0})).find(i=>i.slug===r);if(!s)return null;for(let i of s.actions){let o=`${s.slug}.${i.path}`;if(o===t)return{tool:o,connector:s.slug,action:i.path,risk:i.risk,description:i.description||i.name,inputSchema:i.inputSchema}}return null}function dh(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 pl(e,t,n={},r={}){let{connector:s,action:i}=dh(t),o=r.account?.trim();return u(await c.post(Pn(e,"call"),{connector:s,action:i,args:n,...o?{account:o}:{}}))}async function dl(e,t){let n=await c.get(Pn(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function gh(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 mh(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 gl(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 i={"Content-Type":s,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(i["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(i["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let o=mh($().backendUrl),a=Pn(e,"attachments"),p=await q(`${o}${a}`,{method:"POST",headers:i,body:t},{timeoutMs:6e4}),g=await p.text(),m=null;if(g)try{m=JSON.parse(g)}catch{m=g}if(!p.ok)throw new S(gh(m,p.status),{status:p.status,code:String(m&&typeof m=="object"?m.code??p.status:p.status),details:m,response:p,endpoint:a});return m}function NA(e){if(e.owner_type!=="project")return!1;let t=e.shared_with??[];return t.length===0||t.some(n=>n.principal_type==="project")}async function ml(e){return u(await c.get(`/projects/${e}/connections`))}async function fl(e){return u(await c.get(`/projects/${e}/connections/all`))}async function yl(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function hl(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function bl(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function he(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function WA(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function KA(e,t,n){return u(await c.put(he(e,t,"application"),n))}async function HA(e,t){return u(await c.get(he(e,t,"application")))}async function zA(e,t,n){return u(await c.post(he(e,t,"discover"),n))}async function VA(e,t,n={}){return u(await c.post(he(e,t,"discover-resource"),n))}async function JA(e,t,n){return u(await c.post(he(e,t,"register"),n))}async function XA(e,t,n){return u(await c.post(he(e,t,"authorize"),n))}async function QA(e,t,n){return u(await c.post(he(e,t,"device"),n))}async function YA(e,t,n){return u(await c.post(he(e,t,`device/${encodeURIComponent(n)}`),{}))}async function ZA(e,t){return u(await c.get(he(e,t,"status")))}async function _l(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function xl(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function wl(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function kl(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Pl(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function Sl(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function vl(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function Al(e,t){let n=t?.includeSchemas===void 0?"":`?include_schemas=${t.includeSchemas}`;return u(await c.get(`/connectors/projects/${e}/connectors${n}`,{showErrors:!1}))}async function Rl(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function Cl(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function Tl(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function Il(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function El(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function jl(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function eR(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function tR(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function Ml(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function $l(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function fh(e,t,n={}){return u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,n.owner?{owner:n.owner}:{}))}var Ol=fh;async function nR(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function Dl(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function ql(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function Ul(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function Fl(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 i=s.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/apps${i?`?${i}`:""}`))}async function Ll(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/sections${r?`?${r}`:""}`))}async function rR(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=u(await c.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let i=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:i,hasMore:!!i}}async function sR(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/connect/sections${r?`?${r}`:""}`))}async function ii(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 i=s.toString();return u(await c.get(`/connectors/projects/${e}/discover/connectors${i?`?${i}`:""}`))}async function Bl(e,t){let n=new URLSearchParams;t?.perCategory&&n.set("perCategory",String(t.perCategory)),t?.maxCategories&&n.set("maxCategories",String(t.maxCategories));let r=n.toString();return u(await c.get(`/connectors/projects/${e}/discover/sections${r?`?${r}`:""}`))}async function oi(e,t){let n=new URLSearchParams({id:t});return u(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var iR=ii,oR=oi;async function Gl(){return u(await c.get("/connectors/connect-status"))}async function Nl(e,t,n){let r=typeof n=="string"?{value:n}:n;return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`,r))}async function aR(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function yh(e,t,n={}){let r={};return n.owner&&(r.owner=n.owner),n.connectionId&&(r.connection_id=n.connectionId),u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect/finalize`,r))}var Wl=yh;async function Kl(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function Hl(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function zl(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Vl(e){return u(await c.get(`/projects/${e}/snapshots`))}async function ai(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Jl(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Xl(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Ql(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function Yl(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function Zl(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function eu(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function tu(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function nu(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path);let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/files${r}`,{showErrors:!1}))}async function ru(e,t,n){let r=new URLSearchParams({q:t});return n?.content&&r.set("content","1"),n?.ref&&r.set("ref",n.ref),n?.limit&&r.set("limit",String(n.limit)),u(await c.get(`/projects/${e}/files/search?${r.toString()}`))}async function su(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await c.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}async function iu(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",i=await pt(),o=`${$().backendUrl||""}/projects/${e}/files/archive${s}`,a=await fetch(o,{method:"GET",headers:i?{Authorization:`Bearer ${i}`}:{}});if(!a.ok){let p=await a.text().catch(()=>"");throw new Error(p||`Failed to download (HTTP ${a.status})`)}return await a.blob()}async function ou(e,t){let n=new URLSearchParams;t?.q&&n.set("q",t.q),t?.limit!=null&&n.set("limit",String(t.limit)),t?.includeSessionBranches!==void 0&&n.set("include_session_branches",String(t.includeSessionBranches));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/branches${r}`))}async function au(e,t){let n=new URLSearchParams;t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),t?.limit!=null&&n.set("limit",String(t.limit)),t?.skip!=null&&n.set("skip",String(t.skip));let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`/projects/${e}/commits${r}`))}async function cu(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function lu(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let s=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${s}`))}async function uu(e,t,n){let r=new URLSearchParams({path:t});return n?.ref&&r.set("ref",n.ref),n?.limit!=null&&r.set("limit",String(n.limit)),n?.skip!=null&&r.set("skip",String(n.skip)),u(await c.get(`/projects/${e}/files/history?${r.toString()}`))}async function pu(e,t){let n=new URLSearchParams({from:t.from,into:t.into});return u(await c.get(`/projects/${e}/version-diff?${n.toString()}`))}async function du(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit));let s=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function gu(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function mu(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function fu(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function yu(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function hu(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function bu(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function _u(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function xu(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function wu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}var ci=new Set;function vn(e){e&&ci.add(e)}function ku(e){return!!e&&ci.has(e)}function AR(e){e&&ci.delete(e)}function ER(e){let t=e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var jR=50,hh=200,MR=hh;function Pu(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 Su(e,t){let n=await c.get(`/projects/${e}/sessions${Pu(t)}`);return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function It(e,t){return u(await c.get(`/projects/${e}/sessions${Pu(t)}`))}async function vu(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}function $R(e,t=new Date){let n=null;for(let r of e)r.resource_type!=="transcript"||r.revoked_at||r.expires_at&&Date.parse(r.expires_at)<=t.getTime()||(!n||Date.parse(r.created_at)>Date.parse(n.created_at))&&(n=r);return n}async function Au(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function Ru(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Cu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Tu(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Et(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return t?.initial_prompt||vn(n?.session_id),n}async function Iu(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await c.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||vn(r.session.session_id),r}async function Eu(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return vn(n.session_id),n}async function li(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function ju(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 i=s.toString();return u(await c.get(`/projects/${e}/sessions/${t}/audit${i?`?${i}`:""}`,{showErrors:r?.showErrors}))}async function Mu(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let s=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/transcript${s?`?${s}`:""}`))}async function $u(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),u(await c.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Ou(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/turn`))}async function OR(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}async function Du(e,t,n){return u(await c.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 qu(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Uu(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Fu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Lu(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Bu(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function Gu(e,t){return u(await c.delete(`/projects/${e}/sessions/${t}`))}async function An(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Rn(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}))}async function Nu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function bh(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
15
|
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function Wu(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function Ku(e,t,n,r,s={}){let i=await c.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,s);if(!i.ok){let m=await i.json().catch(()=>null);throw new S(m?.error||`Reload failed: HTTP ${i.status}`,{status:i.status,code:m?.code,data:m})}let o=i.body?.getReader();if(!o)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,p="",g=null;try{for(;;){let{done:m,value:h}=await o.read();if(m)break;p+=a.decode(h,{stream:!0});let _=p.indexOf(`
|
|
16
16
|
|
|
17
17
|
`);for(;_!==-1;){let w=p.slice(0,_);p=p.slice(_+2),_=p.indexOf(`
|
|
18
18
|
|
|
19
19
|
`);let A=bh(w);if(A){if(r(A),A.type==="error")throw new S(A.error,{status:A.status,code:A.code,data:{reason:A.reason}});A.type==="done"&&(g=A.result)}}}}finally{o.cancel().catch(()=>{})}if(!g)throw new Error("Reload stream ended without a result");return g}async function Hu(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function zu(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function Vu(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{opencode_model:n}))}async function Ju(e){return u(await c.get(`/projects/${e}/triggers`))}async function Xu(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function Qu(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function Yu(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function Zu(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}async function ep(e,t){return u(await c.post(`/projects/${e}/triggers/${t}/fire`,{}))}var Ce=new Map;function ui(e,t){return`${e}::${t}`}function tp(e,t){Ce.delete(e),Ce.set(e,t)}function np(e,t){let n=ui(e,t),r=Ce.get(n);return r&&tp(n,r),r}function rp(e,t,n){let r=ui(e,t);if(!Ce.has(r)&&Ce.size>=512){let s=Ce.keys().next().value;s!==void 0&&Ce.delete(s)}tp(r,n)}function sp(e,t){Ce.delete(ui(e,t))}function KR(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 pi=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 HR(e){return e instanceof Error&&e.name==="SessionStartError"}function _h(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 pi(s,{status:n,code:r,terminal:!0}):null}async function Qe(e,t,n){let r=typeof n=="number"?n:n?.waitMs,s=typeof n=="number"?void 0:n?.repositoryMode,i=new URLSearchParams;r&&r>0&&i.set("wait_ms",String(Math.floor(r))),s&&i.set("repository_mode",s);let o=i.size>0?`?${i.toString()}`:"",a=await c.post(`/projects/${e}/sessions/${t}/start${o}`,{},{showErrors:!1});if(!a.success||!a.data){let m=_h(a.error);if(m&&!(m.status===404&&ku(t)))throw m;return null}let p=a.data,g=p.sandbox?.external_id;return p.stage==="ready"&&g&&p.opencode_session_id&&rp(e,t,{opencodeSessionId:p.opencode_session_id,runtimeUrl:sn(g),sandboxId:g}),p}function zR(e,t){return["session-start",e,t]}async function ip(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function op(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function ap(e,t){let n=new URLSearchParams({scope:t.scope,...t.agentName?{agentName:t.agentName}:{}}).toString();return u(await c.delete(`/projects/${e}/model-defaults?${n}`))}async function eC(e,t){return u(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}async function lp(e,t,n){let r=wh(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}function cp(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function xh(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function wh(e){let t=e.connectors_required?cp(e.connectors_required):void 0,n=e.connectors_personal?cp(e.connectors_personal):void 0;if(t&&n&&!xh(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 aC(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?di(n.block):null}}async function cC(e,t,n){let r=di(n,!0),s=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?di(s.block):null}}function di(e,t=!1){let n=Ph(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 up(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function kh(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Ph(e){let t=e.connectors_required?up(e.connectors_required):void 0,n=e.connectors_personal?up(e.connectors_personal):void 0;if(t&&n&&!kh(t,n))throw new Error("connectors_personal must match connectors_required when both fields are present");let r={...e};return delete r.connectors_personal,(t!==void 0||n!==void 0)&&(r.connectors_required=t??n),r}async function lC(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function pp(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}function gi(){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 Sh(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"team"}function gC(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??gi(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:Sh(r),label:s,sublabel:null,isGrandfathered:!1}}async function dp(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 c.get(`/billing/account-state${r}`,{showErrors:!1}),i=s.error?.status===404&&/billing is not enabled/i.test(s.error.message||"");if(s.error&&s.error.status!==401&&!i)throw s.error;return s.error?gi():s.data}async function gp(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 c.get(`/billing/account-state/minimal${r}`,{showErrors:!1}),i=s.error?.status===404&&/billing is not enabled/i.test(s.error.message||"");if(s.error&&s.error.status!==401&&!i)throw s.error;return s.error?gi():s.data}async function mp(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.limit!=null&&t.set("limit",String(e.limit)),e?.offset!=null&&t.set("offset",String(e.offset)),e?.typeFilter&&t.set("type_filter",Array.isArray(e.typeFilter)?e.typeFilter.join(","):e.typeFilter);let n=t.toString();return u(await c.get(`/billing/transactions${n?`?${n}`:""}`))}async function fp(e){let t=new URLSearchParams;e?.accountId&&t.set("account_id",e.accountId),e?.days!=null&&t.set("days",String(e.days));let n=t.toString();return u(await c.get(`/billing/transactions/summary${n?`?${n}`:""}`))}async function yp(){return u(await c.get("/billing/credit-breakdown"))}async function hp(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function bp(){return u(await c.get("/billing/tier-configurations"))}async function mC(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return Je(e,`/v1/billing/account-state${t}`)}async function _p(e){return u(await c.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 xp(e,t){return u(await c.post("/billing/confirm-checkout-session",{account_id:t,session_id:e}),"Failed to confirm checkout session")}async function wp(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function kp(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Pp(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Sp(e,t,n){return u(await c.post("/billing/schedule-downgrade",{account_id:n,target_tier_key:e,commitment_type:t}),"Failed to schedule downgrade")}async function vp(e){return u(await c.post("/billing/cancel-scheduled-change",{account_id:e}),"Failed to cancel scheduled change")}async function Ap(e,t){let n=new URLSearchParams({new_price_id:e});return t&&n.set("account_id",t),u(await c.get(`/billing/proration-preview?${n.toString()}`),"Failed to load proration preview")}async function Rp(e){return u(await c.post("/billing/purchase-credits",{amount:e.amount,account_id:e.accountId,success_url:e.successUrl,cancel_url:e.cancelUrl}),"Failed to purchase credits")}async function Cp(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/billing/auto-topup/settings${t}`),"Failed to load auto-topup settings")}async function Tp(e){return u(await c.post("/billing/auto-topup/configure",{account_id:e.accountId,enabled:e.enabled,threshold:e.threshold,amount:e.amount},{showErrors:!1}),"Failed to configure auto-topup")}async function fC(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/billing/auto-topup/setup-status${t}`,{timeout:8e3,showErrors:!1}),"Failed to load auto-topup setup status")}async function yC(e){return u(await c.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 hC(e){return u(await c.post("/billing/claim-per-seat",{account_id:e}),"Failed to switch to per-seat billing")}async function bC(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function Ip(e={}){let t=new URLSearchParams;e.start&&t.set("start",e.start),e.end&&t.set("end",e.end),(e.groupBy==="model"||e.groupBy==="provider"||e.groupBy==="day")&&t.set("group_by",e.groupBy),e.accountId&&t.set("account_id",e.accountId);let n=t.toString();return u(await c.get(`/usage${n?`?${n}`:""}`))}function mi(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Cn(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Tn(e){return e.size>0?`?${e}`:""}async function jp(e={}){let t=new URLSearchParams;return mi(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Cn(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/session-costs${Tn(t)}`))}async function fi(e,t={}){let n=new URLSearchParams;return mi(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Tn(n)}`))}async function SC(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Cn(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/cost-by-project${Tn(t)}`))}async function vC(e={}){let t=new URLSearchParams;return mi(t,e),e.sessionId&&t.set("session_id",e.sessionId),Cn(t,e),u(await c.get(`/usage/cost-summary${Tn(t)}`))}function Ep(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)}Cn(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`${$().backendUrl||""}${r}?${n}`}async function AC(e,t={}){let n=Ep(e==="projects"?"projects":"sessions",t),r=await pt(),s=await fetch(n,{method:"GET",headers:r?{Authorization:`Bearer ${r}`}:{}});if(!s.ok){let p=await s.text().catch(()=>"");throw new Error(p||`Failed to export CSV (HTTP ${s.status})`)}let i=s.headers.get("x-kortix-row-cap"),o=i!=null?Number(i):NaN;return{blob:await s.blob(),rowCap:Number.isFinite(o)?o:null}}async function Mp(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function IC(e){return Mp("slack",e)}function EC(e){return Mp("teams",e)}async function $p(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function jC(e){return $p("slack",e)}function MC(e){return $p("teams",e)}async function Op(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function Dp(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var vh={oauth_available:!1,install_url:null};async function qp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?vh:t.data}async function Up(e,t,n){return u(await c.post(`/projects/${encodeURIComponent(t)}/channels/${e}/oauth/complete`,{code:n.code,state:n.state},{showErrors:!1}),"Failed to finish the install")}function Fp(e,t){return Up("slack",e,t)}function Lp(e,t){return Up("teams",e,t)}async function Bp(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function Gp(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect")}async function Np(e,t){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/file?url=${encodeURIComponent(t)}`,{showErrors:!1}),"Failed to download Slack file")}async function Wp(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/file/upload`,{channel:t.channel,filename:t.filename,content_base64:t.contentBase64,comment:t.comment,thread_ts:t.threadTs},{showErrors:!1}),"Failed to upload Slack file")}function yi(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 Ah={provider:"agentmail",managed_available:!1};async function Kp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});return r.success&&r.data?yi(r.data):null}async function Hp(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Ah:t.data}async function zp(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return yi(n)}async function Vp(e,t){let n=t?`?connector_slug=${encodeURIComponent(t)}`:"",r=await c.delete(`/projects/${encodeURIComponent(e)}/channels/email/installation${n}`,{showErrors:!1});if(!r.success)throw new Error(r.error?.message??"Failed to disconnect email")}async function Jp(e,t,n){let r=u(await c.patch(`/projects/${encodeURIComponent(e)}/channels/email/installation`,{connector_slug:t??"kortix_email",sender_policy:n},{showErrors:!1}),"Failed to update email policy");return yi(r)}async function $C(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function OC(e,t,n){return u(await c.patch(`/projects/${encodeURIComponent(e)}/channels/bindings/${encodeURIComponent(t)}`,n,{showErrors:!1}),"Failed to update channel binding")}async function Xp(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Qp(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Yp(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Zp(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function ed(e,t){let n=new URLSearchParams;t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset)),t?.ok!==void 0&&n.set("ok",String(t.ok));let r=n.toString();return u(await c.get(`/projects/${e}/gateway/logs${r?`?${r}`:""}`),"Gateway request failed")}async function td(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function nd(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function rd(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function sd(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function id(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function od(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function ad(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function cd(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function ld(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function ud(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function pd(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function dd(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function gd(e,t,n,r,s){return u(await c.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...s&&Object.keys(s).length?{generationConfig:s}:{}}),"Gateway request failed")}async function FC(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function GC(){throw W("getReferralCode")}async function NC(){throw W("refreshReferralCode")}async function WC(e){throw W("validateReferralCode")}async function KC(){throw W("getReferralStats")}async function HC(e={}){throw W("listReferrals")}async function zC(e){throw W("sendReferralEmails")}function C(e){if(!e.success||e.data===void 0)throw e.error||new Error("Unexpected empty response");return e.data}function B(e){return c.get(e,{showErrors:!1})}async function md(e){return C(await B(`/accounts/${e}/iam/groups`)).groups}async function fd(e,t){return C(await B(`/accounts/${e}/iam/groups/${t}`))}async function yd(e,t){return C(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function hd(e,t,n){return C(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function bd(e,t){return C(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function _d(e,t){return C(await B(`/accounts/${e}/iam/groups/${t}/members`)).members}async function xd(e,t,n){return C(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function XC(e,t){return C(await B(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function wd(e,t,n){return C(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function QC(e,t){return C(await B(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function YC(e,t){let n=C(await B(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}async function ZC(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 B(`/accounts/${e}/iam/resource-grants${r?`?${r}`:""}`)).grants}async function eT(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 B(`/accounts/${e}/iam/policies${r?`?${r}`:""}`)).policies}async function tT(e,t){return C(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function nT(e,t,n){return C(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function rT(e,t){return C(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function sT(e,t){return C(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function iT(e,t){return C(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function kd(e){return C(await B(`/accounts/${e}/iam/roles`)).roles}async function Pd(e){return C(await B(`/accounts/${e}/iam/agent-identities`)).agents}async function Sd(e,t){return C(await B(`/accounts/${e}/iam/roles/${t}/permissions`))}async function oT(e){return C(await B(`/accounts/${e}/iam/actions`)).actions}async function vd(e,t){return C(await B(`/accounts/${e}/iam/roles/${t}/usage`))}async function Ad(e,t){return C(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function Rd(e,t,n){return C(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function Cd(e,t,n){return C(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function Td(e,t){return C(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function aT(e,t,n){return C(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function cT(e){return C(await B(`/accounts/${e}/iam/scim/tokens`)).tokens}async function lT(e,t){return C(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function uT(e,t){return C(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function pT(e){return C(await B(`/accounts/${e}/iam/mfa-required`))}async function dT(e){return C(await B(`/accounts/${e}/iam/mfa-required/preview`))}async function gT(e,t){return C(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function mT(e){return C(await B(`/accounts/${e}/iam/session-oversight`))}async function fT(e,t){return C(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function yT(e){return C(await B(`/accounts/${e}/iam/sso/provider`)).provider}async function hT(e,t){return C(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function bT(e,t){return C(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function _T(e){return C(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function xT(e){return C(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function wT(e){return C(await B(`/accounts/${e}/iam/sso/mappings`)).mappings}async function kT(e,t){return C(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function PT(e,t){return C(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function ST(e){return C(await B(`/accounts/${e}/iam/session-policy`))}async function vT(e,t){return C(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function AT(e){return C(await B(`/accounts/${e}/iam/sessions`)).sessions}async function RT(e,t){return C(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function CT(e){return C(await B(`/accounts/${e}/iam/pat-policy`))}async function TT(e,t){return C(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function IT(e){return C(await B(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function ET(e,t){return C(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function jT(e,t){return C(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function MT(e,t){return C(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function $T(e){return C(await B(`/accounts/${e}/audit/webhooks`)).webhooks}async function OT(e,t){return C(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function DT(e,t,n){return C(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function qT(e,t){return C(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function UT(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 B(`/accounts/${e}/audit${r?`?${r}`:""}`))}async function Id(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 B(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function Ed(e,t,n){return n.length===0?[]:C(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function FT(e){return C(await B(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function LT(e,t){return C(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function jd(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function Md(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function $d(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function Od(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function Dd(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function qd(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function Ud(e){return c.get(e,{showErrors:!1})}function Rh(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 Fd(e,t){return u(await Ud(`/accounts/${e}/iam/assignments${Rh(t)}`)).assignments}async function Ld(e,t){let n={principal_type:t.principal.type,principal_id:t.principal.id,scope_type:t.scope.type,scope_id:t.scope.type==="project"?t.scope.id:null};return t.roleId?n.role_id=t.roleId:n.role_key=t.roleKey,t.object&&(n.object_type=t.object.type,n.object_id=t.object.id),t.expiresAt!==void 0&&(n.expires_at=t.expiresAt),u(await c.post(`/accounts/${e}/iam/assignments`,n))}async function Bd(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function Gd(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await Ud(`/accounts/${e}/iam/permissions${n}`)).permissions}async function XT(){let e=await c.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function QT(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function YT(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function ZT(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function eI(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function sI(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function iI(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function oI(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function aI(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function cI(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function lI(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function uI(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var Nd="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function gI(e){throw W("getGoogleAuthUrl",Nd)}async function mI(e,t){throw W("convertPresentationToGoogleSlides",Nd)}async function Wd(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind);let r=n.toString();return u(await c.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function Kd(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function Hd(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function zd(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function Vd(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}var hi="call:";function _I(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(hi)&&e.length>hi.length?{type:"connector_call",executionId:e.slice(hi.length)}:{type:"review_item",reviewItemId:e}}function Ch(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function xI(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Ch(n.status)]+=1;return t}function wI(e){switch(e){case"approved":return"approve";case"rejected":return"reject";case"changes_requested":return"changes";case"done":return"answer";case"dismissed":return"dismiss";default:return null}}function bi(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Xd(e){let t=e.indexOf(".");return t<=0?bi(e):`(${bi(e.slice(0,t))}) ${bi(e.slice(t+1))}`}function Th(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var In=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},U=e=>typeof e=="string"&&e?e:void 0,pe=e=>Array.isArray(e)?e:void 0,Jd=e=>typeof e=="number"?e:0,Ih=e=>e.split(`
|
|
20
|
-
`).map(t=>t.trim()).filter(Boolean);function Eh(e,t){let n=In(e.advanced),r=U(e.description),s=pe(e.whatChanged)??(r?Ih(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:U(e.impact)??"",verification:pe(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:pe(e.conflicts),requestedChanges:pe(e.requested_changes)??[],advanced:{headRef:U(n.headRef)??U(e.head_ref)??"",baseRef:U(n.baseRef)??U(e.base_ref)??"",headSha:U(n.headSha)??U(e.head_sha)??U(e.head_commit_sha)??"",baseSha:U(n.baseSha)??U(e.base_sha)??"",additions:Jd(n.additions),deletions:Jd(n.deletions),files:pe(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function jh(e,t){let n=pe(e.actions);if(n)return{actions:n.map((p,g)=>({id:U(p.id)??`${t.review_item_id}-${g}`,title:U(p.title)??"Action",connector:U(p.connector)??"",action:U(p.action)??"",consequence:U(p.consequence)??"",risk:U(p.risk)??t.risk,icon:U(p.icon)??"generic",argsPreview:pe(p.argsPreview)??[],policySource:U(p.policySource)??"Requires approval",decided:p.decided==="approved"||p.decided==="denied"?p.decided:void 0}))};let r=U(e.action_path)??"",{connector:s,action:i}=Th(r),o=In(e.args_preview),a=Object.keys(o).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?Xd(r):t.title||"Run action",connector:s,action:i,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(o).map(([p,g])=>({key:p,value:g==="[redacted]"?"Hidden credential":typeof g=="string"?g:JSON.stringify(g,null,2)})),actionPath:r,rawArgsPreview:a?o:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,connectorRisk:U(e.risk)??null,policySource:"Requires approval"}]}}function Mh(e,t){return{artifactKind:U(e.artifactKind)??"document",artifactLabel:U(e.artifactLabel)??"Output",previewUrl:U(e.previewUrl)??U(e.preview_url),preview:U(e.preview),files:pe(e.files),note:U(e.note)??t.summary??""}}function $h(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:pe(e.options)??[]}}function Oh(e,t){return{note:U(e.note)??t.summary??"",children:pe(e.children)??[]}}function Dh(e){let t=In(e.detail);switch(e.kind){case"change":return Eh(t,e);case"approval":return jh(t,e);case"output":return Mh(t,e);case"decision":return $h(t,e);case"batch":return Oh(t,e)}}function qh(e,t){let n=typeof e.number=="number"?e.number:void 0,r=U(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function kI(e,t={}){let n=In(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,i=e.kind==="approval"?U(n.action_path):void 0,o=e.kind==="change"?qh(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:i?Xd(i):e.title,summary:o,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:Dh(e)}}async function Qd(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Yd(e){return u(await c.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Zd(e,t){let n=await c.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var _i=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function eg(e,t=""){return`${gt()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function tg(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 _i(s,t.status)}return r}async function CI(e){return tg(eg(e))}async function TI(e){return tg(eg(e,"/messages"))}async function ng(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await c.get(`/accounts/tokens${r}`))}async function rg(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await c.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function sg(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await c.delete(`/accounts/tokens/${e}${n}`))}async function ig(e){return u(await c.get(`/projects/${e}/cli-token`))}async function og(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function ag(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}async function cg(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 u(await c.get(`/accounts/${e}/audit${r?`?${r}`:""}`))}async function lg(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 u(await c.get(`/projects/${e}/audit${r?`?${r}`:""}`))}async function ug(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 u(await c.get(`/accounts/${e}/audit/export${r?`?${r}`:""}`))}async function pg(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function dg(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function gg(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function mg(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function fg(e,t){return u(await c.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function yg(e,t){return u(await c.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function FI(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function hg(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await c.get(`/marketplace/items${n}`))}async function bg(){return u(await c.get("/marketplace/marketplaces"))}async function _g(){return u(await c.get("/marketplace/marketplaces/featured"))}async function xg(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function wg(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function kg(){return u(await c.get("/marketplace/sources"))}async function Pg(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Sg(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function NI(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function HI(e){throw W("getTemplate")}async function zI(e,t){throw W("installTemplate")}async function vg(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Ag(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Rg(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Cg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Tg(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Ig(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Eg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function jg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Mg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function xi(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function wi(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function Uh(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function Fh(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 $g(e,t,n={}){let r=await Uh(t),s=n.mediaType??"application/gzip",i=await xi(e,{kind:"archive",media_type:s});if(!i.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>i.upload.max_bytes)throw new Error(`App artifact exceeds ${i.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let o=await fetch(i.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${o.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),wi(e,i.artifact.artifact_id,{sha256:await Fh(r),size_bytes:r.byteLength})}async function Og(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Dg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function qg(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Ug(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let i=s.size?`?${s.toString()}`:"";return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${i}`),"Failed to load App logs")}async function Fg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Lg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Bg(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}async function ki(e){return u(await c.get(`/projects/${e}/model-access`))}async function Pi(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}function tE(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:i,previewIsLinkOnly:o}=e;return t||n?!1:s?i&&!o:r==="error"}function Si(e){return typeof e=="string"&&e.trim().length>0}function Gg(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Si(t)||Si(n)||Si(r)}function Lh(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function En(e){if(!e)return!0;let t=Lh(e.items);return t?!t.some(Gg):!Gg(e)}function ce(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function sE(e){return ce(e)==="bash"}function iE(e){let t=ce(e);return t==="question"||t==="ask"}function oE(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Bh=new Set(["show","show_user"]);function Ng(e){return Bh.has(ce(e))}function aE(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Wg(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||vi(e))}function vi(e){let t=ce(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:En(e.state?.input)}var Gh=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Kg(e){return Gh.has(ce(e))}var Nh=50*1024*1024,Ai="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Wh=new RegExp(`^kortix-attachment://(${Ai})/(${Ai})/(${Ai})$`);function Ci(e){if(typeof e!="string")return null;let t=Wh.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function mE(e){return Ci(e)!==null}var Ri=new WeakMap;async function zg(e,t,n,r={}){if(n.size>Nh)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,i=r.attachmentId?void 0:Ri.get(n)?.get(s);if(i?.promise)return i.promise;let o=i??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let p=Ri.get(n)??new Map;p.set(s,o),Ri.set(n,p)}let a=new FormData;return a.append("attachment_id",o.id),a.append("file",n,n.name),o.promise=c.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(p=>{throw o.promise=void 0,p}),o.promise}async function Vg(e,t){let n=Ci(e);if(!n)throw new Error("Invalid attachment reference");let r=$().backendUrl.replace(/\/$/,""),s=await q(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new S("Could not load attachment",{status:s.status});return s.blob()}var Kh=new Set(["show","show_user"]);function Hh(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let i=e.indexOf(">",s);if(i===-1)return t;let o=e.indexOf("</file>",i+1);if(o===-1)return t;t.push(e.slice(s,i).trimStart()),n=o+7}}var Ye=e=>!!e&&typeof e=="object"&&!Array.isArray(e),jt=e=>typeof e=="string"&&e.length>0?e:null,Hg=e=>typeof e=="string"?jt(e.split("/").pop()):null;function jn(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function zh(e){if(Array.isArray(e))return e;if(typeof e!="string"||!e.trim())return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function fE(e){if(!Array.isArray(e))return[];let t=[],n=new Set,r=(s,i,o,a,p)=>{let g=Ci(s);!g||n.has(s)||(n.add(s),t.push({url:s,attachment_id:g.attachmentId,filename:i,mime:o,message_id:a,role:p}))};for(let s of e){if(!Ye(s)||!Ye(s.info)||!Array.isArray(s.parts))continue;let i=jt(s.info.id);if(!i)continue;let o=jt(s.info.role)??"unknown";for(let a of s.parts)if(Ye(a)){if(a.type==="file")r(a.url,jt(a.filename),jt(a.mime),i,o);else if(a.type==="text"&&typeof a.text=="string")for(let p of Hh(a.text))r(jn(p,"attachment"),jn(p,"filename")??Hg(jn(p,"path")),jn(p,"mime"),i,o);else if(a.type==="tool"&&typeof a.tool=="string"&&Kh.has(ce(a.tool))&&Ye(a.state)&&Ye(a.state.input)){let p=a.state.input;for(let g of[p,...zh(p.items)])Ye(g)&&r(g.attachment,Hg(g.path),null,i,o)}}}return t}var Mt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};function Vh(e){let t=ve(e?.backendUrl??$().backendUrl??"");if(!t)throw new Mt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);return t.endsWith("/v1")?t:`${t}/v1`}async function Y(e,t,n){let r=n?.fetch??$().fetch??((p,g)=>fetch(p,g)),s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let i=await r(`${Vh(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}:{}}),o=await i.text().catch(()=>""),a=null;try{a=o?JSON.parse(o):null}catch{a=o}if(!i.ok){let p=a&&typeof a=="object"?a:{};throw new Mt(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return a}function Ti(e,t){return Y("/auth/signup",{body:e},t)}function Ii(e,t){return Y("/auth/sign-in/password",{body:e},t)}function Ei(e,t){return Y("/auth/sign-in/magic-link",{body:e},t)}function ji(e,t){return Y("/auth/verify-otp",{body:e},t)}function Mi(e,t){return Y("/auth/sign-in/oauth",{body:e},t)}function $i(e,t){return Y("/auth/oauth/exchange",{body:e},t)}function $t(e,t){return Y("/auth/refresh",{body:e},t)}function Oi(e,t){return Y("/auth/password/reset",{body:e},t)}function Di(e,t,n){return Y("/auth/password/update",{body:e,bearer:t},n)}function qi(e,t){return Y("/auth/user",{bearer:e},t)}function Ui(e,t,n){return Y("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function Fi(e,t){return Y("/auth/sign-in/sso",{body:e},t)}var Li={enroll:(e,t,n)=>Y("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>Y(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>Y(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>Y(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function Bi(e,t={},n){return Y("/auth/sign-out",{body:t,bearer:e},n)}function Gi(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,i=!e.storage,o=null,a=null,p=0,g=new Set,m=P=>(P.expires_at??0)*1e3,h=P=>m(P)-t*1e3<=n();async function _(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let P of[...g])try{P(r)}catch{}try{e.onChange?.(r)}catch{}}async function w(){if(i)return r;if(!o){let P=p,M=(async()=>{let k=await e.storage.get();if(P===p&&k)try{let d=JSON.parse(k);d.session?.access_token&&d.session?.refresh_token&&(r=d.session,s=d.user??null)}catch{r=null}return i=!0,r})();o=M,M.then(()=>{o===M&&(o=null)},()=>{o===M&&(o=null)})}return o}async function A(){if(await w(),!r)return null;if(!a){let P=r.refresh_token,M=p,k=$t({refresh_token:P},e.request).then(async d=>(M!==p||(r=d.session,d.user&&(s=d.user),await _()),r)).catch(async d=>{if(M!==p)return r;let y=d&&typeof d=="object"&&"status"in d?d.status:0;if(y>=400&&y<500)return r=null,s=null,await _(),null;throw d}).finally(()=>{a===k&&(a=null)});a=k}return a}return{subscribe(P){return g.add(P),()=>{g.delete(P)}},current:()=>r,user:()=>s,load:w,async set(P,M){await w(),p+=1,a=null,r=P,M!==void 0&&(s=M),P||(s=null),await _()},async getToken(){return await w(),r?h(r)?(await A().catch(()=>r))?.access_token??null:r.access_token:null},refresh:A,async clear(){p+=1,a=null,r=null,s=null,i=!0,await _()}}}var Xh=["control_plane","provider_ingress","daemon","upstream_port"];function Jg(e){return typeof e=="string"&&Xh.includes(e)?e:null}function PE(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 Xg(e,t){let n=(e===void 0?ye():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await q(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),i=null;try{i=s?JSON.parse(s):null}catch{i=null}let o=i,a=Jg(r.headers.get("X-Kortix-Proxy-Hop"))??Jg(i?.hop),p=Number(r.headers.get("X-Kortix-Upstream-Status")),g=i?.upstream_status,m=Number.isFinite(p)&&p>0?p:typeof g=="number"?g:null;return{status:r.status,ok:r.ok,health:o,body:s,hop:a,upstreamStatus:m}}var Te={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};var Qg=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,Yg=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,Zg=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,em=new Set([22,4096,parseInt(Te.KORTIX_MASTER,10)]);function Qh(e){return Yg.test(e)}function Mn(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 Yh(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var Zh=new Set(["'",'"',"`","<","(","["]),eb=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function tb(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&&Zh.has(e[t]);)t++;for(;n>t&&eb.has(e[n-1]);)n--;return e.slice(t,n)}function nb(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var rb=/^\/proxy\/(\d{1,5})(\/.*)?$/,sb=/^\/(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 ib(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:sb.test(t.pathname)}catch{return!1}}function $n(e){if(!e)return null;let t=tb(Yh(e.trim())),n=im(t);if(n){let r=Mn(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 i=`${r.pathname||"/"}${r.search}${r.hash}`,o=parseInt(Te.KORTIX_MASTER,10);if(s===o){let p=r.pathname.match(rb);if(p){let g=parseInt(p[1],10);if(g>=1&&g<=65535)return s=g,i=Mn(`${p[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${i}`,port:s,path:i}}}let a=Mn(i);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=nb(e);return r&&r!==e?$n(r):null}}function ob(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 i=r.index,o=i+r[0].length;t.some(([p,g])=>i>=p&&o<=g)||t.push([i,o])}return t}function ab(e,t){return t.some(([n,r])=>e>=n&&e<r)}function cb(e){let t=[],n=new Set,r=ob(e);Qg.lastIndex=0;let s;for(;(s=Qg.exec(e))!==null;){let i=$n(s[0]);if(!i)continue;let{originalUrl:o,port:a,path:p}=i;a<1||a>65535||em.has(a)||n.has(o)||(n.add(o),t.push({originalUrl:o,port:a,path:p,startIndex:s.index,endIndex:s.index+o.length,inCodeBlock:ab(s.index,r)}))}return t}function RE(e){return cb(e).length>0}function lb(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function tm(e){return e.trim().toLowerCase().split("_").join("-")}function nm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function ub(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(tm(n.sandboxId));return`${nm(s)}${t}`}function pb(e){return e.sandboxId.trim().length>0}function De(e,t,n){let r=Mn(t);if(!pb(n))return fb(e,r);let s=ub(e,r,n);return s||(lb(n.apiBaseUrl)?`http://p${e}-${tm(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${nm(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function CE(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return De(3211,`/open?path=/workspace/${r}`,t)}function db(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function TE(e){return`http://localhost:3211${db(e)}`}function gb(){return"/health"}function IE(e){return De(3211,gb(),e)}function EE(e,t){return De(e,"/",t)}function mb(e){let t=$n(e);return!(!t||em.has(t.port)||ib(e))}function rm(e,t){if(!e)return e;let n=$n(e);return n?mb(n.originalUrl)?De(n.port,n.path,t):n.originalUrl:e}function fb(e,t="/"){return`http://localhost:${e}${t}`}var sm=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function im(e){let t=e.match(Yg);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(Zg);if(n){let s=443;try{let i=new URL(e);s=i.port?parseInt(i.port,10):i.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(sm);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 jE(e){try{let t=im(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function ME(e){return Qh(e)||Zg.test(e)||sm.test(e)}function $E(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Ot="/web-proxy/";function OE(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Ot}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,i=parseInt(Te.KORTIX_MASTER,10);return`${De(i,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function DE(e){try{let t=new URL(e),n=t.pathname.indexOf(Ot);if(n===-1)return null;let s=t.pathname.slice(n+Ot.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let i=s[1],o=s[2],a=s[3]||"/";return`${i}://${o}${a}${t.search}${t.hash}`}catch{return null}}function qE(e){try{return new URL(e).pathname.includes(Ot)}catch{return e.includes(Ot)}}function UE(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 FE(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 om="frontend";function On(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${om}] ${t}`,...n?[n]:[]);try{Oe().app.log({service:om,level:e,message:t,extra:n})}catch{}}var Ie={debug:(e,t)=>On("debug",e,t),info:(e,t)=>On("info",e,t),warn:(e,t)=>On("warn",e,t),error:(e,t)=>On("error",e,t)};function yb(e){return{type:"heartbeat-gap",gapMs:e}}function hb(e){switch(e.type){case"message.updated":return{type:"message.updated",sessionID:e.properties.sessionID,message:e.properties.info};case"message.removed":return{type:"message.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID};case"message.part.updated":return{type:"message.part.updated",sessionID:e.properties.sessionID,part:e.properties.part};case"message.part.removed":return{type:"message.part.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID,partID:e.properties.partID};case"session.status":return{type:"session.status",sessionID:e.properties.sessionID,status:e.properties.status};case"session.idle":return{type:"session.idle",sessionID:e.properties.sessionID};case"session.error":return{type:"session.error",sessionID:e.properties.sessionID,error:e.properties.error};case"question.asked":return{type:"question.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,questions:e.properties.questions,tool:e.properties.tool};case"question.replied":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"replied",answers:e.properties.answers};case"question.rejected":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"rejected"};case"permission.asked":return{type:"permission.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,permission:e.properties.permission,patterns:e.properties.patterns,tool:e.properties.tool};case"permission.replied":return{type:"permission.replied",sessionID:e.properties.sessionID,requestID:e.properties.requestID,reply:e.properties.reply};case"todo.updated":return{type:"todo.updated",sessionID:e.properties.sessionID,todos:e.properties.todos};case"server.connected":return{type:"connection",status:"connected"};default:return null}}var bb={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},_b=16,xb=8,wb=6e4,kb=5e3,Pb=250,Sb=1e3,vb=3e4,Ab=5,Rb=3e3,Cb=3e4,Tb=2e4,Ib=2e3,Eb=8;function jb(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function am(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 Dn=new WeakMap;function Mb(e,t,n){let r=t.timers??bb,s=t.connectTimeoutMs??Tb,i=t.heartbeatTimeoutMs??wb,o=t.maxConsecutiveHardFailures??Eb,a=new AbortController;function p(k,...d){for(let y of n){let l=k(y);if(l)try{l(...d)}catch(x){console.warn("[opencode-events] subscriber handler threw, skipping",x)}}}let g=r.now(),m=null,h=[],_,w=0,A=new Map,P=()=>{if(_&&r.clearTimeout(_),_=void 0,h.length===0)return;let k=h;h=[],A.clear(),w=r.now(),g=r.now();for(let d of k)d&&p(y=>y.onEvent,d.event)},M=()=>{if(_)return;let k=r.now()-w;_=r.setTimeout(P,Math.max(0,_b-k))};return(async()=>{let k=0,d=0;for(;!a.signal.aborted;){let y=!1,l=!1,x=!1,R,I,O=null,N=r.now(),E=new AbortController,K=am(a.signal);K.promise.then(()=>E.abort());try{let L=await new Promise((J,ie)=>{let Q=!1;I=r.setTimeout(()=>{Q||(Q=!0,Ie.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:s}),E.abort(),ie(new Error(`SSE connect timed out after ${s}ms`)))},s),e.global.event({signal:E.signal,sseDefaultRetryDelay:Rb,sseMaxRetryDelay:Cb,sseMaxRetryAttempts:1}).then(ae=>{Q||(Q=!0,r.clearTimeout(I),J(ae))},ae=>{Q||(Q=!0,r.clearTimeout(I),ie(ae))})}),{stream:X}=L;if(m){let J=r.now()-m.lastActivityAt,ie=m.eventful;m=null,(ie||J>kb)&&p(Q=>Q.onGapRehydrate,J)}g=r.now();let G=()=>{r.clearTimeout(R),R=r.setTimeout(()=>{Ie.warn("SSE heartbeat timeout, forcing reconnect"),E.abort()},i)};G();let se=r.now(),ke=X[Symbol.asyncIterator]();for(;!E.signal.aborted;){let J=ke.next().then(Pe=>({kind:"next",result:Pe}),Pe=>({kind:"error",error:Pe})),ie=am(E.signal),Q=await Promise.race([J,ie.promise.then(()=>({kind:"aborted"}))]);if(ie.cleanup(),Q.kind==="aborted")break;if(Q.kind==="error")throw Q.error;if(Q.result.done)break;y=!0,G();let ae=Q.result.value,it=ae&&typeof ae=="object"&&"payload"in ae?ae.payload:ae;if(!it?.type)continue;it.type!=="server.connected"&&(l=!0);let or=jb(it);if(or){let Pe=A.get(or);Pe!==void 0&&(h[Pe]=void 0),A.set(or,h.length)}h.push({type:it.type,event:it}),M(),!(r.now()-se<xb)&&(se=r.now(),await new Promise(Pe=>r.setTimeout(Pe,0)))}x=y}catch(L){if(a.signal.aborted)break;O=L;let X=String(L),G=X.includes("401")||X.includes("403")||X.includes("Unauthorized")||X.includes("Token refresh failed");if(Ie.error("SSE event stream error",{error:X,retryCount:k,isAuthError:G}),G)try{Us(),await qs(),Ie.info("SSE: refreshed auth token after auth error")}catch(se){Ie.error("SSE: failed to refresh auth token",{error:String(se)})}}finally{r.clearTimeout(R),r.clearTimeout(I),E.abort(),K.cleanup(),P()}if(a.signal.aborted)break;let F=r.now()-N,b=O?.cause?.status;if(d=!y&&(typeof b=="number"&&b>=400||F<Ib)?d+1:0,d>=o){Ie.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:d,lastError:String(O)}),p(L=>L.onParked,{consecutiveFailures:d,lastError:O});break}m={lastActivityAt:g,eventful:(m?.eventful??!1)||l},x?k=0:(k++,k>1&&Ie.warn("SSE event stream reconnecting",{retryCount:k}));let Z=x?Pb:Math.min(Sb*2**Math.min(k-1,Ab),vb);await new Promise(L=>{let X=r.setTimeout(L,Z),G=()=>{r.clearTimeout(X),L()};a.signal.addEventListener("abort",G,{once:!0})})}})(),{subscribers:n,teardown:()=>{a.abort(),_&&r.clearTimeout(_)}}}function Ni(e){let{client:t,onEvent:n,onGapRehydrate:r,onParked:s,signal:i}=e,o={onEvent:n,onGapRehydrate:r,onParked:s},a=Dn.get(t);a?a.subscribers.add(o):(a=Mb(t,e,new Set([o])),Dn.set(t,a));let p=a,g=!1,m=()=>{g||(g=!0,i&&i.removeEventListener("abort",h),p.subscribers.delete(o),p.subscribers.size===0&&(p.teardown(),Dn.get(t)===p&&Dn.delete(t)))},h=()=>m();return i&&(i.aborted?m():i.addEventListener("abort",h,{once:!0})),{close:m}}function $b(){return Oe()}var qn=new Map;function Ob(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Un=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 Db(e,t){cr(e,t);function n(d){try{return new URL(d)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(d,window.location.origin)}catch{return null}throw new S(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(d)}). 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(d){let y=$().backendUrl??e.backendUrl,l=80,x=n(y);return x&&(l=x.port?Number(x.port):x.protocol==="https:"?443:80),Yo({sandboxId:d,apiBaseUrl:y,backendPort:l})}let s={signUp:Ti,signInWithPassword:Ii,sendMagicLink:Ei,verifyOtp:ji,signInWithProvider:Mi,exchangeCode:$i,refresh:$t,resetPassword:Oi,updatePassword:Di,updateUserMetadata:Ui,signInWithSso:Fi,mfa:Li,user:qi,signOut:Bi,session:Gi},i={list:Ta,get:Ea,create:Ia,secretResources:{list:Zc,create:el,rotate:tl,remove:nl,grant:rl,revoke:sl,setAccess:il},updateName:ja,branding:{get:Ma,update:$a,uploadAsset:Oa,removeAsset:Da,reset:qa},leave:Ja,members:Ua,invite:Fa,removeMember:za,updateMemberRole:Va,invites:La,cancelInvite:Ba,resendInvite:Ga,tokens:{list:ng,create:rg,revoke:sg},audit:{log:cg,export:ug,webhooks:{list:pg,create:dg,update:gg,remove:mg}}},o={assignments:{list:Fd,create:Ld,revoke:Bd},permissions:{list:Gd,forRole:Sd},roles:{list:kd,create:Ad,update:Rd,setPermissions:Cd,remove:Td,usage:vd},groups:{list:md,get:fd,create:yd,update:hd,remove:bd,members:{list:_d,add:xd,remove:wd}},agentIdentities:Pd,oauthClients:{list:jd,get:Md,create:$d,update:Od,rotateSecret:Dd,remove:qd},can:Id,canBatch:Ed},a={accountState:dp,accountStateMinimal:gp,transactions:mp,transactionsSummary:fp,creditBreakdown:yp,usageHistory:hp,usageRollup:Ip,sessionCosts:{list:jp,get:fi},tierConfigurations:bp,checkout:{createSession:d=>_p(d),confirmSession:(d,y)=>xp(d,y)},subscription:{createPortalSession:(d,y)=>wp(d,y),cancel:(d,y)=>kp(d,y),reactivate:d=>Pp(d),scheduleDowngrade:(d,y,l)=>Sp(d,y,l),cancelScheduledChange:d=>vp(d),prorationPreview:(d,y)=>Ap(d,y)},credits:{purchase:d=>Rp(d),autoTopupSettings:d=>Cp(d),configureAutoTopup:d=>Tp(d)}},p={listMine:Na,describe:Wa,accept:Ka,decline:Ha},g={list:Xe,listForAccount:Ya,get:Qs,detail:Ys,create:nc,createRepo:rc,provision:sc,update:ti,archive:ni,llmCatalog:Zs,modelPicker:ei,modelAccess:ki,setModelAccess:Pi,sandboxHealth:ai,sandboxTemplates:zl,sessions:It,createSession:Et},m={linkRepository:lc,replaceProjectRepository:uc,getInstallation:pc,listInstallations:dc,listLinkableInstallations:gc,listRepositories:mc,listRepositoryBranches:fc,linkInstallation:hc,saveInstallation:yc,deleteInstallation:bc},h={get:_c,repositories:xc},_={list:Qd,create:Yd,revoke:Zd},w=Gl,A={items:d=>hg(d),item:d=>xg(d),itemFile:(d,y)=>wg(d,y),marketplaces:()=>bg(),featured:()=>_g(),sources:{list:()=>kg(),add:d=>Pg(d),remove:d=>Sg(d)}};function P(d){return{catalog:()=>si(d),tools:()=>Sn(d),search:(...y)=>ll(d,...y),describe:(...y)=>ul(d,...y),call:(...y)=>pl(d,...y),accounts:(...y)=>dl(d,...y),uploadAttachment:(...y)=>gl(d,...y)}}function M(d){let y={list:()=>ml(d),listAll:()=>fl(d),reconcile:(...l)=>yl(d,...l),reconcileMember:(...l)=>hl(d,...l),updateCredential:(...l)=>bl(d,...l),revoke:(...l)=>_l(d,...l),activate:(...l)=>xl(d,...l),setDefault:(...l)=>wl(d,...l),rename:(...l)=>kl(d,...l),share:(...l)=>Pl(d,...l),pipedreamConnect:(...l)=>Sl(d,...l),pipedreamFinalize:(...l)=>vl(d,...l)};return{attachments:{upload:(...l)=>kn(d,...l),delete:(...l)=>Ct(d,...l),createController:l=>Ca(d,l)},get:l=>Qs(d,l),detail:()=>Ys(d),audit:l=>lg(d,l),update:l=>ti(d,l),archive:()=>ni(d),llmCatalog:()=>Zs(d),modelPicker:()=>ei(d),modelAccess:()=>ki(d),setModelAccess:l=>Pi(d,l),sandboxHealth:()=>ai(d),onboardingComplete:(...l)=>cc(d,...l),apps:{list:()=>vg(d),create:l=>Ag(d,l),get:l=>Rg(d,l),update:(...l)=>Cg(d,...l),access:{get:(...l)=>Ig(d,...l),update:(...l)=>jg(d,...l),session:(...l)=>Mg(d,...l),agents:l=>Eg(d,l)},remove:l=>Tg(d,l),artifacts:{register:l=>xi(d,l),uploadArchive:(...l)=>$g(d,...l),finalize:(...l)=>wi(d,...l)},deployments:{create:(...l)=>Og(d,...l),list:l=>Dg(d,l),get:(...l)=>qg(d,...l),logs:(...l)=>Ug(d,...l)},start:l=>Fg(d,l),stop:l=>Lg(d,l),rollback:(...l)=>Bg(d,...l)},tokens:{list:()=>ig(d),create:l=>og(d,l),revoke:l=>ag(d,l)},setupLinks:{requestSecret:l=>fg(d,l),requestConnector:l=>yg(d,l)},validateManifest:l=>ec(d,l),gitToken:()=>tc(d),secrets:{list:()=>Bc(d),upsert:l=>Gc(d,l),setStrategy:(...l)=>Nc(d,...l),broker:(...l)=>Wc(d,...l),remove:l=>Jc(d,l),setPersonal:(...l)=>Xc(d,...l),removePersonal:l=>Qc(d,l),setGitCredential:l=>Vc(d,l),startProviderOAuth:(...l)=>Kc(d,...l),pollProviderOAuth:(...l)=>Hc(d,...l),removeProviderOAuth:l=>zc(d,l)},access:{list:()=>Sc(d),invite:(...l)=>Rc(d,...l),update:(...l)=>vc(d,...l),revoke:l=>Ac(d,l),pendingInvites:()=>Cc(d),resendInvite:(...l)=>Ic(d,...l),revokeInvite:(...l)=>Tc(d,...l),requests:()=>wc(d),approveRequest:(...l)=>kc(d,...l),rejectRequest:(...l)=>Pc(d,...l),groupGrants:()=>Ec(d),attachGroupGrant:(...l)=>jc(d,...l),updateGroupGrant:(...l)=>Mc(d,...l),detachGroupGrant:l=>$c(d,l),resourceGrants:{list:()=>Oc(d),create:l=>Dc(d,l),remove:l=>qc(d,l)}},connectors:{...P(d),list:()=>Al(d),config:(...l)=>Ml(d,...l),create:(...l)=>Dl(d,...l),remove:(...l)=>Ul(d,...l),sync:()=>Rl(d),auth:{discover:(...l)=>ql(d,...l)},setName:(...l)=>$l(d,...l),setCredentialMode:(...l)=>Cl(d,...l),setAuthorizationStrategy:(...l)=>Tl(d,...l),setCredential:(...l)=>Nl(d,...l),setSensitive:(...l)=>Il(d,...l),connections:y,policies:{get:(...l)=>El(d,...l),set:(...l)=>jl(d,...l)},pipedream:{listApps:(...l)=>Fl(d,...l),listSections:(...l)=>Ll(d,...l),connect:(...l)=>Ol(d,...l),finalize:(...l)=>Wl(d,...l)},discover:{list:(...l)=>ii(d,...l),sections:(...l)=>Bl(d,...l),detail:(...l)=>oi(d,...l)}},policies:{list:()=>Kl(d),set:(...l)=>Hl(d,...l)},triggers:{list:()=>Ju(d),create:(...l)=>Xu(d,...l),update:(...l)=>Qu(d,...l),remove:(...l)=>Yu(d,...l),fire:(...l)=>ep(d,...l),setActivation:(...l)=>Zu(d,...l)},files:{list:l=>nu(d,l),read:(l,x)=>su(d,l,x),search:(...l)=>ru(d,...l),archive:(...l)=>iu(d,...l),history:(...l)=>uu(d,...l)},git:{commits:()=>au(d),commit:l=>cu(d,l),commitDiff:l=>lu(d,l),branches:()=>ou(d),versionDiff:(...l)=>pu(d,...l),inviteCollaborator:(...l)=>Za(d,...l)},changeRequests:{list:()=>du(d),get:l=>gu(d,l),diff:l=>mu(d,l),mergePreview:l=>fu(d,l),open:(...l)=>yu(d,...l),merge:(...l)=>hu(d,...l),close:(...l)=>bu(d,...l),reopen:(...l)=>_u(d,...l),requestChanges:(...l)=>xu(d,...l)},sessions:{list:l=>It(d,l),listPage:l=>Su(d,l),create:l=>Et(d,l),ensureWarm:()=>Iu(d),claimWarm:l=>Eu(d,l)},review:{list:l=>Wd(d,l),get:l=>Kd(d,l),submit:l=>Hd(d,l),act:(...l)=>zd(d,...l),bulkAct:l=>Vd(d,l)},approvals:{list:l=>Uc(d,l),resolve:(...l)=>Lc(d,...l),sessionsNeedingInput:l=>Fc(d,l)},gateway:{logs:l=>ed(d,l),log:l=>td(d,l),overview:l=>nd(d,l),series:l=>rd(d,l),breakdown:l=>sd(d,l),sessions:l=>id(d,l),errors:l=>od(d,l),budgets:()=>ad(d),setBudget:l=>cd(d,l),deleteBudget:l=>ld(d,l),keys:()=>ud(d),createKey:l=>pd(d,l),revokeKey:l=>dd(d,l),routing:{get:()=>Xp(d),set:l=>Qp(d,l),reset:()=>Yp(d),preview:l=>Zp(d,l)},playground:(l,x,R)=>gd(d,l,x,R)},channels:{slack:{installation:()=>Op(d),connect:l=>Dp(d,l),mode:()=>qp(d),completeInstall:l=>Fp(d,l),manifest:()=>Bp(d),disconnect:()=>Gp(d),getFile:l=>Np(d,l),uploadFile:l=>Wp(d,l)},teams:{completeInstall:l=>Lp(d,l)},email:{installation:l=>Kp(d,l),mode:()=>Hp(d),connect:l=>zp(d,l),disconnect:l=>Vp(d,l),updatePolicy:(...l)=>Jp(d,...l)}},updateFeatureFlag:(...l)=>ic(d,...l),updateExperimentalFeature:(...l)=>oc(d,...l),modelDefaults:{get:()=>ip(d),set:l=>op(d,l),clear:l=>ap(d,l)},setDefaultAgent:l=>pp(d,l),sandbox:{list:()=>tu(d),snapshots:()=>Vl(d),rebuildSnapshot:l=>Jl(d,l),fixWithAgent:()=>Xl(d),createTemplate:l=>Ql(d,l),updateTemplate:(...l)=>Yl(d,...l),removeTemplate:l=>Zl(d,l),buildTemplate:l=>eu(d,l),setProvider:l=>ac(d,l)},setAgentScope:(...l)=>lp(d,...l),session:l=>k(d,l)}}function k(d,y){let l=null,x,R,I=null;async function O(){I||(I=li(d,y,{showErrors:!1}).then(b=>{let T=typeof b.metadata?.opencode_model=="string"?b.metadata.opencode_model.trim():"",D=T.indexOf("/"),Z=D>0&&D<T.length-1?{providerID:T.slice(0,D),modelID:T.slice(D+1)}:void 0,L=b.agent_name?.trim()||void 0;return{model:Z,agent:L}}));try{return await I}catch(b){throw I=null,b}}function N(){if(l)return l;let b=np(d,y);return b&&(l=b),l}async function E(b){let T=N();if(T)return T;let D=b?.readyTimeoutMs??18e4,Z=We($().backendUrl??e.backendUrl).catch(()=>null),L=`${d}
|
|
20
|
+
`).map(t=>t.trim()).filter(Boolean);function Eh(e,t){let n=In(e.advanced),r=U(e.description),s=pe(e.whatChanged)??(r?Ih(r):t.summary?[t.summary]:[]);return{crId:U(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:U(e.impact)??"",verification:pe(e.verification)??[],previewUrl:U(e.previewUrl)??U(e.preview_url),conflicts:pe(e.conflicts),requestedChanges:pe(e.requested_changes)??[],advanced:{headRef:U(n.headRef)??U(e.head_ref)??"",baseRef:U(n.baseRef)??U(e.base_ref)??"",headSha:U(n.headSha)??U(e.head_sha)??U(e.head_commit_sha)??"",baseSha:U(n.baseSha)??U(e.base_sha)??"",additions:Jd(n.additions),deletions:Jd(n.deletions),files:pe(n.files)??[],mergeMode:U(n.mergeMode)??"merge"}}}function jh(e,t){let n=pe(e.actions);if(n)return{actions:n.map((p,g)=>({id:U(p.id)??`${t.review_item_id}-${g}`,title:U(p.title)??"Action",connector:U(p.connector)??"",action:U(p.action)??"",consequence:U(p.consequence)??"",risk:U(p.risk)??t.risk,icon:U(p.icon)??"generic",argsPreview:pe(p.argsPreview)??[],policySource:U(p.policySource)??"Requires approval",decided:p.decided==="approved"||p.decided==="denied"?p.decided:void 0}))};let r=U(e.action_path)??"",{connector:s,action:i}=Th(r),o=In(e.args_preview),a=Object.keys(o).length>0;return{actions:[{id:U(e.execution_id)??t.review_item_id,title:r?Xd(r):t.title||"Run action",connector:s,action:i,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(o).map(([p,g])=>({key:p,value:g==="[redacted]"?"Hidden credential":typeof g=="string"?g:JSON.stringify(g,null,2)})),actionPath:r,rawArgsPreview:a?o:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,connectorRisk:U(e.risk)??null,policySource:"Requires approval"}]}}function Mh(e,t){return{artifactKind:U(e.artifactKind)??"document",artifactLabel:U(e.artifactLabel)??"Output",previewUrl:U(e.previewUrl)??U(e.preview_url),preview:U(e.preview),files:pe(e.files),note:U(e.note)??t.summary??""}}function $h(e,t){return{question:U(e.question)??t.title??"",context:U(e.context),options:pe(e.options)??[]}}function Oh(e,t){return{note:U(e.note)??t.summary??"",children:pe(e.children)??[]}}function Dh(e){let t=In(e.detail);switch(e.kind){case"change":return Eh(t,e);case"approval":return jh(t,e);case"output":return Mh(t,e);case"decision":return $h(t,e);case"batch":return Oh(t,e)}}function qh(e,t){let n=typeof e.number=="number"?e.number:void 0,r=U(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function kI(e,t={}){let n=In(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,i=e.kind==="approval"?U(n.action_path):void 0,o=e.kind==="change"?qh(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:i?Xd(i):e.title,summary:o,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,detail:Dh(e)}}async function Qd(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Yd(e){return u(await c.post("/p/share",{sandbox_id:e.sandboxId,port:e.port,ttl:e.ttl,label:e.label}),"Failed to generate public URL")}async function Zd(e,t){let n=await c.delete(`/p/share/${encodeURIComponent(t)}?sandbox_id=${encodeURIComponent(e)}`);if(!n.success)throw new Error(n.error?.message??"Failed to revoke public link")}var _i=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function eg(e,t=""){return`${gt()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function tg(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 _i(s,t.status)}return r}async function CI(e){return tg(eg(e))}async function TI(e){return tg(eg(e,"/messages"))}async function ng(e,t){let n=new URLSearchParams;e&&n.set("account_id",e),t?.mine&&n.set("mine","true");let r=n.size>0?`?${n.toString()}`:"";return u(await c.get(`/accounts/tokens${r}`))}async function rg(e){let{accountId:t,expiresAt:n,projectId:r,name:s}=e;return u(await c.post("/accounts/tokens",{name:s,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function sg(e,t){let n=t?`?account_id=${encodeURIComponent(t)}`:"";return u(await c.delete(`/accounts/tokens/${e}${n}`))}async function ig(e){return u(await c.get(`/projects/${e}/cli-token`))}async function og(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function ag(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}async function cg(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 u(await c.get(`/accounts/${e}/audit${r?`?${r}`:""}`))}async function lg(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 u(await c.get(`/projects/${e}/audit${r?`?${r}`:""}`))}async function ug(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 u(await c.get(`/accounts/${e}/audit/export${r?`?${r}`:""}`))}async function pg(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function dg(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function gg(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function mg(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function fg(e,t){return u(await c.post(`/projects/${e}/secret-requests`,{names:t.names,labels:t.labels,descriptions:t.descriptions,scope:t.scope,expires_in_minutes:t.expiresInMinutes}),"Failed to mint secret-entry link")}async function yg(e,t){return u(await c.post(`/projects/${e}/connect-requests`,{slug:t.slug,...t.owner?{owner:t.owner}:{},...t.label?{label:t.label}:{},expires_in_minutes:t.expiresInMinutes}),"Failed to mint connect link")}async function FI(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function hg(e){let t=new URLSearchParams;e?.query&&t.set("query",e.query),e?.type&&t.set("type",e.type),e?.source&&t.set("source",e.source),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.offset!==void 0&&t.set("offset",String(e.offset));let n=t.toString()?`?${t.toString()}`:"";return u(await c.get(`/marketplace/items${n}`))}async function bg(){return u(await c.get("/marketplace/marketplaces"))}async function _g(){return u(await c.get("/marketplace/marketplaces/featured"))}async function xg(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function wg(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function kg(){return u(await c.get("/marketplace/sources"))}async function Pg(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Sg(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function NI(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function HI(e){throw W("getTemplate")}async function zI(e,t){throw W("installTemplate")}async function vg(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Ag(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Rg(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function Cg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Tg(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Ig(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Eg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/agents`),"Failed to load the agents with access to this App").agents}async function jg(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function Mg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function xi(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function wi(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function Uh(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function Fh(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 $g(e,t,n={}){let r=await Uh(t),s=n.mediaType??"application/gzip",i=await xi(e,{kind:"archive",media_type:s});if(!i.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>i.upload.max_bytes)throw new Error(`App artifact exceeds ${i.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let o=await fetch(i.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!o.ok){let a=await o.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${o.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),wi(e,i.artifact.artifact_id,{sha256:await Fh(r),size_bytes:r.byteLength})}async function Og(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Dg(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function qg(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Ug(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let i=s.size?`?${s.toString()}`:"";return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${i}`),"Failed to load App logs")}async function Fg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Lg(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Bg(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}async function ki(e){return u(await c.get(`/projects/${e}/model-access`))}async function Pi(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}function tE(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:i,previewIsLinkOnly:o}=e;return t||n?!1:s?i&&!o:r==="error"}function Si(e){return typeof e=="string"&&e.trim().length>0}function Gg(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Si(t)||Si(n)||Si(r)}function Lh(e){if(Array.isArray(e))return e.length>0?e:null;if(typeof e!="string"||!e.trim())return null;try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:null}catch{return null}}function En(e){if(!e)return!0;let t=Lh(e.items);return t?!t.some(Gg):!Gg(e)}function ce(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function sE(e){return ce(e)==="bash"}function iE(e){let t=ce(e);return t==="question"||t==="ask"}function oE(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Bh=new Set(["show","show_user"]);function Ng(e){return Bh.has(ce(e))}function aE(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Wg(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||vi(e))}function vi(e){let t=ce(e.tool);return t!=="show"&&t!=="show_user"||e.state?.status!=="completed"?!1:En(e.state?.input)}var Gh=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Kg(e){return Gh.has(ce(e))}var Nh=50*1024*1024,Ai="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Wh=new RegExp(`^kortix-attachment://(${Ai})/(${Ai})/(${Ai})$`);function Ci(e){if(typeof e!="string")return null;let t=Wh.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function mE(e){return Ci(e)!==null}var Ri=new WeakMap;async function zg(e,t,n,r={}){if(n.size>Nh)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,i=r.attachmentId?void 0:Ri.get(n)?.get(s);if(i?.promise)return i.promise;let o=i??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let p=Ri.get(n)??new Map;p.set(s,o),Ri.set(n,p)}let a=new FormData;return a.append("attachment_id",o.id),a.append("file",n,n.name),o.promise=c.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(p=>{throw o.promise=void 0,p}),o.promise}async function Vg(e,t){let n=Ci(e);if(!n)throw new Error("Invalid attachment reference");let r=$().backendUrl.replace(/\/$/,""),s=await q(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new S("Could not load attachment",{status:s.status});return s.blob()}var Kh=new Set(["show","show_user"]);function Hh(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let i=e.indexOf(">",s);if(i===-1)return t;let o=e.indexOf("</file>",i+1);if(o===-1)return t;t.push(e.slice(s,i).trimStart()),n=o+7}}var Ye=e=>!!e&&typeof e=="object"&&!Array.isArray(e),jt=e=>typeof e=="string"&&e.length>0?e:null,Hg=e=>typeof e=="string"?jt(e.split("/").pop()):null;function jn(e,t){let n=e.match(new RegExp(`(?:^|\\s)${t}="([^"]*)"`))?.[1];return n===void 0?null:n.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function zh(e){if(Array.isArray(e))return e;if(typeof e!="string"||!e.trim())return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function fE(e){if(!Array.isArray(e))return[];let t=[],n=new Set,r=(s,i,o,a,p)=>{let g=Ci(s);!g||n.has(s)||(n.add(s),t.push({url:s,attachment_id:g.attachmentId,filename:i,mime:o,message_id:a,role:p}))};for(let s of e){if(!Ye(s)||!Ye(s.info)||!Array.isArray(s.parts))continue;let i=jt(s.info.id);if(!i)continue;let o=jt(s.info.role)??"unknown";for(let a of s.parts)if(Ye(a)){if(a.type==="file")r(a.url,jt(a.filename),jt(a.mime),i,o);else if(a.type==="text"&&typeof a.text=="string")for(let p of Hh(a.text))r(jn(p,"attachment"),jn(p,"filename")??Hg(jn(p,"path")),jn(p,"mime"),i,o);else if(a.type==="tool"&&typeof a.tool=="string"&&Kh.has(ce(a.tool))&&Ye(a.state)&&Ye(a.state.input)){let p=a.state.input;for(let g of[p,...zh(p.items)])Ye(g)&&r(g.attachment,Hg(g.path),null,i,o)}}}return t}var Mt=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};function Vh(e){let t=ve(e?.backendUrl??$().backendUrl??"");if(!t)throw new Mt("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);return t.endsWith("/v1")?t:`${t}/v1`}async function Y(e,t,n){let r=n?.fetch??$().fetch??((p,g)=>fetch(p,g)),s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let i=await r(`${Vh(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}:{}}),o=await i.text().catch(()=>""),a=null;try{a=o?JSON.parse(o):null}catch{a=o}if(!i.ok){let p=a&&typeof a=="object"?a:{};throw new Mt(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return a}function Ti(e,t){return Y("/auth/signup",{body:e},t)}function Ii(e,t){return Y("/auth/sign-in/password",{body:e},t)}function Ei(e,t){return Y("/auth/sign-in/magic-link",{body:e},t)}function ji(e,t){return Y("/auth/verify-otp",{body:e},t)}function Mi(e,t){return Y("/auth/sign-in/oauth",{body:e},t)}function $i(e,t){return Y("/auth/oauth/exchange",{body:e},t)}function $t(e,t){return Y("/auth/refresh",{body:e},t)}function Oi(e,t){return Y("/auth/password/reset",{body:e},t)}function Di(e,t,n){return Y("/auth/password/update",{body:e,bearer:t},n)}function qi(e,t){return Y("/auth/user",{bearer:e},t)}function Ui(e,t,n){return Y("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function Fi(e,t){return Y("/auth/sign-in/sso",{body:e},t)}var Li={enroll:(e,t,n)=>Y("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>Y(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>Y(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>Y(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function Bi(e,t={},n){return Y("/auth/sign-out",{body:t,bearer:e},n)}function Gi(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,i=!e.storage,o=null,a=null,p=0,g=new Set,m=P=>(P.expires_at??0)*1e3,h=P=>m(P)-t*1e3<=n();async function _(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let P of[...g])try{P(r)}catch{}try{e.onChange?.(r)}catch{}}async function w(){if(i)return r;if(!o){let P=p,M=(async()=>{let k=await e.storage.get();if(P===p&&k)try{let d=JSON.parse(k);d.session?.access_token&&d.session?.refresh_token&&(r=d.session,s=d.user??null)}catch{r=null}return i=!0,r})();o=M,M.then(()=>{o===M&&(o=null)},()=>{o===M&&(o=null)})}return o}async function A(){if(await w(),!r)return null;if(!a){let P=r.refresh_token,M=p,k=$t({refresh_token:P},e.request).then(async d=>(M!==p||(r=d.session,d.user&&(s=d.user),await _()),r)).catch(async d=>{if(M!==p)return r;let y=d&&typeof d=="object"&&"status"in d?d.status:0;if(y>=400&&y<500)return r=null,s=null,await _(),null;throw d}).finally(()=>{a===k&&(a=null)});a=k}return a}return{subscribe(P){return g.add(P),()=>{g.delete(P)}},current:()=>r,user:()=>s,load:w,async set(P,M){await w(),p+=1,a=null,r=P,M!==void 0&&(s=M),P||(s=null),await _()},async getToken(){return await w(),r?h(r)?(await A().catch(()=>r))?.access_token??null:r.access_token:null},refresh:A,async clear(){p+=1,a=null,r=null,s=null,i=!0,await _()}}}var Xh=["control_plane","provider_ingress","daemon","upstream_port"];function Jg(e){return typeof e=="string"&&Xh.includes(e)?e:null}function PE(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 Xg(e,t){let n=(e===void 0?ye():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await q(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),i=null;try{i=s?JSON.parse(s):null}catch{i=null}let o=i,a=Jg(r.headers.get("X-Kortix-Proxy-Hop"))??Jg(i?.hop),p=Number(r.headers.get("X-Kortix-Upstream-Status")),g=i?.upstream_status,m=Number.isFinite(p)&&p>0?p:typeof g=="number"?g:null;return{status:r.status,ok:r.ok,health:o,body:s,hop:a,upstreamStatus:m}}var Te={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};var Qg=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,Yg=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,Zg=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,em=new Set([22,4096,parseInt(Te.KORTIX_MASTER,10)]);function Qh(e){return Yg.test(e)}function Mn(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 Yh(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var Zh=new Set(["'",'"',"`","<","(","["]),eb=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function tb(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&&Zh.has(e[t]);)t++;for(;n>t&&eb.has(e[n-1]);)n--;return e.slice(t,n)}function nb(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var rb=/^\/proxy\/(\d{1,5})(\/.*)?$/,sb=/^\/(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 ib(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:sb.test(t.pathname)}catch{return!1}}function $n(e){if(!e)return null;let t=tb(Yh(e.trim())),n=im(t);if(n){let r=Mn(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 i=`${r.pathname||"/"}${r.search}${r.hash}`,o=parseInt(Te.KORTIX_MASTER,10);if(s===o){let p=r.pathname.match(rb);if(p){let g=parseInt(p[1],10);if(g>=1&&g<=65535)return s=g,i=Mn(`${p[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${i}`,port:s,path:i}}}let a=Mn(i);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=nb(e);return r&&r!==e?$n(r):null}}function ob(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 i=r.index,o=i+r[0].length;t.some(([p,g])=>i>=p&&o<=g)||t.push([i,o])}return t}function ab(e,t){return t.some(([n,r])=>e>=n&&e<r)}function cb(e){let t=[],n=new Set,r=ob(e);Qg.lastIndex=0;let s;for(;(s=Qg.exec(e))!==null;){let i=$n(s[0]);if(!i)continue;let{originalUrl:o,port:a,path:p}=i;a<1||a>65535||em.has(a)||n.has(o)||(n.add(o),t.push({originalUrl:o,port:a,path:p,startIndex:s.index,endIndex:s.index+o.length,inCodeBlock:ab(s.index,r)}))}return t}function RE(e){return cb(e).length>0}function lb(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function tm(e){return e.trim().toLowerCase().split("_").join("-")}function nm(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function ub(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(tm(n.sandboxId));return`${nm(s)}${t}`}function pb(e){return e.sandboxId.trim().length>0}function De(e,t,n){let r=Mn(t);if(!pb(n))return fb(e,r);let s=ub(e,r,n);return s||(lb(n.apiBaseUrl)?`http://p${e}-${tm(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${nm(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function CE(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return De(3211,`/open?path=/workspace/${r}`,t)}function db(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function TE(e){return`http://localhost:3211${db(e)}`}function gb(){return"/health"}function IE(e){return De(3211,gb(),e)}function EE(e,t){return De(e,"/",t)}function mb(e){let t=$n(e);return!(!t||em.has(t.port)||ib(e))}function rm(e,t){if(!e)return e;let n=$n(e);return n?mb(n.originalUrl)?De(n.port,n.path,t):n.originalUrl:e}function fb(e,t="/"){return`http://localhost:${e}${t}`}var sm=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function im(e){let t=e.match(Yg);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(Zg);if(n){let s=443;try{let i=new URL(e);s=i.port?parseInt(i.port,10):i.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(sm);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 jE(e){try{let t=im(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function ME(e){return Qh(e)||Zg.test(e)||sm.test(e)}function $E(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Ot="/web-proxy/";function OE(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Ot}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,i=parseInt(Te.KORTIX_MASTER,10);return`${De(i,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function DE(e){try{let t=new URL(e),n=t.pathname.indexOf(Ot);if(n===-1)return null;let s=t.pathname.slice(n+Ot.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let i=s[1],o=s[2],a=s[3]||"/";return`${i}://${o}${a}${t.search}${t.hash}`}catch{return null}}function qE(e){try{return new URL(e).pathname.includes(Ot)}catch{return e.includes(Ot)}}function UE(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 FE(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 om="frontend";function On(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${om}] ${t}`,...n?[n]:[]);try{Oe().app.log({service:om,level:e,message:t,extra:n})}catch{}}var Ie={debug:(e,t)=>On("debug",e,t),info:(e,t)=>On("info",e,t),warn:(e,t)=>On("warn",e,t),error:(e,t)=>On("error",e,t)};function yb(e){return{type:"heartbeat-gap",gapMs:e}}function hb(e){switch(e.type){case"message.updated":return{type:"message.updated",sessionID:e.properties.sessionID,message:e.properties.info};case"message.removed":return{type:"message.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID};case"message.part.updated":return{type:"message.part.updated",sessionID:e.properties.sessionID,part:e.properties.part};case"message.part.removed":return{type:"message.part.removed",sessionID:e.properties.sessionID,messageID:e.properties.messageID,partID:e.properties.partID};case"session.status":return{type:"session.status",sessionID:e.properties.sessionID,status:e.properties.status};case"session.idle":return{type:"session.idle",sessionID:e.properties.sessionID};case"session.error":return{type:"session.error",sessionID:e.properties.sessionID,error:e.properties.error};case"question.asked":return{type:"question.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,questions:e.properties.questions,tool:e.properties.tool};case"question.replied":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"replied",answers:e.properties.answers};case"question.rejected":return{type:"question.answered",sessionID:e.properties.sessionID,requestID:e.properties.requestID,outcome:"rejected"};case"permission.asked":return{type:"permission.asked",sessionID:e.properties.sessionID,requestID:e.properties.id,permission:e.properties.permission,patterns:e.properties.patterns,tool:e.properties.tool};case"permission.replied":return{type:"permission.replied",sessionID:e.properties.sessionID,requestID:e.properties.requestID,reply:e.properties.reply};case"todo.updated":return{type:"todo.updated",sessionID:e.properties.sessionID,todos:e.properties.todos};case"server.connected":return{type:"connection",status:"connected"};default:return null}}var bb={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},_b=16,xb=8,wb=6e4,kb=5e3,Pb=250,Sb=1e3,vb=3e4,Ab=5,Rb=3e3,Cb=3e4,Tb=2e4,Ib=2e3,Eb=8;function jb(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function am(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 Dn=new WeakMap;function Mb(e,t,n){let r=t.timers??bb,s=t.connectTimeoutMs??Tb,i=t.heartbeatTimeoutMs??wb,o=t.maxConsecutiveHardFailures??Eb,a=new AbortController;function p(k,...d){for(let y of n){let l=k(y);if(l)try{l(...d)}catch(x){console.warn("[opencode-events] subscriber handler threw, skipping",x)}}}let g=r.now(),m=null,h=[],_,w=0,A=new Map,P=()=>{if(_&&r.clearTimeout(_),_=void 0,h.length===0)return;let k=h;h=[],A.clear(),w=r.now(),g=r.now();for(let d of k)d&&p(y=>y.onEvent,d.event)},M=()=>{if(_)return;let k=r.now()-w;_=r.setTimeout(P,Math.max(0,_b-k))};return(async()=>{let k=0,d=0;for(;!a.signal.aborted;){let y=!1,l=!1,x=!1,R,I,O=null,N=r.now(),E=new AbortController,K=am(a.signal);K.promise.then(()=>E.abort());try{let L=await new Promise((J,ie)=>{let Q=!1;I=r.setTimeout(()=>{Q||(Q=!0,Ie.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:s}),E.abort(),ie(new Error(`SSE connect timed out after ${s}ms`)))},s),e.global.event({signal:E.signal,sseDefaultRetryDelay:Rb,sseMaxRetryDelay:Cb,sseMaxRetryAttempts:1}).then(ae=>{Q||(Q=!0,r.clearTimeout(I),J(ae))},ae=>{Q||(Q=!0,r.clearTimeout(I),ie(ae))})}),{stream:X}=L;if(m){let J=r.now()-m.lastActivityAt,ie=m.eventful;m=null,(ie||J>kb)&&p(Q=>Q.onGapRehydrate,J)}g=r.now();let G=()=>{r.clearTimeout(R),R=r.setTimeout(()=>{Ie.warn("SSE heartbeat timeout, forcing reconnect"),E.abort()},i)};G();let se=r.now(),ke=X[Symbol.asyncIterator]();for(;!E.signal.aborted;){let J=ke.next().then(Pe=>({kind:"next",result:Pe}),Pe=>({kind:"error",error:Pe})),ie=am(E.signal),Q=await Promise.race([J,ie.promise.then(()=>({kind:"aborted"}))]);if(ie.cleanup(),Q.kind==="aborted")break;if(Q.kind==="error")throw Q.error;if(Q.result.done)break;y=!0,G();let ae=Q.result.value,it=ae&&typeof ae=="object"&&"payload"in ae?ae.payload:ae;if(!it?.type)continue;it.type!=="server.connected"&&(l=!0);let or=jb(it);if(or){let Pe=A.get(or);Pe!==void 0&&(h[Pe]=void 0),A.set(or,h.length)}h.push({type:it.type,event:it}),M(),!(r.now()-se<xb)&&(se=r.now(),await new Promise(Pe=>r.setTimeout(Pe,0)))}x=y}catch(L){if(a.signal.aborted)break;O=L;let X=String(L),G=X.includes("401")||X.includes("403")||X.includes("Unauthorized")||X.includes("Token refresh failed");if(Ie.error("SSE event stream error",{error:X,retryCount:k,isAuthError:G}),G)try{Us(),await qs(),Ie.info("SSE: refreshed auth token after auth error")}catch(se){Ie.error("SSE: failed to refresh auth token",{error:String(se)})}}finally{r.clearTimeout(R),r.clearTimeout(I),E.abort(),K.cleanup(),P()}if(a.signal.aborted)break;let F=r.now()-N,b=O?.cause?.status;if(d=!y&&(typeof b=="number"&&b>=400||F<Ib)?d+1:0,d>=o){Ie.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:d,lastError:String(O)}),p(L=>L.onParked,{consecutiveFailures:d,lastError:O});break}m={lastActivityAt:g,eventful:(m?.eventful??!1)||l},x?k=0:(k++,k>1&&Ie.warn("SSE event stream reconnecting",{retryCount:k}));let Z=x?Pb:Math.min(Sb*2**Math.min(k-1,Ab),vb);await new Promise(L=>{let X=r.setTimeout(L,Z),G=()=>{r.clearTimeout(X),L()};a.signal.addEventListener("abort",G,{once:!0})})}})(),{subscribers:n,teardown:()=>{a.abort(),_&&r.clearTimeout(_)}}}function Ni(e){let{client:t,onEvent:n,onGapRehydrate:r,onParked:s,signal:i}=e,o={onEvent:n,onGapRehydrate:r,onParked:s},a=Dn.get(t);a?a.subscribers.add(o):(a=Mb(t,e,new Set([o])),Dn.set(t,a));let p=a,g=!1,m=()=>{g||(g=!0,i&&i.removeEventListener("abort",h),p.subscribers.delete(o),p.subscribers.size===0&&(p.teardown(),Dn.get(t)===p&&Dn.delete(t)))},h=()=>m();return i&&(i.aborted?m():i.addEventListener("abort",h,{once:!0})),{close:m}}function $b(){return Oe()}var qn=new Map;function Ob(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Un=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 Db(e,t){cr(e,t);function n(d){try{return new URL(d)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(d,window.location.origin)}catch{return null}throw new S(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(d)}). 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(d){let y=$().backendUrl??e.backendUrl,l=80,x=n(y);return x&&(l=x.port?Number(x.port):x.protocol==="https:"?443:80),Yo({sandboxId:d,apiBaseUrl:y,backendPort:l})}let s={signUp:Ti,signInWithPassword:Ii,sendMagicLink:Ei,verifyOtp:ji,signInWithProvider:Mi,exchangeCode:$i,refresh:$t,resetPassword:Oi,updatePassword:Di,updateUserMetadata:Ui,signInWithSso:Fi,mfa:Li,user:qi,signOut:Bi,session:Gi},i={list:Ta,get:Ea,create:Ia,secretResources:{list:Zc,create:el,rotate:tl,remove:nl,grant:rl,revoke:sl,setAccess:il},updateName:ja,branding:{get:Ma,update:$a,uploadAsset:Oa,removeAsset:Da,reset:qa},leave:Ja,members:Ua,invite:Fa,removeMember:za,updateMemberRole:Va,invites:La,cancelInvite:Ba,resendInvite:Ga,tokens:{list:ng,create:rg,revoke:sg},audit:{log:cg,export:ug,webhooks:{list:pg,create:dg,update:gg,remove:mg}}},o={assignments:{list:Fd,create:Ld,revoke:Bd},permissions:{list:Gd,forRole:Sd},roles:{list:kd,create:Ad,update:Rd,setPermissions:Cd,remove:Td,usage:vd},groups:{list:md,get:fd,create:yd,update:hd,remove:bd,members:{list:_d,add:xd,remove:wd}},agentIdentities:Pd,oauthClients:{list:jd,get:Md,create:$d,update:Od,rotateSecret:Dd,remove:qd},can:Id,canBatch:Ed},a={accountState:dp,accountStateMinimal:gp,transactions:mp,transactionsSummary:fp,creditBreakdown:yp,usageHistory:hp,usageRollup:Ip,sessionCosts:{list:jp,get:fi},tierConfigurations:bp,checkout:{createSession:d=>_p(d),confirmSession:(d,y)=>xp(d,y)},subscription:{createPortalSession:(d,y)=>wp(d,y),cancel:(d,y)=>kp(d,y),reactivate:d=>Pp(d),scheduleDowngrade:(d,y,l)=>Sp(d,y,l),cancelScheduledChange:d=>vp(d),prorationPreview:(d,y)=>Ap(d,y)},credits:{purchase:d=>Rp(d),autoTopupSettings:d=>Cp(d),configureAutoTopup:d=>Tp(d)}},p={listMine:Na,describe:Wa,accept:Ka,decline:Ha},g={list:Xe,listForAccount:Ya,get:Qs,detail:Ys,create:nc,createRepo:rc,provision:sc,update:ti,archive:ni,llmCatalog:Zs,modelPicker:ei,modelAccess:ki,setModelAccess:Pi,sandboxHealth:ai,sandboxTemplates:zl,sessions:It,createSession:Et},m={linkRepository:lc,replaceProjectRepository:uc,getInstallation:pc,listInstallations:dc,listLinkableInstallations:gc,listRepositories:mc,listRepositoryBranches:fc,linkInstallation:hc,saveInstallation:yc,deleteInstallation:bc},h={get:_c,repositories:xc},_={list:Qd,create:Yd,revoke:Zd},w=Gl,A={items:d=>hg(d),item:d=>xg(d),itemFile:(d,y)=>wg(d,y),marketplaces:()=>bg(),featured:()=>_g(),sources:{list:()=>kg(),add:d=>Pg(d),remove:d=>Sg(d)}};function P(d){return{catalog:()=>Sn(d),tools:()=>si(d),search:(...y)=>ll(d,...y),describe:(...y)=>ul(d,...y),call:(...y)=>pl(d,...y),accounts:(...y)=>dl(d,...y),uploadAttachment:(...y)=>gl(d,...y)}}function M(d){let y={list:()=>ml(d),listAll:()=>fl(d),reconcile:(...l)=>yl(d,...l),reconcileMember:(...l)=>hl(d,...l),updateCredential:(...l)=>bl(d,...l),revoke:(...l)=>_l(d,...l),activate:(...l)=>xl(d,...l),setDefault:(...l)=>wl(d,...l),rename:(...l)=>kl(d,...l),share:(...l)=>Pl(d,...l),pipedreamConnect:(...l)=>Sl(d,...l),pipedreamFinalize:(...l)=>vl(d,...l)};return{attachments:{upload:(...l)=>kn(d,...l),delete:(...l)=>Ct(d,...l),createController:l=>Ca(d,l)},get:l=>Qs(d,l),detail:()=>Ys(d),audit:l=>lg(d,l),update:l=>ti(d,l),archive:()=>ni(d),llmCatalog:()=>Zs(d),modelPicker:()=>ei(d),modelAccess:()=>ki(d),setModelAccess:l=>Pi(d,l),sandboxHealth:()=>ai(d),onboardingComplete:(...l)=>cc(d,...l),apps:{list:()=>vg(d),create:l=>Ag(d,l),get:l=>Rg(d,l),update:(...l)=>Cg(d,...l),access:{get:(...l)=>Ig(d,...l),update:(...l)=>jg(d,...l),session:(...l)=>Mg(d,...l),agents:l=>Eg(d,l)},remove:l=>Tg(d,l),artifacts:{register:l=>xi(d,l),uploadArchive:(...l)=>$g(d,...l),finalize:(...l)=>wi(d,...l)},deployments:{create:(...l)=>Og(d,...l),list:l=>Dg(d,l),get:(...l)=>qg(d,...l),logs:(...l)=>Ug(d,...l)},start:l=>Fg(d,l),stop:l=>Lg(d,l),rollback:(...l)=>Bg(d,...l)},tokens:{list:()=>ig(d),create:l=>og(d,l),revoke:l=>ag(d,l)},setupLinks:{requestSecret:l=>fg(d,l),requestConnector:l=>yg(d,l)},validateManifest:l=>ec(d,l),gitToken:()=>tc(d),secrets:{list:()=>Bc(d),upsert:l=>Gc(d,l),setStrategy:(...l)=>Nc(d,...l),broker:(...l)=>Wc(d,...l),remove:l=>Jc(d,l),setPersonal:(...l)=>Xc(d,...l),removePersonal:l=>Qc(d,l),setGitCredential:l=>Vc(d,l),startProviderOAuth:(...l)=>Kc(d,...l),pollProviderOAuth:(...l)=>Hc(d,...l),removeProviderOAuth:l=>zc(d,l)},access:{list:()=>Sc(d),invite:(...l)=>Rc(d,...l),update:(...l)=>vc(d,...l),revoke:l=>Ac(d,l),pendingInvites:()=>Cc(d),resendInvite:(...l)=>Ic(d,...l),revokeInvite:(...l)=>Tc(d,...l),requests:()=>wc(d),approveRequest:(...l)=>kc(d,...l),rejectRequest:(...l)=>Pc(d,...l),groupGrants:()=>Ec(d),attachGroupGrant:(...l)=>jc(d,...l),updateGroupGrant:(...l)=>Mc(d,...l),detachGroupGrant:l=>$c(d,l),resourceGrants:{list:()=>Oc(d),create:l=>Dc(d,l),remove:l=>qc(d,l)}},connectors:{...P(d),list:()=>Al(d),config:(...l)=>Ml(d,...l),create:(...l)=>Dl(d,...l),remove:(...l)=>Ul(d,...l),sync:()=>Rl(d),auth:{discover:(...l)=>ql(d,...l)},setName:(...l)=>$l(d,...l),setCredentialMode:(...l)=>Cl(d,...l),setAuthorizationStrategy:(...l)=>Tl(d,...l),setCredential:(...l)=>Nl(d,...l),setSensitive:(...l)=>Il(d,...l),connections:y,policies:{get:(...l)=>El(d,...l),set:(...l)=>jl(d,...l)},pipedream:{listApps:(...l)=>Fl(d,...l),listSections:(...l)=>Ll(d,...l),connect:(...l)=>Ol(d,...l),finalize:(...l)=>Wl(d,...l)},discover:{list:(...l)=>ii(d,...l),sections:(...l)=>Bl(d,...l),detail:(...l)=>oi(d,...l)}},policies:{list:()=>Kl(d),set:(...l)=>Hl(d,...l)},triggers:{list:()=>Ju(d),create:(...l)=>Xu(d,...l),update:(...l)=>Qu(d,...l),remove:(...l)=>Yu(d,...l),fire:(...l)=>ep(d,...l),setActivation:(...l)=>Zu(d,...l)},files:{list:l=>nu(d,l),read:(l,x)=>su(d,l,x),search:(...l)=>ru(d,...l),archive:(...l)=>iu(d,...l),history:(...l)=>uu(d,...l)},git:{commits:()=>au(d),commit:l=>cu(d,l),commitDiff:l=>lu(d,l),branches:()=>ou(d),versionDiff:(...l)=>pu(d,...l),inviteCollaborator:(...l)=>Za(d,...l)},changeRequests:{list:()=>du(d),get:l=>gu(d,l),diff:l=>mu(d,l),mergePreview:l=>fu(d,l),open:(...l)=>yu(d,...l),merge:(...l)=>hu(d,...l),close:(...l)=>bu(d,...l),reopen:(...l)=>_u(d,...l),requestChanges:(...l)=>xu(d,...l)},sessions:{list:l=>It(d,l),listPage:l=>Su(d,l),create:l=>Et(d,l),ensureWarm:()=>Iu(d),claimWarm:l=>Eu(d,l)},review:{list:l=>Wd(d,l),get:l=>Kd(d,l),submit:l=>Hd(d,l),act:(...l)=>zd(d,...l),bulkAct:l=>Vd(d,l)},approvals:{list:l=>Uc(d,l),resolve:(...l)=>Lc(d,...l),sessionsNeedingInput:l=>Fc(d,l)},gateway:{logs:l=>ed(d,l),log:l=>td(d,l),overview:l=>nd(d,l),series:l=>rd(d,l),breakdown:l=>sd(d,l),sessions:l=>id(d,l),errors:l=>od(d,l),budgets:()=>ad(d),setBudget:l=>cd(d,l),deleteBudget:l=>ld(d,l),keys:()=>ud(d),createKey:l=>pd(d,l),revokeKey:l=>dd(d,l),routing:{get:()=>Xp(d),set:l=>Qp(d,l),reset:()=>Yp(d),preview:l=>Zp(d,l)},playground:(l,x,R)=>gd(d,l,x,R)},channels:{slack:{installation:()=>Op(d),connect:l=>Dp(d,l),mode:()=>qp(d),completeInstall:l=>Fp(d,l),manifest:()=>Bp(d),disconnect:()=>Gp(d),getFile:l=>Np(d,l),uploadFile:l=>Wp(d,l)},teams:{completeInstall:l=>Lp(d,l)},email:{installation:l=>Kp(d,l),mode:()=>Hp(d),connect:l=>zp(d,l),disconnect:l=>Vp(d,l),updatePolicy:(...l)=>Jp(d,...l)}},updateFeatureFlag:(...l)=>ic(d,...l),updateExperimentalFeature:(...l)=>oc(d,...l),modelDefaults:{get:()=>ip(d),set:l=>op(d,l),clear:l=>ap(d,l)},setDefaultAgent:l=>pp(d,l),sandbox:{list:()=>tu(d),snapshots:()=>Vl(d),rebuildSnapshot:l=>Jl(d,l),fixWithAgent:()=>Xl(d),createTemplate:l=>Ql(d,l),updateTemplate:(...l)=>Yl(d,...l),removeTemplate:l=>Zl(d,l),buildTemplate:l=>eu(d,l),setProvider:l=>ac(d,l)},setAgentScope:(...l)=>lp(d,...l),session:l=>k(d,l)}}function k(d,y){let l=null,x,R,I=null;async function O(){I||(I=li(d,y,{showErrors:!1}).then(b=>{let T=typeof b.metadata?.opencode_model=="string"?b.metadata.opencode_model.trim():"",D=T.indexOf("/"),Z=D>0&&D<T.length-1?{providerID:T.slice(0,D),modelID:T.slice(D+1)}:void 0,L=b.agent_name?.trim()||void 0;return{model:Z,agent:L}}));try{return await I}catch(b){throw I=null,b}}function N(){if(l)return l;let b=np(d,y);return b&&(l=b),l}async function E(b){let T=N();if(T)return T;let D=b?.readyTimeoutMs??18e4,Z=We($().backendUrl??e.backendUrl).catch(()=>null),L=`${d}
|
|
21
21
|
${y}`,X=qn.get(L);if(X)return l=await X,await Z,l;let G=(async()=>{let se=Date.now()+D,ke=()=>Math.max(0,se-Date.now()),J=await Qe(d,y,Math.min(3e4,ke()));for(;Date.now()<se&&(J==null||(J.stage==="provisioning"||J.stage==="starting")&&J.retriable);)await new Promise(ae=>setTimeout(ae,Math.min(1e3,ke()))),J=await Qe(d,y,Math.min(3e4,ke()));if(!J||J.stage!=="ready"||!J.sandbox||!J.opencode_session_id)throw new S(Ob(J),{code:"RUNTIME_UNAVAILABLE"});let ie=J.sandbox.external_id;if(!ie)throw new S("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let Q=sn(ie);return Wo(Q,ie),{opencodeSessionId:J.opencode_session_id,runtimeUrl:Q,sandboxId:ie}})();qn.set(L,G);try{return l=await G,await Z,l}finally{qn.get(L)===G&&qn.delete(L)}}function K(b){let T=N();if(!T)throw new Un(b);return T}function F(){l=null,sp(d,y)}return{get:b=>li(d,y,b),cost:()=>fi(y,{projectId:d}),update:b=>Bu(d,y,b),delete:()=>(F(),Gu(d,y)),start:(...b)=>Qe(d,y,...b),restart:()=>(F(),An(d,y)),stop:()=>(F(),Rn(d,y)),configState:()=>Nu(d,y),reloadConfig:b=>(F(),Wu(d,y,b)),reloadConfigStream:(...b)=>(F(),Ku(d,y,...b)),setSharing:b=>vu(d,y,b),previews:()=>Au(d,y),commit:b=>wu(d,y,b),publicShares:{list:()=>Ru(d,y),create:(...b)=>Cu(d,y,...b),revoke:(...b)=>Tu(d,y,...b)},audit:(b,T)=>ju(d,y,b,T),attachments:{upload:(b,T)=>zg(d,y,b,T),read:(b,T)=>Vg(`kortix-attachment://${d}/${y}/${b}`,T)},transcript:b=>Mu(d,y,b),transcriptSync:b=>$u(d,y,b),turn:()=>Ou(d,y),prompts:{create:b=>Du(d,y,b),list:()=>qu(d,y),remove:b=>Uu(d,y,b),retry:b=>Fu(d,y,b),hold:b=>Lu(d,y,b)},ensureReady:E,health:b=>Xg(N()?.runtimeUrl??null,b),previewUrl:(b,T="/")=>De(b,T,r(K("previewUrl").sandboxId)),proxyUrl:b=>rm(b,r(K("proxyUrl").sandboxId)),setModel:b=>{x=b},changeModel:async b=>{let T=await Vu(d,y,b);return I=null,T},scope:()=>Hu(d,y),providerSecretPool:{list:()=>al(d,y),get:b=>ol(d,y,b),set:(b,T)=>cl(d,y,b,T)},rescope:b=>zu(d,y,b),setAgent:b=>{R=b},send:async(b,T)=>{let{opencodeSessionId:D,runtimeUrl:Z}=await E(),L=T?.model??x,X=T?.agent??R,G=L&&X?{}:await O(),se=L??G.model,ke=X??G.agent;return Re(Z).session.prompt({sessionID:D,parts:[{type:"text",text:b}],...se?{model:se}:{},...ke?{agent:ke}:{}})},abort:async()=>{let{opencodeSessionId:b,runtimeUrl:T}=await E();return Re(T).session.abort({sessionID:b})},rewind:async b=>{let{opencodeSessionId:T,runtimeUrl:D}=await E();return Re(D).session.revert({sessionID:T,messageID:b})},restoreRewind:async()=>{let{opencodeSessionId:b,runtimeUrl:T}=await E();return Re(T).session.unrevert({sessionID:b})},stream:async b=>{let{runtimeUrl:T}=await E();return Ni({client:Re(T),onEvent:b.onEvent,onGapRehydrate:b.onGapRehydrate,signal:b.signal})},get runtime(){return Re(K("runtime").runtimeUrl)},files:{list:async b=>wt(b,(await E()).runtimeUrl),read:async b=>kt(b,(await E()).runtimeUrl),readBlob:async b=>Pt(b,(await E()).runtimeUrl),status:async()=>dn((await E()).runtimeUrl),findFiles:async(b,T)=>gn(b,T,(await E()).runtimeUrl),findText:async b=>mn(b,(await E()).runtimeUrl),upload:async(b,T,D,Z)=>St(b,T,D,(await E()).runtimeUrl,Z),write:async(b,T)=>hn(b,T,(await E()).runtimeUrl),create:async b=>fn(b,(await E()).runtimeUrl),copy:async(b,T)=>yn(b,T,(await E()).runtimeUrl),remove:async b=>Ve(b,(await E()).runtimeUrl),mkdir:async b=>vt(b,(await E()).runtimeUrl),rename:async(b,T)=>bn(b,T,(await E()).runtimeUrl)}}}return{config:e,auth:s,accounts:i,iam:o,accountInvites:p,projects:g,connectors:P(),project:M,session:k,github:m,gitBackend:h,billing:a,sandboxShares:_,connectStatus:w,marketplace:A,validateToken:Xa,runtime:$b}}function qb(){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 Ub(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Ze(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function Fb(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function Lb(e){if(Ze(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 Bb(e){let t=Ze(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function Gb(e,t){let n=Ze(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 Nb(e,t){let n=e.failed.find(i=>i.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(i=>i.id!==t)}}function Wb(e,t){return Ze(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 Kb(e,t,n){return Ze(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 Hb(e,t,n){let r=Ze(e);if(r.includes(t))return e;let s=e.pending.findIndex(g=>g.id===t);if(s===-1)return e;let i=r.length,o=Math.min(Math.max(n,i),e.pending.length-1);if(o===s)return e;let a=[...e.pending],[p]=a.splice(s,1);return a.splice(o,0,p),{...e,pending:a}}var cm={thinking:!1,toolDetails:!0,assistantMetadata:!0};function zb(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function Vb(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 Jb(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
22
22
|
|
|
23
23
|
`;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
|
|
@@ -94,4 +94,4 @@ ${e.state.error}
|
|
|
94
94
|
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function $w(e){let t=H(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=_f.test(e.output.trim())?jw(e.output):Mw(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function Ow(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 co(e){let t=st(e)??{};return{content:H(t.content)??"",status:H(t.status)??"pending",priority:H(t.priority)}}function Dw(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(co)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(co)};let n=st(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(co)}:{kind:"todo",items:[]}}function qw(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=st(r)??{},o=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let p=st(a),g=p&&H(p.label);return g?[{label:g,description:p?H(p.description):void 0}]:[]});return{question:H(s.question)??"",header:H(s.header),options:o}})}}function Uw(e){let n=e.input&&Object.keys(e.input).length>0?yf(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Kt(e.outputParsed):yf(e.outputParsed):e.outputText!==void 0?r=Kt(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function Fw(e){switch(Bn(e.name)){case"web_search":case"websearch":case"image_search":return bw(e);case"bash":return vw(e);case"read":return Aw(e);case"write":return Rw(e);case"edit":case"morph_edit":return Iw(e);case"grep":case"glob":return $w(e);case"task":return Ow(e);case"todowrite":return Dw(e);case"question":case"ask":return qw(e);default:return Uw(e)}}var Lw=new Set(["AbortError","MessageAbortedError"]),Bw=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],Gw=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function xf(e){let t=e.toLowerCase();return Gw.some(n=>t.includes(n))?!1:Bw.some(n=>t.includes(n))}function Nw(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 Jn(e){if(typeof e=="string")return xf(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&Lw.has(n))return!0;let r=Nw(t);return typeof r=="string"?xf(r):!1}var Ww=["user","runtime-disposed","orphan-finalized","wake"],hO=["orphan-finalized","wake"];function bO(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 Ww.includes(n)?n:void 0}function Xn(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}function Kw(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 PO(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 uo(e,t,n){return e!==void 0?e:Kw(Xn(t),n)}var SO={get disableMobileAdvertising(){return uo($().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return uo($().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return uo($().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var Qn="kortix-active-instance",Hw=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function zw(e){return Hw.some(t=>e===t||e.startsWith(`${t}/`))}function Ht(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 AO(e){let t=Ht(e);return!!t&&t.innerPath===""}function RO(e){let t=Ht(e);return!t||!t.innerPath?e:t.innerPath}function Vw(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=Ht(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return zw(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function Jw(e){return e?Ht(e)?.instanceId??null:null}function CO(){return typeof window>"u"?null:Jw(window.location.pathname)||Xw()}function Xw(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Qn}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function TO(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Qn}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Qn}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Qn}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function IO(e,t){return t?Vw(t,e):e}function EO(e){let t=Ht(e);return t?t.innerPath||"/dashboard":e}function po(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 Qw(e){let t=po(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 wf(e){let t=Qw(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}function MO(e){return wf(e)!==null}var Yw=[/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 Zn(e){let t=po(e);return t?Yw.some(n=>n.test(t)):!1}var Yn=class extends Error{constructor(t){let n=t?.trim();super(n&&Zn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function Zw(e){let t=wf(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),i=t.data?.issues?.[0]?.message,o=t.data?.issues?.[0]?.path?.join("."),a=o?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${a}`,detail:i?`${o?`${o}: `:""}${i}`:void 0}}let n=po(e);return Zn(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"OpenCode failed to load",message:n||"The sandbox is running, but OpenCode returned an error."}}function ge(){let e=Xn("BACKEND_URL")||$().backendUrl;return e||"http://localhost:8008/v1"}function zt(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=zt(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return zt(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}var kf=["http://localhost:8008/v1","http://127.0.0.1:8008/v1"];function Pf(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return`${e.slice(0,t)}/platform/local-bridge/status`}function ek(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 go(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?`${ge()}/p/${n.external_id}/${Te.KORTIX_MASTER}`:""),status:ek(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 mo(){let e=await Xe(),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:go(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},i=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return i!==0?i:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Le(e){let t=await mo();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}function Sf(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`${ge()}/p/${e.external_id}/${Te.KORTIX_MASTER}`}function GO(e,t){return e.external_id?`${ge()}/p/${e.external_id}/${t}`:null}async function VO(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function tk(e){let t=await Le();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Xe())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await Et(r.project_id,{...e?.provider?{provider:e.provider}:{}}),i=(await Qe(r.project_id,s.session_id))?.sandbox??null;return{sandbox:go(r,s,i),created:!0}}async function JO(){return(await Le().catch(()=>null))?.sandbox??null}async function XO(e){return{sandbox:(await tk(e)).sandbox}}async function QO(e){let t=zt(e);return t?(await Le(t).catch(()=>null))?.sandbox??null:null}async function YO(e,t){throw await Le(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function ZO(e){let t=zt(e);return(await mo().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function eD(){if(typeof window>"u")return null;let e=ge(),t=Array.from(new Set([e,...kf]));for(let n of t)try{let r=await fetch(Pf(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 tD(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Le(e);if(!t)throw new Error("Project session sandbox not found");await An(t.project.project_id,t.session.session_id)}async function nD(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Le(e);if(!t)throw new Error("Project session sandbox not found");await Rn(t.project.project_id,t.session.session_id)}async function rD(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function sD(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function fo(e,t,n){let r=Sf(e),s=await q(`${ve(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let i=await s.text().catch(()=>"");throw new Error(i||`Request failed (${s.status})`)}return await s.json()}async function lD(e,t){return fo(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function uD(e,t,n,r="member"){await fo(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function pD(e,t,n){await fo(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var yo="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function mD(e){throw W("getInvite",yo)}async function fD(e){throw W("acceptInvite",yo)}async function yD(e){throw W("declineInvite",yo)}async function bD(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function _D(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function xD(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function wD(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function PD(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function SD(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var nk=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function RD(e){return nk.includes(e)}async function CD(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 TD(e){let t=e?`?channel=${e}`:"",n=await fetch(`${ge()}/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 rk(e||"stable");r.changelog=s.find(i=>i.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function rk(e){let t=e?`?channel=${e}`:"",n=await fetch(`${ge()}/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 ID(){let e=await fetch(`${ge()}/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 ED(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function jD(e){}async function MD(e){}async function DD(e){return{serverTypes:[],location:e||"hel1"}}async function qD(e){throw new Error("Retired instance provisioning is unavailable. Create a project session with daytona, platinum, or e2b.")}async function UD(e){throw W("deleteInstance")}async function FD(e,t){}async function LD(){throw W("claimComputer")}async function BD(e){return null}function GD(e,t){throw W("getSandboxProvisionStreamUrl")}var je=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function er(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return/\/v1$/.test(t)?t:`${t}/v1`}function ho(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 tr(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function nr(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 V(e,t,n){let r=n?.body!==void 0,s=await fetch(`${er(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:ho(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),i=await tr(s);if(!s.ok)throw new je(nr(s,i),s.status,i);return i}function sk(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 WD(e,t){return V(`/marketplace/items${sk(t)}`,e)}function KD(e){return V("/marketplace/marketplaces",e)}function HD(e,t){return V(`/marketplace/items/${encodeURIComponent(e)}`,t)}function zD(e,t,n){return V(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function VD(e,t){return V("/access/check-email",t,{method:"POST",body:{email:e}})}function JD(e,t){return V("/access/request-access",t,{method:"POST",body:e})}function XD(e){return V("/auth/logout",e,{method:"POST",body:{}})}function QD(e,t){return V(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function YD(e,t){return V("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function ZD(e,t){return V(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function e0(e,t){return V(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function t0(e,t,n={}){return V(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function n0(e,t){return V(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function r0(e,t,n){return V(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t}})}function s0(e,t){return V(`/p/public-share/${encodeURIComponent(e)}`,t)}function i0(e,t,n){return V(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function o0(e){return V("/system/maintenance",e)}function a0(e,t){return V("/system/maintenance",t,{method:"PUT",body:e})}function c0(e){return V("/user-roles",e)}function l0(e,t){return V("/system/demo-request",t,{method:"POST",body:e})}async function u0(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(`${er(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${r}`,{headers:ho(n,!1),...n.signal?{signal:n.signal}:{}});if(!s.ok){let i=await tr(s);throw new je(nr(s,i),s.status,i)}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 p0(e,t){let n=await fetch(`${er(t.backendUrl)}/admin/stress-test/run`,{method:"POST",headers:ho(t,!0),body:JSON.stringify(e),...t.signal?{signal:t.signal}:{}});if(!n.ok){let r=await tr(n);throw new je(nr(n,r),n.status,r)}if(!n.body)throw new je("No response body",n.status,null);return n.body}var ik=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ok(e,t){return ik.test(t)?new URL(`templates/public/${t.toLowerCase()}`,`${er(e)}/`):null}async function d0(e,t,n){let r=ok(e,t);if(!r)throw new je("Invalid shareId parameter",400,null);let s=await fetch(r,{signal:n}),i=await tr(s);if(!s.ok)throw new je(nr(s,i),s.status,i);return i}async function f0(){let e=await c.get("/platform/github-app/status",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App status request failed");return e.data}async function y0(e={}){let t=await c.post("/platform/github-app/manifest-start",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App manifest-start request failed");return t.data}async function h0(e){let t=await c.post("/platform/github-app/app",{app_id:e.appId,private_key:e.privateKey,installation_id:e.installationId,slug:e.slug,client_id:e.clientId,client_secret:e.clientSecret},{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub App configuration request failed");return t.data}async function b0(e){let t=await c.post("/platform/github-app/pat",e,{showErrors:!1});if(t.error)throw t.error;if(!t.data)throw new Error("GitHub token configuration request failed");return t.data}async function _0(){let e=await c.delete("/platform/github-app",{showErrors:!1});if(e.error)throw e.error;if(!e.data)throw new Error("GitHub App disconnect request failed");return e.data}var ak="/kortix/part/";function ck(e){return typeof e=="string"&&e.startsWith(ak)}async function P0(e){if(!ck(e))throw new Error(`not an attachment part reference: ${e}`);let t=ye();if(!t)throw new Error("runtime url not bound");let n=await q(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function vf(e){try{let t=new URL(e);if(/^\/proxy\/\d+(?:\/|$)/.test(t.pathname))return`${t.origin}/v1/p/auth`;let n=t.pathname.indexOf("/p/");return n!==-1?`${t.origin}${t.pathname.slice(0,n)}/p/auth`:`${t.origin}/v1/p/auth`}catch{return null}}function lk(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let i=new Set;if(t)try{i.add(new URL(t).origin)}catch{}return typeof window<"u"&&i.add(window.location.origin),i.has(n.origin)}catch{return!1}}function Af(e,t){return lk(e,t)?(t?vf(t):null)??vf(e):null}function rr(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 Rf(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var uk=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function pk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dk(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let s=(t.slice(n+3).split("/")[0]??"").toLowerCase(),i=`${r}://${s}`.split("{port}").map(o=>o.split("{sandbox}").map(pk).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${i}$`).test(e)}function gk(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function Cf(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function mk(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:uk.test(n.hostname)?t.backendUrls.some(r=>{let s=gk(r);return s!==null&&Cf(s)===Cf(n)}):t.templates.some(r=>dk(n.origin,r))}async function Tf(e,t={}){if(!rr(e))return!1;let n=$().backendUrl;n&&await We(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return mk(e,{templates:Xo(),backendUrls:r})}async function fk(e,t={}){let n=Af(e,t.serverUrl||$().backendUrl||void 0);if(!n)return!1;let r=await dt();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 $0(e,t={}){if(rr(e)){if(!await Tf(e,t))return e;let n=await dt();return n?Rf(e,n):e}return await fk(e,t),e}var D0=3e3;function yk(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 q0(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 i=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return yk(i.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function bo(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function F0(e,t){return`${bo(e)}/presentation-templates/${encodeURIComponent(t)}/pdf#toolbar=0&navpanes=0&scrollbar=0&view=FitH`}function L0(e,t){return`${bo(e)}/presentation-templates/${encodeURIComponent(t)}/image.png`}function hk(e,t){return`${bo(e)}/presentation/convert-to-${t}`}async function B0(e,t,n,r){let s=hk(t,e),i=r?.pollIntervalMs??2500,o=r?.timeoutMs??4*6e4,a=Date.now(),p=!1;for(;;){let g=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),m=g.headers.get("content-type")||"";if(g.ok&&(m.includes("pdf")||m.includes("presentation")||m.includes("octet-stream"))){let A=await g.blob();if(A.size===0)throw new Error("Downloaded file is empty");return A}if(g.status===202){if(p||(p=!0,r?.onGenerating?.()),Date.now()-a>o)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((A,P)=>{let M=setTimeout(A,i);r?.signal?.addEventListener("abort",()=>{clearTimeout(M),P(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let _=await g.text().catch(()=>""),w=g.statusText;try{let A=JSON.parse(_);w=String(A.error||A.detail||A.message||w)}catch{_&&(w=_)}throw new Error(`Failed to download ${e.toUpperCase()}: ${w} (HTTP ${g.status})`)}}function N0(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 W0(e){return e==="unreachable"}var H0=6e4,z0=45e3,V0=45e3,J0=1e4,X0=3e3,Q0=15e3;function Y0(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function Z0(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 _o(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function eq(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:i,activity:o,nowMs:a}=e,p=!!t&&a-t.atMs<6e4,g=t?t.turnId===void 0?t.messageId:t.turnId:null,m=p?t.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,h=p?t.atMs:Number.NEGATIVE_INFINITY,_=!!n&&a-n.atMs<15e3,w=_?n.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,A=!!s&&a-s.atMs<=45e3,P=!!i&&a-i.atMs<=45e3,M=!!r&&a-r.atMs<=1e4,k=i&&i.type==="idle"&&i.origin!=="local"?i:null,y=!!o&&a-o.atMs<=45e3&&(!k||o.atMs>k.atMs),l=D=>{if(!k)return!1;let Z=_o(D.started_at);return!(Z===null||Z>=k.atMs)};if(y&&o.atMs>=w)return{state:"working",source:"stream",turnId:A?s.turns.find(D=>D.state==="active"&&!l(D))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:s?.turns[0]?.turn_token??null};let R=s?.turns[0]?.turn_token??null,I=A?s.turns.filter(D=>!l(D)):[],O=I.find(D=>D.state==="active")??I[0],N=!!i&&!(i.type==="idle"&&i.origin==="local");if(O&&s.atMs>=w&&(!N||s.atMs>=i.atMs))return{...O.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:O.message_id,since:_o(O.started_at)??s.atMs,serverOpenTurnToken:R};if(M&&r.pending>0&&r.atMs>=w)return{...P&&i.type!=="idle"&&(!A||i.atMs>s.atMs)&&i.atMs>=w?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:p?g:null,since:r.atMs,serverOpenTurnToken:R};let E=r?.drainedAtMs;if(M&&r.pending===0&&E!=null&&!_&&!(A&&s.atMs>=E))return{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:E,serverOpenTurnToken:R};let F=A&&!O&&s.atMs>=m,b=P&&i.atMs>=h&&(i.type==="idle"||i.atMs>=w);if(F&&(!i||s.atMs>=i.atMs))return{state:"idle",source:"server",turnId:null,since:_o(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:R};if(b)return{state:i.type==="idle"?"idle":"working",source:"stream",turnId:null,since:i.atMs,serverOpenTurnToken:R};if(p)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:g,since:t.atMs,serverOpenTurnToken:R};let T=s&&i?s.atMs>=i.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:i.atMs}:s?{source:"server",atMs:s.atMs}:i?{source:"stream",atMs:i.atMs}:{source:"server",atMs:a};return{state:"idle",source:T.source,turnId:null,since:T.atMs,serverOpenTurnToken:R}}function tq(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:i,activity:o,nowMs:a}=e,p=[null,t?t.atMs+6e4:null,n?n.atMs+15e3:null,r?r.atMs+1e4:null,s?s.atMs+45e3:null,i?i.atMs+45e3:null,o?o.atMs+45e3:null],g=null;for(let m of p)m===null||m<=a||(g===null||m<g)&&(g=m);return g}function bk(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(i=>i.message_id===t),r=e.last_ended,s=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!s?.message||Jn({name:s.name??void 0,message:s.message})?null:s}var _k="SandboxMemoryGuard";function iq(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=bk(e,t);if(r?.message){if(r.name!==_k)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],p=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:p}}let s=e.recent_failures?.find(a=>a.message_id===t);if(!s)return null;let i=s.ended_at?Date.parse(s.ended_at):Number.NaN;return Number.isFinite(i)&&typeof e.atMs=="number"&&e.atMs-i<2500?null:{kind:"unexplained"}}var aq=6e4;function cq(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function lq(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var xk=9e4;function uq(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+xk}var dq=75e3,gq=2,mq=2e4;function If(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function fq(e){return e.filter(t=>t!=null).join("|")}function wk(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function yq(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,i=n.cooldownMs??2e4;if(t.runtimeReachable)return{...If(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...If(),settled:!0};let o=e.lastProgressAtMs,a=o===null,p=t.progress!==e.fingerprint,g=o===null||p?t.nowMs:o,m=Math.max(0,t.nowMs-g),h={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:g,msSinceProgress:m,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...h,status:"exhausted"};let _=!a&&!p&&m>=r;if(!t.serverGaveUp&&!_||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<i)return h;let w=wk(e.attempts,s);return w?{...h,status:"escalating",dispatch:w,attempts:[...e.attempts,{step:w,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...h,status:"exhausted"}}var kk={"retry-start":"retrying",restart:"restarting"};function hq(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${kk[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function Pk(e){return e===1?"once":e===2?"twice":`${e} times`}function bq(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 ${Pk(t)}`),`Tried: ${r.join(", then ")}.`}var Sk=12e4,sr=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},vk=1e3,Ak=15e3,Ef=100,Rk=50,Ck=10;function jf(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},i)=>{let o=new URLSearchParams({limit:String(r)});s&&o.set("before",s);let a=await e.getToken?.(),p=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${o}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...i?{signal:i}:{}});if(!p.ok)throw p.status===503?new Yn(`session ${p.status}`):new S(`Session synchronization failed: ${p.status}`,{status:p.status});return{messages:await p.json(),nextCursor:p.headers.get("x-next-cursor")||void 0}}}function Tk(e){return Ek(jf(e))}function Ik(e){return new xo({...e,loadPage:jf(e)})}async function Ek(e){let t=[],n=new Set,r;do{let o=await e({limit:Ef,...r?{before:r}:{}});if(t.push(o.messages),r=o.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],i=new Set;for(let o=t.length-1;o>=0;o--)for(let a of t[o])i.has(a.info.id)||(i.add(a.info.id),s.push(a));return s}var jk={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},xo=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;olderRequest;livenessTimer;livenessBusy=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??jk,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??Sk,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":"stale"}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcile("turn-end");return}r&&!this.destroyed&&this.reconcile("turn-end"),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||this.abortController.signal.aborted)return;let r=n instanceof sr;if(!r&&Jn(n))return;if(r||this.update({freshness:Zn(n)?"loading":"error"}),n instanceof S&&(n.status===404||n.status===410)){this.tailUnavailable=!0,this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0;return}this.scheduleTailRetry(t)}}scheduleTailRetry(t){if(this.destroyed||this.tailRetryTimer!==void 0)return;let n=Math.min(vk*2**this.retryAttempt,Ak);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 i=await this.boundedRead(o=>this.options.loadPage({limit:t==="tail"?Rk:Ef,...r?{before:r}:{}},o));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:i.messages.length,succeeded:!0}),i}catch(i){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),i}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,s=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",s,{once:!0});let i,o=new Promise((p,g)=>{i=this.startTimer(()=>{let m=new sr(this.readTimeoutMs);g(m),r.abort(m)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(p){a=Promise.reject(p)}return Promise.race([a,o]).finally(()=>{this.cancelTimer(i),n.removeEventListener("abort",s)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,i){let o=[...t.messages],a=new Set(this.knownUserMessageIds),p=new Set(s?[s]:[]),g=t.nextCursor,m=0;for(let h of t.messages)h.info.role==="user"&&a.add(h.info.id);for(;g&&m<Ck&&o.some(h=>h.info.role==="assistant"&&!!h.info.parentID&&!a.has(h.info.parentID));){if(p.has(g))throw new Error(`Session history cursor repeated: ${g}`);p.add(g);let h;try{h=await this.loadPage(n,r,g)}catch(_){throw i?.({messages:[...o],nextCursor:g}),_}if(this.destroyed)return{messages:o,nextCursor:g};m+=1,o.unshift(...h.messages);for(let _ of h.messages)_.info.role==="user"&&a.add(_.info.id);g=h.nextCursor,i?.({messages:[...o],nextCursor:g})}return{messages:o,nextCursor:g}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,i=!1,o=()=>{i||(i=!0,this.cancelTimer(s),r())};s=this.startTimer(o,n),t.then(o,o)})}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 Mk(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return`${t}/tunnel/permission-requests/stream`}function $k(e){let{url:t,token:n,method:r="GET",body:s,onEvent:i,onOpen:o,onError:a,signal:p}=e,g=new Map,m=null,h=!1;function _(k,d){i?.(k,d);let y=g.get(k);if(y)for(let l of y)try{l(d)}catch{}}async function w(){if(h)return;m=new AbortController;let k=p?AbortSignal.any([m.signal,p]):m.signal;try{let d={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(d["Content-Type"]="application/json");let y=await fetch(t,{method:r,headers:d,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:k,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");o?.();let l=y.body.getReader(),x=new TextDecoder,R="",I="message",O="";for(;!h;){let{done:N,value:E}=await l.read();if(N)break;R+=x.decode(E,{stream:!0});let K=R.split(`
|
|
95
95
|
`);R=K.pop()||"";for(let F of K)F===""?O&&(_(I,O.trimEnd()),I="message",O=""):F.startsWith("event: ")?I=F.slice(7).trim():F.startsWith("data: ")?O+=(O?`
|
|
96
96
|
`:"")+F.slice(6):F.startsWith("data:")&&(O+=(O?`
|
|
97
|
-
`:"")+F.slice(5))}}catch(d){if(h||d instanceof DOMException&&d.name==="AbortError")return;a?.(d instanceof Error?d:new Error(String(d)))}}function A(){h=!0,m?.abort(),m=null,g.clear()}function P(k,d){let y=g.get(k)??new Set;y.add(d),g.set(k,y)}function M(k,d){g.get(k)?.delete(d)}return{connect:w,close:A,addEventListener:P,removeEventListener:M}}function Sq(e,t){return $k({...t,url:Mk(e)})}var Ok="/_kortix/viewer";var ir=new Map;function Dk(){ir.clear()}async function qk(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 Mf(e={}){let t=e.path??Ok,n=e.fetch??((i,o)=>fetch(i,o)),r=ir.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=qk(t,n).then(i=>{let o=i?.expires_at?Date.parse(i.expires_at):Number.NaN,a=Number.isFinite(o)?o-6e4:Date.now()+6e4;return ir.set(t,{session:i,expiresAt:a}),i});return ir.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function Uk(e={}){return async()=>(await Mf(e))?.access_token??null}export{Ww as ABORT_REASONS,hO as ABORT_REASONS_NOT_YET_EMITTED,Qn as ACTIVE_INSTANCE_COOKIE,fy as ANALYTICS_UNAVAILABLE_CODE,ak as ATTACHMENT_PART_REF_PREFIX,S as ApiError,oe as AuthError,Me as BillingError,hx as CONTEXT_TOOLS,lf as COST_MARKUP,bx as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,cm as DEFAULT_TRANSCRIPT_OPTIONS,nk as DESTRUCTIVE_PHASES,Ts as FEATURE_DISABLED_CODE,uA as FEATURE_FLAG_KEYS,dy as FEATURE_NOT_SUPPORTED_CODE,Fe as FILE_VERBS,_t as FileExistsError,Mt as HeadlessAuthError,je as HostBoundaryError,Zf as IMPERSONATION_HEADER,J0 as INBOX_OBSERVATION_MAX_MS,Hw as INSTANCE_SCOPED_ROUTES,Jy as MAX_PROMPT_ATTACHMENTS_BYTES,Vs as MAX_PROMPT_ATTACHMENT_BYTES,xa as MAX_PROMPT_ATTACHMENT_FILES,X$ as MEMORY_VERBS,gy as MODEL_NOT_SERVABLE_CODE,Bh as NO_GROUP_ACTIVITY_TOOLS,Q0 as OPTIMISTIC_ABORT_MAX_MS,aq as OPTIMISTIC_COMPACTION_MAX_MS,H0 as OPTIMISTIC_RECEIPT_MAX_MS,gx as PLUMBING_TOOLS,D0 as PREVIEW_PROBE_TIMEOUT_MS,MR as PROJECT_SESSION_NAME_LOOKUP_LIMIT,jR as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,hh as PROJECT_SESSION_PAGE_MAX_LIMIT,my as PROVISION_IN_FLIGHT_CODE,_i as PublicSessionShareError,Ge as RequestTooLargeError,yt as RuntimeNotReadyError,Hs as SANDBOX_FS_ROOTS,Te as SANDBOX_PORTS,xk as SERVER_COMPACTION_REVALIDATE_MS,z0 as SERVER_OBSERVATION_MAX_MS,Gh as STANDALONE_TOOLS,V0 as STREAM_OBSERVATION_MAX_MS,Yn as SandboxNotReadyError,Un as SessionNotReadyError,pi as SessionStartError,X0 as TURN_END_LEDGER_LAG_MS,mq as WAKE_ESCALATION_COOLDOWN_MS,gq as WAKE_MAX_RESTARTS,dq as WAKE_NO_PROGRESS_MS,Wi as WIRE_ID_BACKDATE_MS,qe as WIRE_ID_CLOCK_TOLERANCE,Ee as WIRE_ID_TIME_MASK,Dt as WIRE_ID_TIME_SCALE,t_ as WIRE_MESSAGE_ID,Lk as __getConfigResolver,Fk as __setConfigResolver,bO as abortErrorReason,Ka as acceptAccountInvite,fD as acceptInvite,zd as actReviewItem,xl as activateConnection,xd as addGroupMembers,Pg as addMarketplaceSource,yq as advanceWakeEscalation,X_ as allDescendantIds,Rf as appendPreviewToken,kc as approveProjectAccessRequest,TS as approveTask,ni as archiveProject,qS as assignTicket,jc as attachGroupToProject,Li as authMfa,qi as authUser,q as authenticatedFetch,$0 as authorizePreviewUrl,c as backendApi,IC as bindSlackIdentity,EC as bindTeamsIdentity,Wc as brokerProjectSecretRequest,Vw as buildInstancePath,L0 as buildPresentationTemplateImageUrl,F0 as buildPresentationTemplatePdfUrl,Af as buildPreviewAuthEndpoint,ok as buildPublicTemplateUrl,hk as buildRuntimePresentationConversionUrl,eu as buildSandboxTemplate,xx as buildScrapeFailureResults,IE as buildStaticFileHealthPreviewUrl,TE as buildStaticFileLocalUrl,CE as buildStaticFilePreviewUrl,db as buildStaticFileServicePath,Mk as buildTunnelEventStreamUrl,OE as buildWebProxyUrl,Vd as bulkActReviewItems,sT as bulkDeletePolicies,iT as bulkImportPolicies,gM as burstSummary,mM as burstSummaryLabel,pl as callConnector,YT as cancelAccountDeletion,Ba as cancelAccountInvite,rD as cancelSandbox,MD as cancelSandboxUpdate,vp as cancelScheduledChange,kp as cancelSubscription,VD as checkAccessEmail,Vj as childMapByParent,LD as claimComputer,Lb as claimNext,hC as claimPerSeatBilling,Eu as claimWarmProjectSession,_m as classifyPart,yk as classifyPreviewProbeStatus,Cy as classifyPtyClose,L_ as classifyTurn,nM as cleanErrorMessage,RM as cleanResultSnippet,B$ as cleanWorkerOutput,Lo as clearImpersonationSession,Dk as clearKortixAppViewerCache,ap as clearModelDefault,AR as clearSessionFresh,bu as closeChangeRequest,pv as closeMilestone,Wj as collectTurnParts,FS as commentTicket,wu as commitSessionChanges,lq as compactionExpiryAtMs,yM as compactionTurnInfo,Gj as compareMessagesForDisplay,Bb as completeInFlight,Fp as completeSlackInstall,Lp as completeTeamsInstall,cf as computeStatusFromPart,Tp as configureAutoTopup,cr as configureKortix,xp as confirmCheckoutSession,zp as connectEmail,Dp as connectSlack,W0 as connectionIsFaulted,NA as connectionSharedWithEveryone,fh as connectorConnect,yh as connectorFinalize,LM as contextLabelForTool,wM as contextToolSummary,kM as contextToolTrigger,mI as convertPresentationToGoogleSlides,B0 as convertRuntimePresentation,yn as copyFile,Ep as costExportUrl,Z0 as countLiveInboxPrompts,xI as countReviewItemsBySegment,Ia as createAccount,dg as createAccountAuditWebhook,el as createAccountSecretResource,rg as createAccountToken,Ag as createApp,Mg as createAppAccessSession,Og as createAppDeployment,BM as createArtifactKind,Ld as createAssignment,OT as createAuditWebhook,_D as createBackup,_p as createCheckoutSession,Dl as createConnector,fn as createFile,pd as createGatewayKey,yd as createGroup,Ik as createHttpSessionSyncController,qD as createInstance,Db as createKortix,ra as createKortixPty,Gi as createKortixSession,NI as createMarketplaceInstallSession,lv as createMilestone,$d as createOAuthClient,yC as createPerSeatCheckout,tT as createPolicy,wp as createPortalSession,nc as createProject,JS as createProjectAgent,og as createProjectCliToken,rc as createProjectRepo,Dc as createProjectResourceGrant,Et as createProjectSession,Xu as createProjectTrigger,Ca as createPromptAttachmentController,Ad as createRole,$k as createSSEStream,XO as createSandbox,Yd as createSandboxShare,Ql as createSandboxTemplate,lT as createScimToken,ET as createServiceAccountApi,Du as createSessionPrompt,Cu as createSessionPublicShare,Ub as createSessionQueue,kT as createSsoGroupMapping,AS as createTask,$S as createTicket,Sq as createTunnelEventStream,Ha as declineAccountInvite,yD as declineInvite,ZT as deleteAccountImmediately,nl as deleteAccountSecretResource,Tg as deleteApp,qT as deleteAuditWebhook,wD as deleteBackup,Ul as deleteConnector,bv as deleteCredential,ta as deleteEnv,Ve as deleteFile,ld as deleteGatewayBudget,bc as deleteGitHubInstallation,bd as deleteGroup,UD as deleteInstance,sv as deleteKortixProject,gv as deleteMilestone,qd as deleteOAuthClient,Qc as deletePersonalProjectSecret,rT as deletePolicy,QS as deleteProjectAgent,zc as deleteProjectProviderOAuth,qc as deleteProjectResourceGrant,Jc as deleteProjectSecret,Gu as deleteProjectSession,Yu as deleteProjectTrigger,Ct as deletePromptAttachment,Td as deleteRole,Zl as deleteSandboxTemplate,MT as deleteServiceAccountApi,Uu as deleteSessionPrompt,PT as deleteSsoGroupMapping,xT as deleteSsoProvider,IS as deleteTask,LS as deleteTicket,Wa as describeAccountInvite,ul as describeConnectorTool,$c as detachGroupFromProject,cb as detectLocalhostUrls,jT as disableServiceAccountApi,Vp as disconnectEmail,_0 as disconnectGitHubApp,Gp as disconnectSlack,zA as discoverConnectionOAuth2,VA as discoverConnectionOAuth2Resource,ql as discoverConnectorAuth,eD as discoverLocalSandbox,u0 as downloadAccountAudit,Ev as dropClientForUrl,$v as dropPublicClientForUrl,Kb as editQueued,Fb as enqueue,zS as ensurePmSession,fk as ensurePreviewSessionCookie,WA as ensureProjectConnectorConnection,tk as ensureSandbox,Iu as ensureWarmProjectSession,Ay as env,$i as exchangeCode,ug as exportAccountAudit,de as extractGatewayErrorDetails,Ht as extractInstanceRoute,mw as extractSkillBaseDir,pO as extractSkillContent,pw as extractSkillFiles,N$ as extractWorkerPreview,Gb as failInFlight,g$ as fallbackBusyRowAfterTurnId,io as familyForTool,Do as featureDisabledKey,SO as featureFlags,mC as fetchAccountStateWithToken,iA as fetchAccountsWithToken,P0 as fetchAttachmentPart,AC as fetchCostExportCsv,Mf as fetchKortixAppViewer,iu as fetchProjectArchive,bA as fetchProjectsForAccountWithToken,Vg as fetchSessionAttachment,z$ as filePhase,H$ as fileVerb,zy as files,wi as finalizeAppArtifact,t0 as finalizeConnectorSetupLink,$R as findActiveTranscriptShare,gn as findFiles,Kj as findLastTextPart,fE as findSessionAttachments,mn as findText,ep as fireProjectTrigger,Xl as fixSandboxWithAgent,JM as flattenThought,Uo as formatBillingErrorForUI,$$ as formatCost,E$ as formatDuration,rM as formatJsonFailureOutput,YM as formatMessageDay,ZM as formatMessageExact,Zw as formatOpenCodeRuntimeError,AM as formatRawOutput,Zw as formatRuntimeError,O$ as formatTokens,Yb as formatTranscript,y$ as freshSendHint,qb as generateSessionId,Ea as getAccount,Ma as getAccountBranding,XT as getAccountDeletionStatus,dp as getAccountState,gp as getAccountStateMinimal,Xw as getActiveInstanceIdFromCookie,aI as getAdminProviderAnalytics,sI as getAdminProviderDistribution,lI as getAdminProviderFallback,eI as getAdminRole,K_ as getAgentCardLabel,aC as getAgentConfig,YS as getAgentPersona,ID as getAllVersions,zj as getAnsweredQuestionParts,Rg as getApp,Ig as getAppAccess,qg as getAppDeployment,Ug as getAppDeploymentLogs,FI as getApprovalLink,dt as getAuthToken,NP as getAuthTokenWithRetry,Cp as getAutoTopupSettings,fC as getAutoTopupSetupStatus,yp as getBillingCreditBreakdown,bp as getBillingTierConfigurations,fp as getBillingTransactionsSummary,hp as getBillingUsageHistory,gu as getChangeRequest,mu as getChangeRequestDiff,fu as getChangeRequestMergePreview,Cj as getChildSessionError,Rj as getChildSessionId,Tj as getChildSessionToolParts,Oe as getClient,Re as getClientForUrl,Gl as getConnectStatus,HA as getConnectionOAuth2Application,ZA as getConnectionOAuth2Status,eR as getConnectionPolicies,si as getConnectorCatalog,Ml as getConnectorConfig,El as getConnectorPolicies,ZD as getConnectorSetupLink,vC as getCostSummary,Jw as getCurrentInstanceIdFromPathname,CO as getCurrentInstanceIdFromWindow,ba as getCurrentProject,gi as getDefaultAccountState,jj as getDiagnostics,W_ as getDirectory,oi as getDiscoverConnector,oR as getDiscoverIntegration,Kp as getEmailInstallation,Hp as getEmailMode,FT as getEnterpriseDemo,dn as getFileStatus,xm as getFileWithDir,N_ as getFilename,rk as getFullChangelog,sd as getGatewayBreakdown,ad as getGatewayBudgets,od as getGatewayErrors,ud as getGatewayKeys,td as getGatewayLog,nd as getGatewayOverview,Xp as getGatewayRoutingPolicy,rd as getGatewaySeries,id as getGatewaySessions,f0 as getGitHubAppStatus,pc as getGitHubInstallation,gI as getGoogleAuthUrl,fd as getGroup,vj as getHiddenToolParts,ny as getImpersonationSession,mD as getInvite,DD as getJustavpsServerTypes,tv as getKortixProject,nv as getKortixProjectBySession,oa as getKortixPtyWebSocketUrl,TD as getLatestSandboxVersion,o0 as getMaintenanceConfig,_c as getManagedGitBackend,mA as getManagedGitStatus,xg as getMarketplaceCatalogItem,wg as getMarketplaceCatalogItemFile,pT as getMfaRequired,av as getMilestone,ip as getModelDefaults,Md as getOAuthClient,QD as getOAuthConsentRequest,wf as getOpenCodeConfigInvalidError,kj as getPartText,CT as getPatPolicy,Mj as getPermissionForTool,Qs as getProject,ZS as getProjectActivity,cu as getProjectCommit,lu as getProjectCommitDiff,Ys as getProjectDetail,uu as getProjectFileHistory,tc as getProjectGitToken,Zs as getProjectLlmCatalog,dA as getProjectLlmCatalogProviders,ki as getProjectModelAccess,ei as getProjectModelPicker,ai as getProjectSandboxHealth,fA as getProjectSandboxProviderTransition,li as getProjectSession,Nu as getProjectSessionConfigState,Hu as getProjectSessionScope,Ap as getProrationPreview,VO as getProviders,EE as getProxyBaseUrl,Mv as getPublicClientForUrl,HD as getPublicMarketplaceItem,zD as getPublicMarketplaceItemFile,CI as getPublicSessionShare,TI as getPublicSessionShareMessages,s0 as getPublicShareByToken,d0 as getPublicTemplate,$j as getQuestionForTool,GC as getReferralCode,KC as getReferralStats,D$ as getRetryInfo,q$ as getRetryMessage,Kd as getReviewItem,Sd as getRolePermissions,vd as getRoleUsage,SD as getSSHConnection,JO as getSandbox,QO as getSandboxById,GO as getSandboxPortUrl,BD as getSandboxProvisionStatus,GD as getSandboxProvisionStreamUrl,CD as getSandboxUpdateStatus,Sf as getSandboxUrl,n0 as getSecretSetupLink,zs as getServerHealth,wv as getServiceLogs,ju as getSessionAudit,M$ as getSessionCost,fi as getSessionCostRecord,Xg as getSessionHealth,OR as getSessionOpenBundle,mT as getSessionOversight,ST as getSessionPolicy,Au as getSessionPreviewCandidates,ol as getSessionProviderSecretPool,Mu as getSessionTranscript,$u as getSessionTranscriptSync,Ou as getSessionTurn,x$ as getShellModePart,Np as getSlackChannelFile,Op as getSlackInstallation,Bp as getSlackManifest,qp as getSlackMode,yT as getSsoProvider,gb as getStaticFileHealthPath,qs as getSupabaseAccessToken,pt as getSupabaseAccessTokenWithRetry,PS as getTask,vS as getTaskStatus,HI as getTemplate,jS as getTicket,Ij as getToolInfo,no as getToolPrimaryArg,Zb as getTranscriptFilename,j$ as getTurnCost,R$ as getTurnError,T$ as getTurnErrorDetails,C$ as getTurnErrorRawText,I$ as getTurnStatus,Ip as getUsageRollup,c0 as getUserRolesWithToken,pu as getVersionDiff,v$ as getWorkingState,rl as grantAccountSecretResource,uD as grantSandboxProjectAccess,lC as grantSecretToAgent,Nj as groupMessagesIntoTurns,a$ as groupShowSegments,Zm as groupSteps,U$ as hasDiffs,RE as hasLocalhostUrls,pb as hasPreviewTarget,Qj as hasRetryingAssistantTurn,yb as heartbeatGapEvent,Lu as holdSessionPrompts,Xd as humanizeReviewActionPath,Wn as humanizeSearchQuery,zi as humanizeToolName,Bo as impersonationHeaders,bT as importSsoProviderFromMetadata,Y0 as inboxObservationSupersedes,If as initialWakeEscalationState,zI as installTemplate,Us as invalidateTokenCache,Fa as inviteAccountMember,Rc as inviteProjectMember,Za as inviteRepoCollaborator,Jn as isAbortError,oy as isAdminBypassEnabled,bj as isAgentPart,ib as isAppRouteUrl,Pj as isAttachment,ck as isAttachmentPartRef,qo as isBillingError,_j as isCompactionPart,lr as isConfigured,xM as isContextTool,RD as isDestructivePhase,vi as isEmptyShowPart,tM as isErrorOutput,UE as isExternalUrl,Oo as isFeatureDisabledError,wm as isFilePart,ey as isImpersonationSessionLive,AO as isInstanceDetailPath,zw as isInstanceScopedAppPath,$E as isInternalLocalhostUrl,Wg as isInvisibleActivityPart,IA as isInviteSent,S$ as isLastUserMessage,pA as isManagedGithubProject,Ng as isNoGroupActivityTool,MO as isOpenCodeConfigInvalidError,wj as isPatchPart,ME as isPreviewUrl,mb as isProxiableLocalhostUrl,iE as isQuestionTool,_e as isReasoningPart,Q_ as isRetryableTurnError,PE as isRuntimeReady,Zn as isSandboxNotReadyError,_a as isServerReachable,mE as isSessionAttachmentRef,ku as isSessionFresh,HR as isSessionStartError,sE as isShellActivityTool,lw as isShellMode,G$ as isShortOutput,tE as isShowContentUnavailable,En as isShowPayloadEmpty,xj as isSnapshotPart,Kg as isStandaloneActivityTool,rr as isSubdomainPreviewUrl,be as isTextPart,te as isToolPart,Aj as isToolPartHidden,da as isUnderSandboxRoot,qE as isWebProxyUrl,s_ as isWireIdAheadOf,Uk as kortixAppViewerToken,jy as kortixPty,Ja as leaveAccount,hc as linkGitHubInstallation,lc as linkRepository,cg as listAccountAudit,pg as listAccountAuditWebhooks,La as listAccountInvites,Ua as listAccountMembers,ZC as listAccountResourceGrants,Zc as listAccountSecretResources,AT as listAccountSessions,ng as listAccountTokens,Ta as listAccounts,oT as listActions,iI as listAdminSandboxes,Pd as listAgentIdentities,fl as listAllConnections,Eg as listAppAgents,Dg as listAppDeployments,vg as listApps,Fd as listAssignments,UT as listAuditEvents,$T as listAuditWebhooks,bD as listBackups,mp as listBillingTransactions,du as listChangeRequests,$C as listChannelBindings,BS as listColumns,sR as listConnectSections,rR as listConnectToolkits,ml as listConnections,dl as listConnectorAccounts,Sn as listConnectorTools,Al as listConnectors,SC as listCostByProject,fv as listCredentialEvents,mv as listCredentials,ii as listDiscoverConnectors,iR as listDiscoverIntegrations,Bl as listDiscoverSections,Zo as listEnv,_g as listFeaturedMarketplaces,NS as listFields,wt as listFiles,ed as listGatewayLogs,dc as listGitHubInstallations,mc as listGitHubRepositories,fc as listGitHubRepositoryBranches,_d as listGroupMembers,XC as listGroupProjectGrants,md as listGroups,rv as listKortixProjectSessions,ev as listKortixProjects,na as listKortixPty,gc as listLinkableGitHubInstallations,xc as listManagedGitRepositories,hg as listMarketplaceCatalogItems,kg as listMarketplaceSources,bg as listMarketplaces,QC as listMemberGroups,YC as listMemberProjectAccess,cv as listMilestoneEvents,ov as listMilestones,Na as listMyAccountInvites,jd as listOAuthClients,Uc as listPendingApprovals,Cc as listPendingProjectInvites,Gd as listPermissions,Fl as listPipedreamApps,Ll as listPipedreamSections,eT as listPolicies,Sc as listProjectAccess,wc as listProjectAccessRequests,VS as listProjectAgents,lg as listProjectAudit,ou as listProjectBranches,ig as listProjectCliTokens,au as listProjectCommits,nu as listProjectFiles,Ec as listProjectGroupGrants,Kl as listProjectPolicies,Oc as listProjectResourceGrants,zl as listProjectSandboxTemplates,tu as listProjectSandboxes,Bc as listProjectSecrets,It as listProjectSessions,Su as listProjectSessionsPage,Vl as listProjectSnapshots,Ju as listProjectTriggers,Xe as listProjects,Ya as listProjectsForAccount,WD as listPublicMarketplaceItems,KD as listPublicMarketplaces,HC as listReferrals,Wd as listReviewItems,kd as listRoles,lD as listSandboxProjectMembers,Qd as listSandboxShares,ZO as listSandboxes,cT as listScimTokens,IT as listServiceAccountsApi,xv as listServiceTemplates,_v as listServices,nR as listSessionConnectRequests,jp as listSessionCosts,qu as listSessionPrompts,al as listSessionProviderSecretPools,Ru as listSessionPublicShares,Fc as listSessionsNeedingInput,wT as listSsoGroupMappings,SS as listTaskEvents,kS as listTasks,KS as listTemplates,MS as listTicketEvents,ES as listTickets,Tk as loadHttpSessionHistory,Bm as looksLikeError,$M as looksLikeHtml,vM as looksLikeJsonPayload,kI as mapApiReviewItem,FD as markInstanceError,vn as markSessionFresh,um as maxWireIdClock,Q$ as memoryRelPath,VM as mergeBurstSteps,hu as mergeChangeRequest,QM as messageCreatedAt,Zx as messageTime,cI as migrateAdminSandboxProvider,o_ as mintWireMessageId,dm as mintWireMessageIdAbove,vt as mkdir,Qm as narrateFailedStep,Xm as narrateStep,Hn as narrationToolName,hb as narrowChatEvent,i_ as newestWireIdClock,ce as normalizeActivityToolName,EO as normalizeAppPathname,FE as normalizeExternalInput,z as normalizeName,Bn as normalizeToolName,yu as openChangeRequest,Ni as openEventStream,p0 as openStressTestStream,tn as parseBillingError,CM as parseEmbeddedFailure,PO as parseFlagOverride,ox as parseJsonFailure,$n as parseLocalhostUrl,Y$ as parseMemoryView,Qw as parseOpenCodeErrorPayload,rO as parsePresentationOutput,Jg as parseProxyHop,iO as parseQuestionAnswersFromOutput,cO as parseReadOutput,_x as parseScrapeInputUrls,wx as parseScrapeOutput,im as parseSubdomainUrl,W$ as parseTaskRows,DE as parseWebProxyUrl,Km as parseWebSearchOutput,Gm as partOutcome,iv as patchKortixProject,tO as patchVerb,Ol as pipedreamConnect,Sl as pipedreamConnectConnection,Wl as pipedreamFinalize,vl as pipedreamFinalizeConnection,$ as platformConfig,YA as pollConnectionOAuth2DeviceAuthorization,Hc as pollProjectProviderOAuth,Zp as previewGatewayRoute,dT as previewMfaRequired,jC as previewSlackIdentity,MC as previewTeamsIdentity,Id as probeEffectivePermission,Ed as probeEffectivePermissions,q0 as probePreviewPort,cq as projectCompacting,N0 as projectSessionConnection,KR as projectSessionStartSeed,eq as projectWorking,sc as provisionProject,gA as provisionProjectStream,_A as provisionProjectWithToken,rm as proxyLocalhostUrl,jE as proxyUrlToInternal,Rp as purchaseCredits,KA as putConnectionOAuth2Application,hm as rawErrorText,sD as reactivateSandbox,Pp as reactivateSubscription,Pt as readBlob,kt as readFile,su as readProjectFile,Xx as reasoningIsRunning,Jl as rebuildProjectSnapshot,yl as reconcileConnection,hl as reconcileMemberConnection,Pv as reconcileServices,XD as recordPlatformLogout,ro as recoverLinkResults,NC as refreshReferralCode,$t as refreshSession,xi as registerAppArtifact,JA as registerConnectionOAuth2Client,Sv as registerService,Pc as rejectProjectAccessRequest,Ej as relativizePath,Wu as reloadProjectSessionConfig,Ku as reloadProjectSessionConfigStream,mg as removeAccountAuditWebhook,Da as removeAccountBrandingAsset,za as removeAccountMember,wd as removeGroupMember,ia as removeKortixPty,Sg as removeMarketplaceSource,Wb as removeQueued,kl as renameConnection,bn as renameFile,YO as renameSandbox,_u as reopenChangeRequest,dv as reopenMilestone,Hb as reorderQueued,GS as replaceColumns,WS as replaceFields,uc as replaceProjectRepository,HS as replaceTemplates,QT as requestAccountDeletion,xu as requestChangesOnChangeRequest,TA as requestProjectAccess,yg as requestProjectConnector,fg as requestProjectSecret,Ga as resendAccountInvite,Ic as resendPendingProjectInvite,qa as resetAccountBranding,jv as resetClient,Yp as resetGatewayRoutingPolicy,Oi as resetPassword,Ov as resetPublicClient,jD as resetSandboxUpdateStatus,Lc as resolveApproval,OM as resolveScrapeResults,h$ as resolveWorkingTurn,gC as resolvedPlan,An as restartProjectSession,tD as restartSandbox,xD as restoreBackup,Nb as retryFailed,Fu as retrySessionPrompt,hv as revealCredential,_I as reviewItemTarget,Ch as reviewSegmentForStatus,wI as reviewVerdictForStatus,sl as revokeAccountSecretResourceGrant,RT as revokeAccountSession,sg as revokeAccountToken,Bd as revokeAssignment,_l as revokeConnection,dd as revokeGatewayKey,Tc as revokePendingProjectInvite,Ac as revokeProjectAccess,ag as revokeProjectCliToken,pD as revokeSandboxProjectAccess,Zd as revokeSandboxShare,uT as revokeScimToken,Tu as revokeSessionPublicShare,De as rewriteLocalhostUrl,Bg as rollbackApp,tl as rotateAccountSecretResource,Dd as rotateOAuthClientSecret,gd as runGatewayPlayground,Ey as sanitizePtyChunk,yc as saveGitHubInstallation,Sp as scheduleDowngrade,ll as searchConnectorTools,ru as searchProjectFiles,r$ as segmentTurn,Ei as sendMagicLink,zC as sendReferralEmails,uq as serverCompactionRevalidateAtMs,kv as serviceAction,ER as sessionParentId,zR as sessionStartKey,il as setAccountSecretResourceAccess,TO as setActiveInstanceCookie,iy as setAdminBypass,oI as setAdminProviderDistribution,uI as setAdminProviderFallback,lp as setAgentScope,GP as setBootstrapAuthToken,BP as setCachedAuthToken,tR as setConnectionPolicies,Tl as setConnectorAuthorizationStrategy,Nl as setConnectorCredential,Cl as setConnectorCredentialMode,$l as setConnectorName,jl as setConnectorPolicies,aR as setConnectorSecretBinding,Il as setConnectorSensitive,wl as setDefaultConnection,LT as setEnterpriseDemo,ea as setEnv,cd as setGatewayBudget,Qp as setGatewayRoutingPolicy,h0 as setGitHubAppFromExisting,b0 as setGitHubAppPat,CP as setImpersonationSession,a0 as setMaintenanceConfig,aT as setMemberSuperAdmin,gT as setMfaRequired,op as setModelDefault,Xc as setPersonalProjectSecret,Pi as setProjectModelAccess,eC as setProjectModelEnablement,cc as setProjectOnboardingComplete,hA as setProjectOnboardingProfile,Hl as setProjectPolicies,Nc as setProjectSecretStrategy,Vu as setProjectSessionModel,zu as setProjectSessionScope,vu as setProjectSessionSharing,Zu as setProjectTriggersActivation,fT as setSessionOversight,cl as setSessionProviderSecretPool,PD as setupSSH,Pl as shareConnection,oE as shellActivityGroupLabel,bf as shellExitCode,sy as shouldAttachImpersonation,A$ as shouldHideResponsePart,G_ as shouldShowToolPart,d$ as shouldSuppressWorkingTurnBusy,c$ as showGroupItems,af as showTurnBusyIndicator,Ii as signInWithPassword,Mi as signInWithProvider,Fi as signInWithSso,Bi as signOut,Ti as signUp,gO as skillDocumentPath,dO as skillInputDir,Jj as sortSessions,Sj as splitUserParts,Fg as startApp,XA as startConnectionOAuth2Authorization,QA as startConnectionOAuth2DeviceAuthorization,e0 as startConnectorSetupLink,y0 as startGitHubAppManifest,Kc as startProjectProviderOAuth,Qe as startProjectSession,i0 as startSessionWithToken,CS as startTask,Wm as stepLabel,Lg as stopApp,Rn as stopProjectSession,nD as stopSandbox,Oj as stripAnsi,RO as stripInstancePrefix,ve as stripTrailingSlashes,JD as submitAccessRequest,l0 as submitDemoRequest,YD as submitOAuthConsent,Hd as submitReviewItem,r0 as submitSecretSetupLink,TP as subscribeToImpersonation,ZP as supabaseClient,Rl as syncConnectors,bC as syncSubscription,Dv as systemReload,ze as toDaemonPath,IO as toInstanceAwarePath,fb as toInternalUrl,xt as toSandboxAbsolutePath,ga as toWorkspaceRelative,Vi as toolInfo,Fw as toolViewModel,ED as triggerSandboxUpdate,Ry as triggersRequest,bk as turnEndCause,iq as turnEndNotice,Hj as turnHasSteps,m$ as turnIsConfirmedActive,US as unassignTicket,le as unwrapError,gg as updateAccountAuditWebhook,$a as updateAccountBranding,Va as updateAccountMemberRole,ja as updateAccountName,cC as updateAgentConfig,Cg as updateApp,jg as updateAppAccess,DT as updateAuditWebhook,OC as updateChannelBinding,bl as updateConnectionCredential,Jp as updateEmailPolicy,oc as updateExperimentalFeature,ic as updateFeatureFlag,hd as updateGroup,sa as updateKortixPty,uv as updateMilestone,Od as updateOAuthClient,Di as updatePassword,TT as updatePatPolicy,nT as updatePolicy,ti as updateProject,vc as updateProjectAccess,XS as updateProjectAgent,pp as updateProjectDefaultAgent,Mc as updateProjectGroupGrant,ac as updateProjectSandboxProvider,Bu as updateProjectSession,Qu as updateProjectTrigger,Rd as updateRole,Cd as updateRolePermissions,Yl as updateSandboxTemplate,vT as updateSessionPolicy,RS as updateTask,yA as updateTemplateWarmPool,OS as updateTicket,DS as updateTicketStatus,Ui as updateUserMetadata,Oa as uploadAccountBrandingAsset,$g as uploadAppArtifactArchive,gl as uploadConnectorAttachment,St as uploadFile,kn as uploadPromptAttachment,zg as uploadSessionAttachment,Wp as uploadSlackChannelFile,bt as uploadTimeoutMsForBytes,yv as upsertCredential,Vc as upsertProjectGitCredential,Gc as upsertProjectSecret,hT as upsertSsoProvider,ec as validateProjectManifest,WC as validateReferralCode,Xa as validateToken,FC as verifyGatewayProvider,ji as verifyOtp,_T as verifySsoDomain,bq as wakeEscalationAttemptSummary,hq as wakeEscalationNote,fq as wakeProgressFingerprint,et as wireIdClock,qt as wireIdClockAt,tt as wireIdClockDelta,tq as workingExpiryAtMs,f$ as workingTurnDrawsBusyRow,aE as writeActivityGroupLabel,hn as writeFile,so as wsDomain,MM as wsFavicon,jM as wsRootDomain};
|
|
97
|
+
`:"")+F.slice(5))}}catch(d){if(h||d instanceof DOMException&&d.name==="AbortError")return;a?.(d instanceof Error?d:new Error(String(d)))}}function A(){h=!0,m?.abort(),m=null,g.clear()}function P(k,d){let y=g.get(k)??new Set;y.add(d),g.set(k,y)}function M(k,d){g.get(k)?.delete(d)}return{connect:w,close:A,addEventListener:P,removeEventListener:M}}function Sq(e,t){return $k({...t,url:Mk(e)})}var Ok="/_kortix/viewer";var ir=new Map;function Dk(){ir.clear()}async function qk(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 Mf(e={}){let t=e.path??Ok,n=e.fetch??((i,o)=>fetch(i,o)),r=ir.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=qk(t,n).then(i=>{let o=i?.expires_at?Date.parse(i.expires_at):Number.NaN,a=Number.isFinite(o)?o-6e4:Date.now()+6e4;return ir.set(t,{session:i,expiresAt:a}),i});return ir.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function Uk(e={}){return async()=>(await Mf(e))?.access_token??null}export{Ww as ABORT_REASONS,hO as ABORT_REASONS_NOT_YET_EMITTED,Qn as ACTIVE_INSTANCE_COOKIE,fy as ANALYTICS_UNAVAILABLE_CODE,ak as ATTACHMENT_PART_REF_PREFIX,S as ApiError,oe as AuthError,Me as BillingError,hx as CONTEXT_TOOLS,lf as COST_MARKUP,bx as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,cm as DEFAULT_TRANSCRIPT_OPTIONS,nk as DESTRUCTIVE_PHASES,Ts as FEATURE_DISABLED_CODE,uA as FEATURE_FLAG_KEYS,dy as FEATURE_NOT_SUPPORTED_CODE,Fe as FILE_VERBS,_t as FileExistsError,Mt as HeadlessAuthError,je as HostBoundaryError,Zf as IMPERSONATION_HEADER,J0 as INBOX_OBSERVATION_MAX_MS,Hw as INSTANCE_SCOPED_ROUTES,Jy as MAX_PROMPT_ATTACHMENTS_BYTES,Vs as MAX_PROMPT_ATTACHMENT_BYTES,xa as MAX_PROMPT_ATTACHMENT_FILES,X$ as MEMORY_VERBS,gy as MODEL_NOT_SERVABLE_CODE,Bh as NO_GROUP_ACTIVITY_TOOLS,Q0 as OPTIMISTIC_ABORT_MAX_MS,aq as OPTIMISTIC_COMPACTION_MAX_MS,H0 as OPTIMISTIC_RECEIPT_MAX_MS,gx as PLUMBING_TOOLS,D0 as PREVIEW_PROBE_TIMEOUT_MS,MR as PROJECT_SESSION_NAME_LOOKUP_LIMIT,jR as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,hh as PROJECT_SESSION_PAGE_MAX_LIMIT,my as PROVISION_IN_FLIGHT_CODE,_i as PublicSessionShareError,Ge as RequestTooLargeError,yt as RuntimeNotReadyError,Hs as SANDBOX_FS_ROOTS,Te as SANDBOX_PORTS,xk as SERVER_COMPACTION_REVALIDATE_MS,z0 as SERVER_OBSERVATION_MAX_MS,Gh as STANDALONE_TOOLS,V0 as STREAM_OBSERVATION_MAX_MS,Yn as SandboxNotReadyError,Un as SessionNotReadyError,pi as SessionStartError,X0 as TURN_END_LEDGER_LAG_MS,mq as WAKE_ESCALATION_COOLDOWN_MS,gq as WAKE_MAX_RESTARTS,dq as WAKE_NO_PROGRESS_MS,Wi as WIRE_ID_BACKDATE_MS,qe as WIRE_ID_CLOCK_TOLERANCE,Ee as WIRE_ID_TIME_MASK,Dt as WIRE_ID_TIME_SCALE,t_ as WIRE_MESSAGE_ID,Lk as __getConfigResolver,Fk as __setConfigResolver,bO as abortErrorReason,Ka as acceptAccountInvite,fD as acceptInvite,zd as actReviewItem,xl as activateConnection,xd as addGroupMembers,Pg as addMarketplaceSource,yq as advanceWakeEscalation,X_ as allDescendantIds,Rf as appendPreviewToken,kc as approveProjectAccessRequest,TS as approveTask,ni as archiveProject,qS as assignTicket,jc as attachGroupToProject,Li as authMfa,qi as authUser,q as authenticatedFetch,$0 as authorizePreviewUrl,c as backendApi,IC as bindSlackIdentity,EC as bindTeamsIdentity,Wc as brokerProjectSecretRequest,Vw as buildInstancePath,L0 as buildPresentationTemplateImageUrl,F0 as buildPresentationTemplatePdfUrl,Af as buildPreviewAuthEndpoint,ok as buildPublicTemplateUrl,hk as buildRuntimePresentationConversionUrl,eu as buildSandboxTemplate,xx as buildScrapeFailureResults,IE as buildStaticFileHealthPreviewUrl,TE as buildStaticFileLocalUrl,CE as buildStaticFilePreviewUrl,db as buildStaticFileServicePath,Mk as buildTunnelEventStreamUrl,OE as buildWebProxyUrl,Vd as bulkActReviewItems,sT as bulkDeletePolicies,iT as bulkImportPolicies,gM as burstSummary,mM as burstSummaryLabel,pl as callConnector,YT as cancelAccountDeletion,Ba as cancelAccountInvite,rD as cancelSandbox,MD as cancelSandboxUpdate,vp as cancelScheduledChange,kp as cancelSubscription,VD as checkAccessEmail,Vj as childMapByParent,LD as claimComputer,Lb as claimNext,hC as claimPerSeatBilling,Eu as claimWarmProjectSession,_m as classifyPart,yk as classifyPreviewProbeStatus,Cy as classifyPtyClose,L_ as classifyTurn,nM as cleanErrorMessage,RM as cleanResultSnippet,B$ as cleanWorkerOutput,Lo as clearImpersonationSession,Dk as clearKortixAppViewerCache,ap as clearModelDefault,AR as clearSessionFresh,bu as closeChangeRequest,pv as closeMilestone,Wj as collectTurnParts,FS as commentTicket,wu as commitSessionChanges,lq as compactionExpiryAtMs,yM as compactionTurnInfo,Gj as compareMessagesForDisplay,Bb as completeInFlight,Fp as completeSlackInstall,Lp as completeTeamsInstall,cf as computeStatusFromPart,Tp as configureAutoTopup,cr as configureKortix,xp as confirmCheckoutSession,zp as connectEmail,Dp as connectSlack,W0 as connectionIsFaulted,NA as connectionSharedWithEveryone,fh as connectorConnect,yh as connectorFinalize,LM as contextLabelForTool,wM as contextToolSummary,kM as contextToolTrigger,mI as convertPresentationToGoogleSlides,B0 as convertRuntimePresentation,yn as copyFile,Ep as costExportUrl,Z0 as countLiveInboxPrompts,xI as countReviewItemsBySegment,Ia as createAccount,dg as createAccountAuditWebhook,el as createAccountSecretResource,rg as createAccountToken,Ag as createApp,Mg as createAppAccessSession,Og as createAppDeployment,BM as createArtifactKind,Ld as createAssignment,OT as createAuditWebhook,_D as createBackup,_p as createCheckoutSession,Dl as createConnector,fn as createFile,pd as createGatewayKey,yd as createGroup,Ik as createHttpSessionSyncController,qD as createInstance,Db as createKortix,ra as createKortixPty,Gi as createKortixSession,NI as createMarketplaceInstallSession,lv as createMilestone,$d as createOAuthClient,yC as createPerSeatCheckout,tT as createPolicy,wp as createPortalSession,nc as createProject,JS as createProjectAgent,og as createProjectCliToken,rc as createProjectRepo,Dc as createProjectResourceGrant,Et as createProjectSession,Xu as createProjectTrigger,Ca as createPromptAttachmentController,Ad as createRole,$k as createSSEStream,XO as createSandbox,Yd as createSandboxShare,Ql as createSandboxTemplate,lT as createScimToken,ET as createServiceAccountApi,Du as createSessionPrompt,Cu as createSessionPublicShare,Ub as createSessionQueue,kT as createSsoGroupMapping,AS as createTask,$S as createTicket,Sq as createTunnelEventStream,Ha as declineAccountInvite,yD as declineInvite,ZT as deleteAccountImmediately,nl as deleteAccountSecretResource,Tg as deleteApp,qT as deleteAuditWebhook,wD as deleteBackup,Ul as deleteConnector,bv as deleteCredential,ta as deleteEnv,Ve as deleteFile,ld as deleteGatewayBudget,bc as deleteGitHubInstallation,bd as deleteGroup,UD as deleteInstance,sv as deleteKortixProject,gv as deleteMilestone,qd as deleteOAuthClient,Qc as deletePersonalProjectSecret,rT as deletePolicy,QS as deleteProjectAgent,zc as deleteProjectProviderOAuth,qc as deleteProjectResourceGrant,Jc as deleteProjectSecret,Gu as deleteProjectSession,Yu as deleteProjectTrigger,Ct as deletePromptAttachment,Td as deleteRole,Zl as deleteSandboxTemplate,MT as deleteServiceAccountApi,Uu as deleteSessionPrompt,PT as deleteSsoGroupMapping,xT as deleteSsoProvider,IS as deleteTask,LS as deleteTicket,Wa as describeAccountInvite,ul as describeConnectorTool,$c as detachGroupFromProject,cb as detectLocalhostUrls,jT as disableServiceAccountApi,Vp as disconnectEmail,_0 as disconnectGitHubApp,Gp as disconnectSlack,zA as discoverConnectionOAuth2,VA as discoverConnectionOAuth2Resource,ql as discoverConnectorAuth,eD as discoverLocalSandbox,u0 as downloadAccountAudit,Ev as dropClientForUrl,$v as dropPublicClientForUrl,Kb as editQueued,Fb as enqueue,zS as ensurePmSession,fk as ensurePreviewSessionCookie,WA as ensureProjectConnectorConnection,tk as ensureSandbox,Iu as ensureWarmProjectSession,Ay as env,$i as exchangeCode,ug as exportAccountAudit,de as extractGatewayErrorDetails,Ht as extractInstanceRoute,mw as extractSkillBaseDir,pO as extractSkillContent,pw as extractSkillFiles,N$ as extractWorkerPreview,Gb as failInFlight,g$ as fallbackBusyRowAfterTurnId,io as familyForTool,Do as featureDisabledKey,SO as featureFlags,mC as fetchAccountStateWithToken,iA as fetchAccountsWithToken,P0 as fetchAttachmentPart,AC as fetchCostExportCsv,Mf as fetchKortixAppViewer,iu as fetchProjectArchive,bA as fetchProjectsForAccountWithToken,Vg as fetchSessionAttachment,z$ as filePhase,H$ as fileVerb,zy as files,wi as finalizeAppArtifact,t0 as finalizeConnectorSetupLink,$R as findActiveTranscriptShare,gn as findFiles,Kj as findLastTextPart,fE as findSessionAttachments,mn as findText,ep as fireProjectTrigger,Xl as fixSandboxWithAgent,JM as flattenThought,Uo as formatBillingErrorForUI,$$ as formatCost,E$ as formatDuration,rM as formatJsonFailureOutput,YM as formatMessageDay,ZM as formatMessageExact,Zw as formatOpenCodeRuntimeError,AM as formatRawOutput,Zw as formatRuntimeError,O$ as formatTokens,Yb as formatTranscript,y$ as freshSendHint,qb as generateSessionId,Ea as getAccount,Ma as getAccountBranding,XT as getAccountDeletionStatus,dp as getAccountState,gp as getAccountStateMinimal,Xw as getActiveInstanceIdFromCookie,aI as getAdminProviderAnalytics,sI as getAdminProviderDistribution,lI as getAdminProviderFallback,eI as getAdminRole,K_ as getAgentCardLabel,aC as getAgentConfig,YS as getAgentPersona,ID as getAllVersions,zj as getAnsweredQuestionParts,Rg as getApp,Ig as getAppAccess,qg as getAppDeployment,Ug as getAppDeploymentLogs,FI as getApprovalLink,dt as getAuthToken,NP as getAuthTokenWithRetry,Cp as getAutoTopupSettings,fC as getAutoTopupSetupStatus,yp as getBillingCreditBreakdown,bp as getBillingTierConfigurations,fp as getBillingTransactionsSummary,hp as getBillingUsageHistory,gu as getChangeRequest,mu as getChangeRequestDiff,fu as getChangeRequestMergePreview,Cj as getChildSessionError,Rj as getChildSessionId,Tj as getChildSessionToolParts,Oe as getClient,Re as getClientForUrl,Gl as getConnectStatus,HA as getConnectionOAuth2Application,ZA as getConnectionOAuth2Status,eR as getConnectionPolicies,Sn as getConnectorCatalog,Ml as getConnectorConfig,El as getConnectorPolicies,ZD as getConnectorSetupLink,vC as getCostSummary,Jw as getCurrentInstanceIdFromPathname,CO as getCurrentInstanceIdFromWindow,ba as getCurrentProject,gi as getDefaultAccountState,jj as getDiagnostics,W_ as getDirectory,oi as getDiscoverConnector,oR as getDiscoverIntegration,Kp as getEmailInstallation,Hp as getEmailMode,FT as getEnterpriseDemo,dn as getFileStatus,xm as getFileWithDir,N_ as getFilename,rk as getFullChangelog,sd as getGatewayBreakdown,ad as getGatewayBudgets,od as getGatewayErrors,ud as getGatewayKeys,td as getGatewayLog,nd as getGatewayOverview,Xp as getGatewayRoutingPolicy,rd as getGatewaySeries,id as getGatewaySessions,f0 as getGitHubAppStatus,pc as getGitHubInstallation,gI as getGoogleAuthUrl,fd as getGroup,vj as getHiddenToolParts,ny as getImpersonationSession,mD as getInvite,DD as getJustavpsServerTypes,tv as getKortixProject,nv as getKortixProjectBySession,oa as getKortixPtyWebSocketUrl,TD as getLatestSandboxVersion,o0 as getMaintenanceConfig,_c as getManagedGitBackend,mA as getManagedGitStatus,xg as getMarketplaceCatalogItem,wg as getMarketplaceCatalogItemFile,pT as getMfaRequired,av as getMilestone,ip as getModelDefaults,Md as getOAuthClient,QD as getOAuthConsentRequest,wf as getOpenCodeConfigInvalidError,kj as getPartText,CT as getPatPolicy,Mj as getPermissionForTool,Qs as getProject,ZS as getProjectActivity,cu as getProjectCommit,lu as getProjectCommitDiff,Ys as getProjectDetail,uu as getProjectFileHistory,tc as getProjectGitToken,Zs as getProjectLlmCatalog,dA as getProjectLlmCatalogProviders,ki as getProjectModelAccess,ei as getProjectModelPicker,ai as getProjectSandboxHealth,fA as getProjectSandboxProviderTransition,li as getProjectSession,Nu as getProjectSessionConfigState,Hu as getProjectSessionScope,Ap as getProrationPreview,VO as getProviders,EE as getProxyBaseUrl,Mv as getPublicClientForUrl,HD as getPublicMarketplaceItem,zD as getPublicMarketplaceItemFile,CI as getPublicSessionShare,TI as getPublicSessionShareMessages,s0 as getPublicShareByToken,d0 as getPublicTemplate,$j as getQuestionForTool,GC as getReferralCode,KC as getReferralStats,D$ as getRetryInfo,q$ as getRetryMessage,Kd as getReviewItem,Sd as getRolePermissions,vd as getRoleUsage,SD as getSSHConnection,JO as getSandbox,QO as getSandboxById,GO as getSandboxPortUrl,BD as getSandboxProvisionStatus,GD as getSandboxProvisionStreamUrl,CD as getSandboxUpdateStatus,Sf as getSandboxUrl,n0 as getSecretSetupLink,zs as getServerHealth,wv as getServiceLogs,ju as getSessionAudit,M$ as getSessionCost,fi as getSessionCostRecord,Xg as getSessionHealth,OR as getSessionOpenBundle,mT as getSessionOversight,ST as getSessionPolicy,Au as getSessionPreviewCandidates,ol as getSessionProviderSecretPool,Mu as getSessionTranscript,$u as getSessionTranscriptSync,Ou as getSessionTurn,x$ as getShellModePart,Np as getSlackChannelFile,Op as getSlackInstallation,Bp as getSlackManifest,qp as getSlackMode,yT as getSsoProvider,gb as getStaticFileHealthPath,qs as getSupabaseAccessToken,pt as getSupabaseAccessTokenWithRetry,PS as getTask,vS as getTaskStatus,HI as getTemplate,jS as getTicket,Ij as getToolInfo,no as getToolPrimaryArg,Zb as getTranscriptFilename,j$ as getTurnCost,R$ as getTurnError,T$ as getTurnErrorDetails,C$ as getTurnErrorRawText,I$ as getTurnStatus,Ip as getUsageRollup,c0 as getUserRolesWithToken,pu as getVersionDiff,v$ as getWorkingState,rl as grantAccountSecretResource,uD as grantSandboxProjectAccess,lC as grantSecretToAgent,Nj as groupMessagesIntoTurns,a$ as groupShowSegments,Zm as groupSteps,U$ as hasDiffs,RE as hasLocalhostUrls,pb as hasPreviewTarget,Qj as hasRetryingAssistantTurn,yb as heartbeatGapEvent,Lu as holdSessionPrompts,Xd as humanizeReviewActionPath,Wn as humanizeSearchQuery,zi as humanizeToolName,Bo as impersonationHeaders,bT as importSsoProviderFromMetadata,Y0 as inboxObservationSupersedes,If as initialWakeEscalationState,zI as installTemplate,Us as invalidateTokenCache,Fa as inviteAccountMember,Rc as inviteProjectMember,Za as inviteRepoCollaborator,Jn as isAbortError,oy as isAdminBypassEnabled,bj as isAgentPart,ib as isAppRouteUrl,Pj as isAttachment,ck as isAttachmentPartRef,qo as isBillingError,_j as isCompactionPart,lr as isConfigured,xM as isContextTool,RD as isDestructivePhase,vi as isEmptyShowPart,tM as isErrorOutput,UE as isExternalUrl,Oo as isFeatureDisabledError,wm as isFilePart,ey as isImpersonationSessionLive,AO as isInstanceDetailPath,zw as isInstanceScopedAppPath,$E as isInternalLocalhostUrl,Wg as isInvisibleActivityPart,IA as isInviteSent,S$ as isLastUserMessage,pA as isManagedGithubProject,Ng as isNoGroupActivityTool,MO as isOpenCodeConfigInvalidError,wj as isPatchPart,ME as isPreviewUrl,mb as isProxiableLocalhostUrl,iE as isQuestionTool,_e as isReasoningPart,Q_ as isRetryableTurnError,PE as isRuntimeReady,Zn as isSandboxNotReadyError,_a as isServerReachable,mE as isSessionAttachmentRef,ku as isSessionFresh,HR as isSessionStartError,sE as isShellActivityTool,lw as isShellMode,G$ as isShortOutput,tE as isShowContentUnavailable,En as isShowPayloadEmpty,xj as isSnapshotPart,Kg as isStandaloneActivityTool,rr as isSubdomainPreviewUrl,be as isTextPart,te as isToolPart,Aj as isToolPartHidden,da as isUnderSandboxRoot,qE as isWebProxyUrl,s_ as isWireIdAheadOf,Uk as kortixAppViewerToken,jy as kortixPty,Ja as leaveAccount,hc as linkGitHubInstallation,lc as linkRepository,cg as listAccountAudit,pg as listAccountAuditWebhooks,La as listAccountInvites,Ua as listAccountMembers,ZC as listAccountResourceGrants,Zc as listAccountSecretResources,AT as listAccountSessions,ng as listAccountTokens,Ta as listAccounts,oT as listActions,iI as listAdminSandboxes,Pd as listAgentIdentities,fl as listAllConnections,Eg as listAppAgents,Dg as listAppDeployments,vg as listApps,Fd as listAssignments,UT as listAuditEvents,$T as listAuditWebhooks,bD as listBackups,mp as listBillingTransactions,du as listChangeRequests,$C as listChannelBindings,BS as listColumns,sR as listConnectSections,rR as listConnectToolkits,ml as listConnections,dl as listConnectorAccounts,si as listConnectorTools,Al as listConnectors,SC as listCostByProject,fv as listCredentialEvents,mv as listCredentials,ii as listDiscoverConnectors,iR as listDiscoverIntegrations,Bl as listDiscoverSections,Zo as listEnv,_g as listFeaturedMarketplaces,NS as listFields,wt as listFiles,ed as listGatewayLogs,dc as listGitHubInstallations,mc as listGitHubRepositories,fc as listGitHubRepositoryBranches,_d as listGroupMembers,XC as listGroupProjectGrants,md as listGroups,rv as listKortixProjectSessions,ev as listKortixProjects,na as listKortixPty,gc as listLinkableGitHubInstallations,xc as listManagedGitRepositories,hg as listMarketplaceCatalogItems,kg as listMarketplaceSources,bg as listMarketplaces,QC as listMemberGroups,YC as listMemberProjectAccess,cv as listMilestoneEvents,ov as listMilestones,Na as listMyAccountInvites,jd as listOAuthClients,Uc as listPendingApprovals,Cc as listPendingProjectInvites,Gd as listPermissions,Fl as listPipedreamApps,Ll as listPipedreamSections,eT as listPolicies,Sc as listProjectAccess,wc as listProjectAccessRequests,VS as listProjectAgents,lg as listProjectAudit,ou as listProjectBranches,ig as listProjectCliTokens,au as listProjectCommits,nu as listProjectFiles,Ec as listProjectGroupGrants,Kl as listProjectPolicies,Oc as listProjectResourceGrants,zl as listProjectSandboxTemplates,tu as listProjectSandboxes,Bc as listProjectSecrets,It as listProjectSessions,Su as listProjectSessionsPage,Vl as listProjectSnapshots,Ju as listProjectTriggers,Xe as listProjects,Ya as listProjectsForAccount,WD as listPublicMarketplaceItems,KD as listPublicMarketplaces,HC as listReferrals,Wd as listReviewItems,kd as listRoles,lD as listSandboxProjectMembers,Qd as listSandboxShares,ZO as listSandboxes,cT as listScimTokens,IT as listServiceAccountsApi,xv as listServiceTemplates,_v as listServices,nR as listSessionConnectRequests,jp as listSessionCosts,qu as listSessionPrompts,al as listSessionProviderSecretPools,Ru as listSessionPublicShares,Fc as listSessionsNeedingInput,wT as listSsoGroupMappings,SS as listTaskEvents,kS as listTasks,KS as listTemplates,MS as listTicketEvents,ES as listTickets,Tk as loadHttpSessionHistory,Bm as looksLikeError,$M as looksLikeHtml,vM as looksLikeJsonPayload,kI as mapApiReviewItem,FD as markInstanceError,vn as markSessionFresh,um as maxWireIdClock,Q$ as memoryRelPath,VM as mergeBurstSteps,hu as mergeChangeRequest,QM as messageCreatedAt,Zx as messageTime,cI as migrateAdminSandboxProvider,o_ as mintWireMessageId,dm as mintWireMessageIdAbove,vt as mkdir,Qm as narrateFailedStep,Xm as narrateStep,Hn as narrationToolName,hb as narrowChatEvent,i_ as newestWireIdClock,ce as normalizeActivityToolName,EO as normalizeAppPathname,FE as normalizeExternalInput,z as normalizeName,Bn as normalizeToolName,yu as openChangeRequest,Ni as openEventStream,p0 as openStressTestStream,tn as parseBillingError,CM as parseEmbeddedFailure,PO as parseFlagOverride,ox as parseJsonFailure,$n as parseLocalhostUrl,Y$ as parseMemoryView,Qw as parseOpenCodeErrorPayload,rO as parsePresentationOutput,Jg as parseProxyHop,iO as parseQuestionAnswersFromOutput,cO as parseReadOutput,_x as parseScrapeInputUrls,wx as parseScrapeOutput,im as parseSubdomainUrl,W$ as parseTaskRows,DE as parseWebProxyUrl,Km as parseWebSearchOutput,Gm as partOutcome,iv as patchKortixProject,tO as patchVerb,Ol as pipedreamConnect,Sl as pipedreamConnectConnection,Wl as pipedreamFinalize,vl as pipedreamFinalizeConnection,$ as platformConfig,YA as pollConnectionOAuth2DeviceAuthorization,Hc as pollProjectProviderOAuth,Zp as previewGatewayRoute,dT as previewMfaRequired,jC as previewSlackIdentity,MC as previewTeamsIdentity,Id as probeEffectivePermission,Ed as probeEffectivePermissions,q0 as probePreviewPort,cq as projectCompacting,N0 as projectSessionConnection,KR as projectSessionStartSeed,eq as projectWorking,sc as provisionProject,gA as provisionProjectStream,_A as provisionProjectWithToken,rm as proxyLocalhostUrl,jE as proxyUrlToInternal,Rp as purchaseCredits,KA as putConnectionOAuth2Application,hm as rawErrorText,sD as reactivateSandbox,Pp as reactivateSubscription,Pt as readBlob,kt as readFile,su as readProjectFile,Xx as reasoningIsRunning,Jl as rebuildProjectSnapshot,yl as reconcileConnection,hl as reconcileMemberConnection,Pv as reconcileServices,XD as recordPlatformLogout,ro as recoverLinkResults,NC as refreshReferralCode,$t as refreshSession,xi as registerAppArtifact,JA as registerConnectionOAuth2Client,Sv as registerService,Pc as rejectProjectAccessRequest,Ej as relativizePath,Wu as reloadProjectSessionConfig,Ku as reloadProjectSessionConfigStream,mg as removeAccountAuditWebhook,Da as removeAccountBrandingAsset,za as removeAccountMember,wd as removeGroupMember,ia as removeKortixPty,Sg as removeMarketplaceSource,Wb as removeQueued,kl as renameConnection,bn as renameFile,YO as renameSandbox,_u as reopenChangeRequest,dv as reopenMilestone,Hb as reorderQueued,GS as replaceColumns,WS as replaceFields,uc as replaceProjectRepository,HS as replaceTemplates,QT as requestAccountDeletion,xu as requestChangesOnChangeRequest,TA as requestProjectAccess,yg as requestProjectConnector,fg as requestProjectSecret,Ga as resendAccountInvite,Ic as resendPendingProjectInvite,qa as resetAccountBranding,jv as resetClient,Yp as resetGatewayRoutingPolicy,Oi as resetPassword,Ov as resetPublicClient,jD as resetSandboxUpdateStatus,Lc as resolveApproval,OM as resolveScrapeResults,h$ as resolveWorkingTurn,gC as resolvedPlan,An as restartProjectSession,tD as restartSandbox,xD as restoreBackup,Nb as retryFailed,Fu as retrySessionPrompt,hv as revealCredential,_I as reviewItemTarget,Ch as reviewSegmentForStatus,wI as reviewVerdictForStatus,sl as revokeAccountSecretResourceGrant,RT as revokeAccountSession,sg as revokeAccountToken,Bd as revokeAssignment,_l as revokeConnection,dd as revokeGatewayKey,Tc as revokePendingProjectInvite,Ac as revokeProjectAccess,ag as revokeProjectCliToken,pD as revokeSandboxProjectAccess,Zd as revokeSandboxShare,uT as revokeScimToken,Tu as revokeSessionPublicShare,De as rewriteLocalhostUrl,Bg as rollbackApp,tl as rotateAccountSecretResource,Dd as rotateOAuthClientSecret,gd as runGatewayPlayground,Ey as sanitizePtyChunk,yc as saveGitHubInstallation,Sp as scheduleDowngrade,ll as searchConnectorTools,ru as searchProjectFiles,r$ as segmentTurn,Ei as sendMagicLink,zC as sendReferralEmails,uq as serverCompactionRevalidateAtMs,kv as serviceAction,ER as sessionParentId,zR as sessionStartKey,il as setAccountSecretResourceAccess,TO as setActiveInstanceCookie,iy as setAdminBypass,oI as setAdminProviderDistribution,uI as setAdminProviderFallback,lp as setAgentScope,GP as setBootstrapAuthToken,BP as setCachedAuthToken,tR as setConnectionPolicies,Tl as setConnectorAuthorizationStrategy,Nl as setConnectorCredential,Cl as setConnectorCredentialMode,$l as setConnectorName,jl as setConnectorPolicies,aR as setConnectorSecretBinding,Il as setConnectorSensitive,wl as setDefaultConnection,LT as setEnterpriseDemo,ea as setEnv,cd as setGatewayBudget,Qp as setGatewayRoutingPolicy,h0 as setGitHubAppFromExisting,b0 as setGitHubAppPat,CP as setImpersonationSession,a0 as setMaintenanceConfig,aT as setMemberSuperAdmin,gT as setMfaRequired,op as setModelDefault,Xc as setPersonalProjectSecret,Pi as setProjectModelAccess,eC as setProjectModelEnablement,cc as setProjectOnboardingComplete,hA as setProjectOnboardingProfile,Hl as setProjectPolicies,Nc as setProjectSecretStrategy,Vu as setProjectSessionModel,zu as setProjectSessionScope,vu as setProjectSessionSharing,Zu as setProjectTriggersActivation,fT as setSessionOversight,cl as setSessionProviderSecretPool,PD as setupSSH,Pl as shareConnection,oE as shellActivityGroupLabel,bf as shellExitCode,sy as shouldAttachImpersonation,A$ as shouldHideResponsePart,G_ as shouldShowToolPart,d$ as shouldSuppressWorkingTurnBusy,c$ as showGroupItems,af as showTurnBusyIndicator,Ii as signInWithPassword,Mi as signInWithProvider,Fi as signInWithSso,Bi as signOut,Ti as signUp,gO as skillDocumentPath,dO as skillInputDir,Jj as sortSessions,Sj as splitUserParts,Fg as startApp,XA as startConnectionOAuth2Authorization,QA as startConnectionOAuth2DeviceAuthorization,e0 as startConnectorSetupLink,y0 as startGitHubAppManifest,Kc as startProjectProviderOAuth,Qe as startProjectSession,i0 as startSessionWithToken,CS as startTask,Wm as stepLabel,Lg as stopApp,Rn as stopProjectSession,nD as stopSandbox,Oj as stripAnsi,RO as stripInstancePrefix,ve as stripTrailingSlashes,JD as submitAccessRequest,l0 as submitDemoRequest,YD as submitOAuthConsent,Hd as submitReviewItem,r0 as submitSecretSetupLink,TP as subscribeToImpersonation,ZP as supabaseClient,Rl as syncConnectors,bC as syncSubscription,Dv as systemReload,ze as toDaemonPath,IO as toInstanceAwarePath,fb as toInternalUrl,xt as toSandboxAbsolutePath,ga as toWorkspaceRelative,Vi as toolInfo,Fw as toolViewModel,ED as triggerSandboxUpdate,Ry as triggersRequest,bk as turnEndCause,iq as turnEndNotice,Hj as turnHasSteps,m$ as turnIsConfirmedActive,US as unassignTicket,le as unwrapError,gg as updateAccountAuditWebhook,$a as updateAccountBranding,Va as updateAccountMemberRole,ja as updateAccountName,cC as updateAgentConfig,Cg as updateApp,jg as updateAppAccess,DT as updateAuditWebhook,OC as updateChannelBinding,bl as updateConnectionCredential,Jp as updateEmailPolicy,oc as updateExperimentalFeature,ic as updateFeatureFlag,hd as updateGroup,sa as updateKortixPty,uv as updateMilestone,Od as updateOAuthClient,Di as updatePassword,TT as updatePatPolicy,nT as updatePolicy,ti as updateProject,vc as updateProjectAccess,XS as updateProjectAgent,pp as updateProjectDefaultAgent,Mc as updateProjectGroupGrant,ac as updateProjectSandboxProvider,Bu as updateProjectSession,Qu as updateProjectTrigger,Rd as updateRole,Cd as updateRolePermissions,Yl as updateSandboxTemplate,vT as updateSessionPolicy,RS as updateTask,yA as updateTemplateWarmPool,OS as updateTicket,DS as updateTicketStatus,Ui as updateUserMetadata,Oa as uploadAccountBrandingAsset,$g as uploadAppArtifactArchive,gl as uploadConnectorAttachment,St as uploadFile,kn as uploadPromptAttachment,zg as uploadSessionAttachment,Wp as uploadSlackChannelFile,bt as uploadTimeoutMsForBytes,yv as upsertCredential,Vc as upsertProjectGitCredential,Gc as upsertProjectSecret,hT as upsertSsoProvider,ec as validateProjectManifest,WC as validateReferralCode,Xa as validateToken,FC as verifyGatewayProvider,ji as verifyOtp,_T as verifySsoDomain,bq as wakeEscalationAttemptSummary,hq as wakeEscalationNote,fq as wakeProgressFingerprint,et as wireIdClock,qt as wireIdClockAt,tt as wireIdClockDelta,tq as workingExpiryAtMs,f$ as workingTurnDrawsBusyRow,aE as writeActivityGroupLabel,hn as writeFile,so as wsDomain,MM as wsFavicon,jM as wsRootDomain};
|