@kortix/sdk 0.14.4 → 0.14.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -16
- package/dist/browser/session-sync/server-transcript-mirror.d.ts +6 -0
- package/dist/browser/session-sync/server-transcript-mirror.d.ts.map +1 -1
- package/dist/browser/session-sync/server-transcript-mirror.js +6 -0
- package/dist/browser/session-sync/server-transcript-mirror.js.map +1 -1
- package/dist/browser/session-sync/session-sync-registry.d.ts +9 -6
- package/dist/browser/session-sync/session-sync-registry.d.ts.map +1 -1
- package/dist/browser/session-sync/session-sync-registry.js +17 -8
- package/dist/browser/session-sync/session-sync-registry.js.map +1 -1
- package/dist/core/client/capture.d.ts +50 -0
- package/dist/core/client/capture.d.ts.map +1 -1
- package/dist/core/client/capture.js +5 -0
- package/dist/core/client/capture.js.map +1 -1
- package/dist/core/client/kortix.d.ts +26 -0
- package/dist/core/client/kortix.d.ts.map +1 -1
- package/dist/core/client/project-core.d.ts.map +1 -1
- package/dist/core/client/session-handle.d.ts +1 -0
- package/dist/core/client/session-handle.d.ts.map +1 -1
- package/dist/core/client/session-lifecycle-security.d.ts +10 -2
- package/dist/core/client/session-lifecycle-security.d.ts.map +1 -1
- package/dist/core/client/session-lifecycle-security.js +10 -2
- package/dist/core/client/session-lifecycle-security.js.map +1 -1
- package/dist/core/models/composer-model.d.ts +7 -4
- package/dist/core/models/composer-model.d.ts.map +1 -1
- package/dist/core/models/composer-model.js +12 -8
- package/dist/core/models/composer-model.js.map +1 -1
- package/dist/core/models/model-flatten.d.ts +15 -5
- package/dist/core/models/model-flatten.d.ts.map +1 -1
- package/dist/core/models/model-flatten.js +8 -6
- package/dist/core/models/model-flatten.js.map +1 -1
- package/dist/core/models/model-visibility.d.ts +1 -0
- package/dist/core/models/model-visibility.d.ts.map +1 -1
- package/dist/core/models/model-visibility.js +10 -13
- package/dist/core/models/model-visibility.js.map +1 -1
- package/dist/core/rest/platform-client/capture.d.ts +76 -1
- package/dist/core/rest/platform-client/capture.d.ts.map +1 -1
- package/dist/core/rest/platform-client/capture.js +14 -0
- package/dist/core/rest/platform-client/capture.js.map +1 -1
- package/dist/core/rest/projects-client/billing.d.ts +2 -0
- package/dist/core/rest/projects-client/billing.d.ts.map +1 -1
- package/dist/core/rest/projects-client/billing.js.map +1 -1
- package/dist/core/rest/projects-client/change-requests.d.ts +6 -0
- package/dist/core/rest/projects-client/change-requests.d.ts.map +1 -1
- package/dist/core/rest/projects-client/change-requests.js.map +1 -1
- package/dist/core/rest/projects-client/git-history.d.ts +12 -0
- package/dist/core/rest/projects-client/git-history.d.ts.map +1 -1
- package/dist/core/rest/projects-client/git-history.js.map +1 -1
- package/dist/core/rest/projects-client/projects.d.ts +10 -5
- package/dist/core/rest/projects-client/projects.d.ts.map +1 -1
- package/dist/core/rest/projects-client/projects.js +0 -1
- package/dist/core/rest/projects-client/projects.js.map +1 -1
- package/dist/core/rest/projects-client/session-reminders.d.ts +2 -0
- package/dist/core/rest/projects-client/session-reminders.d.ts.map +1 -1
- package/dist/core/rest/projects-client/session-reminders.js +4 -0
- package/dist/core/rest/projects-client/session-reminders.js.map +1 -1
- package/dist/core/rest/projects-client/sessions.d.ts +17 -2
- package/dist/core/rest/projects-client/sessions.d.ts.map +1 -1
- package/dist/core/rest/projects-client/sessions.js +3 -0
- package/dist/core/rest/projects-client/sessions.js.map +1 -1
- package/dist/core/session/control-stream.d.ts.map +1 -1
- package/dist/core/session/control-stream.js +2 -1
- package/dist/core/session/control-stream.js.map +1 -1
- package/dist/core/session/open-bundle.d.ts +2 -0
- package/dist/core/session/open-bundle.d.ts.map +1 -1
- package/dist/core/session/open-bundle.js +2 -0
- package/dist/core/session/open-bundle.js.map +1 -1
- package/dist/core/session-log/shell-exit.d.ts +18 -0
- package/dist/core/session-log/shell-exit.d.ts.map +1 -0
- package/dist/core/session-log/shell-exit.js +52 -0
- package/dist/core/session-log/shell-exit.js.map +1 -0
- package/dist/core/session-log/source.d.ts +0 -4
- package/dist/core/session-log/source.d.ts.map +1 -1
- package/dist/core/session-log/source.js +4 -9
- package/dist/core/session-log/source.js.map +1 -1
- package/dist/core/session-log/store.d.ts.map +1 -1
- package/dist/core/session-log/store.js +8 -2
- package/dist/core/session-log/store.js.map +1 -1
- package/dist/core/session-log/turns/turn.d.ts +2 -0
- package/dist/core/session-log/turns/turn.d.ts.map +1 -1
- package/dist/core/session-log/turns/turn.js +26 -2
- package/dist/core/session-log/turns/turn.js.map +1 -1
- package/dist/core/session-sync/saved-transcript.d.ts +21 -20
- package/dist/core/session-sync/saved-transcript.d.ts.map +1 -1
- package/dist/core/session-sync/saved-transcript.js +16 -18
- package/dist/core/session-sync/saved-transcript.js.map +1 -1
- package/dist/core/turns/tools/tool-outcome.d.ts.map +1 -1
- package/dist/core/turns/tools/tool-outcome.js +28 -3
- package/dist/core/turns/tools/tool-outcome.js.map +1 -1
- package/dist/core/turns/tools/web-helpers.d.ts +3 -0
- package/dist/core/turns/tools/web-helpers.d.ts.map +1 -1
- package/dist/core/turns/tools/web-helpers.js +5 -0
- package/dist/core/turns/tools/web-helpers.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/kortix.esm.min.js +39 -39
- package/dist/kortix.global.js +39 -39
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.d.ts.map +1 -1
- package/dist/react/index.js +1 -1
- package/dist/react/index.js.map +1 -1
- package/dist/react/opencode.js +1 -1
- package/dist/react/opencode.js.map +1 -1
- package/dist/react/query-contracts.d.ts +1 -0
- package/dist/react/query-contracts.d.ts.map +1 -1
- package/dist/react/query-contracts.js +1 -0
- package/dist/react/query-contracts.js.map +1 -1
- package/dist/react/query-keys.d.ts +2 -0
- package/dist/react/query-keys.d.ts.map +1 -1
- package/dist/react/query-keys.js +2 -0
- package/dist/react/query-keys.js.map +1 -1
- package/dist/react/session-start-stash.d.ts +1 -1
- package/dist/react/session-start-stash.js +1 -1
- package/dist/react/use-admin-accounts.d.ts +1 -0
- package/dist/react/use-admin-accounts.d.ts.map +1 -1
- package/dist/react/use-admin-accounts.js.map +1 -1
- package/dist/react/use-capture.d.ts +25 -1
- package/dist/react/use-capture.d.ts.map +1 -1
- package/dist/react/use-capture.js +19 -1
- package/dist/react/use-capture.js.map +1 -1
- package/dist/react/use-kortix-master.js +1 -1
- package/dist/react/use-reminders.d.ts +32 -2
- package/dist/react/use-reminders.d.ts.map +1 -1
- package/dist/react/use-reminders.js +15 -5
- package/dist/react/use-reminders.js.map +1 -1
- package/dist/react/use-session-log.d.ts +7 -9
- package/dist/react/use-session-log.d.ts.map +1 -1
- package/dist/react/use-session-log.js +9 -13
- package/dist/react/use-session-log.js.map +1 -1
- package/dist/react/use-session-sync.d.ts +10 -7
- package/dist/react/use-session-sync.d.ts.map +1 -1
- package/dist/react/use-session-sync.js +24 -8
- package/dist/react/use-session-sync.js.map +1 -1
- package/dist/react/use-session.d.ts.map +1 -1
- package/dist/react/use-session.js +7 -6
- package/dist/react/use-session.js.map +1 -1
- package/package.json +2 -2
package/dist/kortix.esm.min.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var nx={backendUrl:"",getToken:async()=>null},Xo=null,sr=null;function WM(e){sr=e}function HM(){return sr}function Zo(e,t){t?.global!==!1&&(Xo=e)}function C(){return sr?.()??Xo??nx}function es(){return Xo!==null||sr?.()!==void 0}function rx(e){return new Promise(t=>setTimeout(t,e))}async function ir(e,t,n){let r=Math.max(1,t?.attempts??1),o=t?.baseDelayMs??0,s=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(s&&n?.(),o>0&&await rx(o)),i=await e(),i)return i;return i}var ts=12e4;function ox(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Na(e,t,n=ts){let r=e instanceof Request?e.signal:t?.signal;if(ox(e))return r??void 0;let o=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,o]):r:o}function ar(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var S=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:o,...s}=n;Object.assign(this,s),r&&(this.name=r),o&&(this.stack=o);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},ie=class extends S{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},ut=class extends S{constructor(t,n,r,o={}){super(r||n.message||`Billing Error: ${t}`,{...o,status:t,detail:n}),this.name="BillingError"}},kt=class extends S{constructor(t=431,n,r){let o="Request headers are too large";super(r||n?.message||o,{status:t,detail:{message:n?.message||o,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},sx="ENDPOINT_RETIRED";function F(e,t){let n=t?` ${t}`:"";return new S(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:sx})}var en="feature_disabled";function Ba(e){if(!(e instanceof S)||e.status!==403||e.code!==en)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Ka(e){let t=Ba(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function qa(e){let t=Ba(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}var cr="repository_disconnected",ix=new Set(["app_uninstalled","app_suspended","repo_not_accessible"]);function ax(e){return!!e&&typeof e=="object"&&e.code===cr}function cx(e){if(e?.status!=="error")return null;let t=e.last_error_code;return t&&ix.has(t)?t:null}function lr(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new ut(t,{message:r?.message||e.message||"Billing error",...r},void 0,{code:e.code,details:e.details,data:e.data,response:e.response,url:e.url,endpoint:e.endpoint})}function Ga(e){return e instanceof ut}function tn(e){if(e instanceof ie)return!0;let t=e?.status;return t===401||t===403}function Wa(e){if(!(e instanceof ut))return null;let t=e.detail?.message?.toLowerCase()||"";return t.includes("credit")||t.includes("balance")||t.includes("insufficient")?{alertTitle:"You ran out of credits",alertSubtitle:"Upgrade your plan to get more credits and continue using the AI assistant."}:{alertTitle:"Billing check failed",alertSubtitle:e.detail?.message||"Please upgrade to continue."}}function ke(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function ve(e,t){return new Promise((n,r)=>{let o=()=>{t.removeEventListener("abort",o),r(ke())};t.addEventListener("abort",o,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",o)),t.aborted&&o()})}function ur(e,t){return new Promise((n,r)=>{let o=()=>{clearTimeout(s),t?.removeEventListener("abort",o),r(ke())},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.aborted?o():t?.addEventListener("abort",o,{once:!0})})}var Ha="request_deadline",lx=/^Request exceeded the \d+s server processing deadline$/,Va=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Ha||lx.test(n),ux="git_mirror_unavailable",px=/^git mirror is temporarily unavailable$/,dx=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===ux||px.test(n),gx="connectors_provider_unavailable",mx=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===gx;async function fx(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await ve(e.json(),t),typeof r.message=="string"?n=r.message:r.error&&typeof r.error=="string"?n=r.error:typeof r.detail=="string"?n=r.detail:typeof r.detail?.message=="string"?n=r.detail.message:typeof r.reason=="string"&&(n=r.reason)}catch{}if(t.aborted)throw ke();return{message:n,data:r}}function yx(e,t,n){return Va(e,t,n)||dx(e,t,n)||mx(e,t)||e===403&&t?.code===en||e===501&&t?.code===Ya||e===409&&(t?.code===Ja||t?.code===Qa||t?.code===Xa||t?.code===cr)||e===503&&(t?.code===Za||t?.code===ec)}async function za(e,t,n,r){let{message:o,data:s}=await fx(e,t),i=new S(o,{status:e.status,response:e,details:s||void 0,data:s,detail:s?.detail,code:Va(e.status,s,o)?Ha:s?.code||s?.error_code||s?.detail?.error_code||e.status.toString()});e.status===402&&(i=lr(i));let a=e.status===403&&(s?.code==="account_mfa_required"||s?.code==="sso_required")?s.code:null;if(a){try{C().onAccessRemedy?.(a)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a==="account_mfa_required"?"kortix:mfa-required":"kortix:sso-required"))}catch{}}return e.status===431&&(i=new kt(431,{message:"Request is too large to process",suggestion:"Try uploading files one at a time, or reduce the number of files attached to your message."})),n&&!yx(e.status,s,o)&&C().onError?.(i,r),{error:i,success:!1}}var hx="X-Kortix-Impersonate",rs="kortix.impersonation",pt=null,pr=!1,ns=new Set;function os(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function _x(e,t=Date.now()){if(!e||!e.grantId||!e.accountId)return!1;let n=Date.parse(e.expiresAt);return Number.isFinite(n)&&n>t}function bx(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.grantId!="string"||typeof t?.accountId!="string"?null:{grantId:t.grantId,accountId:t.accountId,accountName:typeof t.accountName=="string"?t.accountName:null,expiresAt:typeof t.expiresAt=="string"?t.expiresAt:""}}catch{return null}}function tc(){for(let e of ns)try{e()}catch{}}function Px(){return pr||(pr=!0,pt=bx(os()?.getItem(rs)??null)),pt&&!_x(pt)?(nc(),null):pt}function nO(e){if(pr=!0,!e){nc();return}pt=e;try{os()?.setItem(rs,JSON.stringify(e))}catch{}tc()}function nc(){pr=!0;let e=pt!==null;pt=null;try{os()?.removeItem(rs)}catch{}e&&tc()}function rO(e){return ns.add(e),()=>{ns.delete(e)}}var Sx=/(^|\/)admin\/(api|analytics)(\/|$)/;function xx(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!Sx.test(t)}function rc(e){if(e!==void 0&&!xx(e))return{};let t=Px();return t?{[hx]:t.grantId}:{}}function wx(e){}function kx(){return!1}function vx(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function dr(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function nn(e,t,n){let r=t.toLowerCase();for(let o of Object.keys(e))o.toLowerCase()===r&&delete e[o];e[t]=n}function gr(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[o,s]of r.flatMap(vx))nn(n,o,s);return n}function is(e,t,n){let r={...t},o=C().clientVersion?.trim();o&&!dr(r,"x-kortix-client-version")&&nn(r,"X-Kortix-Client-Version",o);for(let[i,a]of Object.entries(rc(e)))nn(r,i,a);let s=C().credentialHeader?.trim();return s?dr(r,s)||nn(r,s,n):dr(r,"authorization")||nn(r,"Authorization",`Bearer ${n}`),r}async function vt(e,t){let n=await mr();if(!n)throw new ie;return{headers:new Headers(is(e,gr(e,{headers:t}),n)),rejected:()=>rn(n)}}function Ax(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function oc(e,t,n,r,o){if(t instanceof Request){let l=new Headers(is(t.url,gr(t,n),r));return e(new Request(t,{headers:l,...o?{signal:o}:{}}))}let s=String(t),i=is(s,gr(t,n),r),a=s.startsWith("/")&&!s.startsWith("//");return e(s,{...n,headers:i,...a?{credentials:"same-origin"}:{},...o?{signal:o}:{}})}var sc=null;async function as(e){let t=await ir(()=>C().getToken(),e);return t&&(sc=t),t}var mr=as;function rn(e=sc){e&&C().getToken.invalidate?.(e)}var ss=new Map;function Rx(e){let t=ss.get(e);if(t)return t;let n=(async()=>(rn(e),mr({attempts:2,baseDelayMs:200})))().finally(()=>ss.delete(e));return ss.set(e,n),n}async function dt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:o=ts}=n,s=n.fetch??C().fetch??fetch,i=o===null?(e instanceof Request?e.signal:t.signal)??void 0:Na(e,t,o);if(i?.aborted)throw ke();let a=await(i?ve(mr(),i):mr());if(!a)throw new ie;let l=r&&!Ax(t)&&!dr(gr(e,t),"authorization"),p=l&&e instanceof Request?e.clone():e,d=await oc(s,e,t,a,i);if(d.status!==401||!l)return d;let g=await Rx(a);return!g||g===a?d:oc(s,p,t,g,i)}async function Oe(e,t,n,r){let o=await dt(e,t,n);if(o.ok)return o;let s=await o.text().catch(()=>"");throw new S(s||`${r} (HTTP ${o.status})`,{status:o.status,response:o})}var ic=()=>C().backendUrl||"",Cx=new Set([502,503,504]),Tx=e=>Cx.has(e),ac=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},Ix=e=>ac(e)||(e??"GET").toUpperCase()==="DELETE",Ex=2,fr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function De(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:o=3e4,deadlineCoversBody:s=!1,...i}=t,a=new AbortController,l={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>l.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await Mx(e,i,n,r,o,s,a,l)}finally{i.signal?.removeEventListener("abort",p)}}async function Mx(e,t,n,r,o,s,i,a){try{if(t.signal?.aborted)throw ke();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},o);let l={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await Dx(e,t,l,o,s,i,a);if(p instanceof ie)return{error:p,success:!1};if(!p.ok)return await za(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await ve(p.json(),a.activeController.signal):g?.includes("text/")?d=await ve(p.text(),a.activeController.signal):d=await ve(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(l){return Lx(l,e,t.method,n,r,o,a)}finally{yr(a)}}function yr(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function Ox(e,t,n){try{await ve(e.arrayBuffer(),t)}catch(r){if(fr(r))throw r}finally{yr(n)}}async function Dx(e,t,n,r,o,s,i){let a=ac(t.method),l=Ix(t.method),p=l?Ex+1:1,d;for(let g=0;g<p;g++){g>0&&await ur(250*2**(g-1),t.signal??void 0);let m=g===0?s:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await ve(dt(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(f){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),f instanceof ie)return new ie;if(i.didTimeout&&fr(f)&&!t.signal?.aborted&&l&&g<p-1){i.didTimeout=!1;continue}if(fr(f)||g===p-1)throw f;continue}if(!a||!Tx(d.status)||g===p-1)return o||yr(i),d;await Ox(d,m.signal,i)}return d}function Lx(e,t,n,r,o,s,i){yr(i);let a=fr(e);a&&(i.isAborted=!0);let l;if(a){if(!i.didTimeout)return{error:new S("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(ic(),"")||t;l=new S(`Request timed out after ${Math.round(s/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:s})}else e instanceof Error?(l=new S(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(ic(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&C().onError?.(l,o)):(l=new S(String(e)),r&&C().onError?.(l,o));return{error:l,success:!1}}var Le=()=>C().backendUrl||"",Ya="feature_not_supported",Ja="model_not_servable",Qa="provision_in_flight",Xa="sandbox_state_change_in_progress",Za="analytics_unavailable",ec="accounts_list_unavailable",xO={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let o=new S(r.message||"Database error",{code:r.code,details:r});return C().onError?.(o,t),{error:o,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new S(n.message,{name:n.name||"ApiError",stack:n.stack}):new S(String(n));return C().onError?.(r,t),{error:r,success:!1}}}};async function jx(e,t,n={}){let{timeout:r=3e4,fetch:o}=n,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return await dt(`${Le()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:s.signal,credentials:"omit"},{timeoutMs:null,fetch:o})}catch(a){if(a instanceof ie)return ar();throw a}finally{clearTimeout(i)}}var c={putRaw:(e,t,n)=>De(`${Le()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>De(`${Le()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>De(`${Le()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>De(`${Le()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>De(`${Le()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>De(`${Le()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],De(`${Le()}${e}`,{...o,method:"POST",body:t,headers:s})},uploadPut:(e,t,n)=>{let{headers:r,...o}=n||{},s={...r};return delete s["Content-Type"],De(`${Le()}${e}`,{...o,method:"PUT",body:t,headers:s})},postStream:jx};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function cs(e){return e.replace(/\/v1\/?$/,"")}async function At(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=cs(e.backendUrl);try{let r=await fetch(`${n}${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(e.timeoutMs??8e3)});return r.ok?await r.json():null}catch{return null}}async function cc(){return u(await c.get("/accounts"))}async function lc(e){return u(await c.post("/accounts",e))}async function uc(e){return u(await c.get(`/accounts/${e}`))}async function pc(e,t){return u(await c.patch(`/accounts/${e}`,{name:t}))}async function dc(e){return u(await c.get(`/accounts/${e}/branding`))}async function gc(e,t){return u(await c.put(`/accounts/${e}/branding`,t))}async function mc(e,t,n,r){let o=new FormData;return o.append("file",n,r??(n instanceof File?n.name:t)),u(await c.upload(`/accounts/${e}/branding/assets/${t}`,o))}async function fc(e,t){return u(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function yc(e){return u(await c.delete(`/accounts/${e}/branding`))}async function hc(e){return u(await c.get(`/accounts/${e}/members`))}async function _c(e,t){return u(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function bc(e){return u(await c.get(`/accounts/${e}/invites`))}async function Pc(e,t){return u(await c.delete(`/accounts/${e}/invites/${t}`))}async function Sc(e,t){return u(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function xc(){return u(await c.get("/account-invites",{showErrors:!1})).invites}async function wc(e){return u(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function ls(e){return u(await c.post(`/account-invites/${e}/accept`,{}))}function $x(e,t){let n=e.bootstrap_grants_applied?.[0]??t?.projects?.[0];return n?{kind:"project",projectId:n.project_id,accountId:e.account_id}:{kind:"account",accountId:e.account_id}}async function kc(e,t){let n=await ls(e);return{accepted:n,landing:$x(n,t)}}async function vc(e){return u(await c.post(`/account-invites/${e}/decline`,{}))}async function Ac(e,t){return u(await c.delete(`/accounts/${e}/members/${t}`))}async function Rc(e,t,n){return u(await c.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Cc(e){return u(await c.post(`/accounts/${e}/leave`,{}))}async function TO(e){return At(e,"/v1/accounts")}async function Tc(){let e=await c.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var DO=["marketplace","connectors_api_discover","agentmail_email","meta_agent","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","genui","us_region","event_triggers","notification_center","volumes","drives","session_log","session_log_restore","connectors_v2","agent_rooms","goals"];async function Rt(){return u(await c.get("/projects"))}async function Ec(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/projects${t}`))}async function Ct(e,t){return u(await c.get(`/projects/${e}`,t))}async function Mc(e,t,n="write"){return u(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Oc(e,t){return u(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Dc(e){return u(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function LO(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function hr(e,t){let n=u(await c.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function _r(e,t){return u(await c.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function br(e,t){return u(await c.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function jO(e,t){return u(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Lc(e){return u(await c.post("/projects",e))}async function jc(e){return u(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function $c(e,t={}){return u(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var Ux="provision_stream_unterminated",Ic=200;function Fx(e){let t=e.split(`
|
|
1
|
+
var iP={backendUrl:"",getToken:async()=>null},Qs=null,ir=null;function QM(e){ir=e}function XM(){return ir}function Xs(e,t){t?.global!==!1&&(Qs=e)}function I(){return ir?.()??Qs??iP}function Zs(){return Qs!==null||ir?.()!==void 0}function aP(e){return new Promise(t=>setTimeout(t,e))}async function ar(e,t,n){let r=Math.max(1,t?.attempts??1),s=t?.baseDelayMs??0,o=t?.invalidateBetweenAttempts??!1,i=null;for(let a=0;a<r;a++)if(a>0&&(o&&n?.(),s>0&&await aP(s)),i=await e(),i)return i;return i}var eo=12e4;function cP(e){return(e instanceof Request?e.url:String(e)).includes("/global/event")}function Fa(e,t,n=eo){let r=e instanceof Request?e.signal:t?.signal;if(cP(e))return r??void 0;let s=AbortSignal.timeout(n);return r?typeof AbortSignal.any=="function"?AbortSignal.any([r,s]):r:s}function cr(){return new Response(JSON.stringify({error:"Not authenticated"}),{status:401,headers:{"Content-Type":"application/json"}})}var P=class extends Error{status;code;details;data;detail;response;url;endpoint;timeout;constructor(t,n={}){super(t),this.name="ApiError";let{name:r,stack:s,...o}=n;Object.assign(this,o),r&&(this.name=r),s&&(this.stack=s);let i=typeof t=="string"?t:t==null?"":String(t);Object.defineProperty(this,"message",{value:i,enumerable:!0,writable:!0,configurable:!0}),Object.setPrototypeOf(this,new.target.prototype)}},ie=class extends P{constructor(t="Not authenticated"){super(t,{code:"NO_SESSION"}),this.name="AuthError"}},ut=class extends P{constructor(t,n,r,s={}){super(r||n.message||`Billing Error: ${t}`,{...s,status:t,detail:n}),this.name="BillingError"}},kt=class extends P{constructor(t=431,n,r){let s="Request headers are too large";super(r||n?.message||s,{status:t,detail:{message:n?.message||s,suggestion:n?.suggestion||"Try uploading files one at a time, or reduce the number of files in a single request."}}),this.name="RequestTooLargeError"}},lP="ENDPOINT_RETIRED";function N(e,t){let n=t?` ${t}`:"";return new P(`${e}() is retired: the Kortix API no longer serves this endpoint.${n}`,{code:lP})}var en="feature_disabled";function Na(e){if(!(e instanceof P)||e.status!==403||e.code!==en)return null;let t=e.details??e.data;return t&&typeof t=="object"?t:{}}function Ba(e){let t=Na(e);return t?(typeof t.feature=="string"&&!e.feature&&(e.feature=t.feature),!0):!1}function Ka(e){let t=Na(e);if(!t)return null;let n=e.feature;return typeof n=="string"?n:typeof t.feature=="string"?t.feature:null}var lr="repository_disconnected",uP=new Set(["app_uninstalled","app_suspended","repo_not_accessible"]);function pP(e){return!!e&&typeof e=="object"&&e.code===lr}function dP(e){if(e?.status!=="error")return null;let t=e.last_error_code;return t&&uP.has(t)?t:null}function ur(e){let t=e.response?.status||e.status;if(t!==402)return e;let n=e.response?.data||e.data||e.detail||{},r=n?.detail||n;return new ut(t,{message:r?.message||e.message||"Billing error",...r},void 0,{code:e.code,details:e.details,data:e.data,response:e.response,url:e.url,endpoint:e.endpoint})}function qa(e){return e instanceof ut}function tn(e){if(e instanceof ie)return!0;let t=e?.status;return t===401||t===403}function Ga(e){if(!(e instanceof ut))return null;let t=e.detail?.message?.toLowerCase()||"";return t.includes("credit")||t.includes("balance")||t.includes("insufficient")?{alertTitle:"You ran out of credits",alertSubtitle:"Upgrade your plan to get more credits and continue using the AI assistant."}:{alertTitle:"Billing check failed",alertSubtitle:e.detail?.message||"Please upgrade to continue."}}function ke(){return typeof DOMException=="function"?new DOMException("Aborted","AbortError"):Object.assign(new Error("Aborted"),{name:"AbortError"})}function ve(e,t){return new Promise((n,r)=>{let s=()=>{t.removeEventListener("abort",s),r(ke())};t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s)),t.aborted&&s()})}function pr(e,t){return new Promise((n,r)=>{let s=()=>{clearTimeout(o),t?.removeEventListener("abort",s),r(ke())},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.aborted?s():t?.addEventListener("abort",s,{once:!0})})}var Wa="request_deadline",gP=/^Request exceeded the \d+s server processing deadline$/,Ha=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===Wa||gP.test(n),mP="git_mirror_unavailable",fP=/^git mirror is temporarily unavailable$/,yP=(e,t,n)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===mP||fP.test(n),hP="connectors_provider_unavailable",_P=(e,t)=>e!==503?!1:(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)===hP;async function bP(e,t){let n=`HTTP ${e.status}: ${e.statusText}`,r=null;try{r=await ve(e.json(),t),typeof r.message=="string"?n=r.message:r.error&&typeof r.error=="string"?n=r.error:typeof r.detail=="string"?n=r.detail:typeof r.detail?.message=="string"?n=r.detail.message:typeof r.reason=="string"&&(n=r.reason)}catch{}if(t.aborted)throw ke();return{message:n,data:r}}function SP(e,t,n){return Ha(e,t,n)||yP(e,t,n)||_P(e,t)||e===403&&t?.code===en||e===501&&t?.code===za||e===409&&(t?.code===Ya||t?.code===Ja||t?.code===Qa||t?.code===lr)||e===503&&(t?.code===Xa||t?.code===Za)}async function Va(e,t,n,r){let{message:s,data:o}=await bP(e,t),i=new P(s,{status:e.status,response:e,details:o||void 0,data:o,detail:o?.detail,code:Ha(e.status,o,s)?Wa:o?.code||o?.error_code||o?.detail?.error_code||e.status.toString()});e.status===402&&(i=ur(i));let a=e.status===403&&(o?.code==="account_mfa_required"||o?.code==="sso_required")?o.code:null;if(a){try{I().onAccessRemedy?.(a)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent(a==="account_mfa_required"?"kortix:mfa-required":"kortix:sso-required"))}catch{}}return e.status===431&&(i=new kt(431,{message:"Request is too large to process",suggestion:"Try uploading files one at a time, or reduce the number of files attached to your message."})),n&&!SP(e.status,o,s)&&I().onError?.(i,r),{error:i,success:!1}}var xP="X-Kortix-Impersonate",no="kortix.impersonation",pt=null,dr=!1,to=new Set;function ro(){try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}}function PP(e,t=Date.now()){if(!e||!e.grantId||!e.accountId)return!1;let n=Date.parse(e.expiresAt);return Number.isFinite(n)&&n>t}function wP(e){if(!e)return null;try{let t=JSON.parse(e);return typeof t?.grantId!="string"||typeof t?.accountId!="string"?null:{grantId:t.grantId,accountId:t.accountId,accountName:typeof t.accountName=="string"?t.accountName:null,expiresAt:typeof t.expiresAt=="string"?t.expiresAt:""}}catch{return null}}function ec(){for(let e of to)try{e()}catch{}}function kP(){return dr||(dr=!0,pt=wP(ro()?.getItem(no)??null)),pt&&!PP(pt)?(tc(),null):pt}function cO(e){if(dr=!0,!e){tc();return}pt=e;try{ro()?.setItem(no,JSON.stringify(e))}catch{}ec()}function tc(){dr=!0;let e=pt!==null;pt=null;try{ro()?.removeItem(no)}catch{}e&&ec()}function lO(e){return to.add(e),()=>{to.delete(e)}}var vP=/(^|\/)admin\/(api|analytics)(\/|$)/;function AP(e){let t=e;if(/^https?:\/\//.test(e))try{t=new URL(e).pathname}catch{t=e}return!vP.test(t)}function nc(e){if(e!==void 0&&!AP(e))return{};let t=kP();return t?{[xP]:t.grantId}:{}}function RP(e){}function CP(){return!1}function TP(e){return e?e instanceof Headers||Array.isArray(e)?[...new Headers(e).entries()]:Object.entries(e):[]}function gr(e,t){let n=t.toLowerCase();return Object.keys(e).some(r=>r.toLowerCase()===n)}function nn(e,t,n){let r=t.toLowerCase();for(let s of Object.keys(e))s.toLowerCase()===r&&delete e[s];e[t]=n}function mr(e,t){let n={},r=[e instanceof Request?e.headers:void 0,t.headers];for(let[s,o]of r.flatMap(TP))nn(n,s,o);return n}function oo(e,t,n){let r={...t},s=I().clientVersion?.trim();s&&!gr(r,"x-kortix-client-version")&&nn(r,"X-Kortix-Client-Version",s);for(let[i,a]of Object.entries(nc(e)))nn(r,i,a);let o=I().credentialHeader?.trim();return o?gr(r,o)||nn(r,o,n):gr(r,"authorization")||nn(r,"Authorization",`Bearer ${n}`),r}async function vt(e,t){let n=await fr();if(!n)throw new ie;return{headers:new Headers(oo(e,mr(e,{headers:t}),n)),rejected:()=>rn(n)}}function IP(e){return typeof ReadableStream<"u"&&e.body instanceof ReadableStream}function rc(e,t,n,r,s){if(t instanceof Request){let l=new Headers(oo(t.url,mr(t,n),r));return e(new Request(t,{headers:l,...s?{signal:s}:{}}))}let o=String(t),i=oo(o,mr(t,n),r),a=o.startsWith("/")&&!o.startsWith("//");return e(o,{...n,headers:i,...a?{credentials:"same-origin"}:{},...s?{signal:s}:{}})}var sc=null;async function io(e){let t=await ar(()=>I().getToken(),e);return t&&(sc=t),t}var fr=io;function rn(e=sc){e&&I().getToken.invalidate?.(e)}var so=new Map;function EP(e){let t=so.get(e);if(t)return t;let n=(async()=>(rn(e),fr({attempts:2,baseDelayMs:200})))().finally(()=>so.delete(e));return so.set(e,n),n}async function dt(e,t={},n={}){let{retryOnAuthError:r=!0,timeoutMs:s=eo}=n,o=n.fetch??I().fetch??fetch,i=s===null?(e instanceof Request?e.signal:t.signal)??void 0:Fa(e,t,s);if(i?.aborted)throw ke();let a=await(i?ve(fr(),i):fr());if(!a)throw new ie;let l=r&&!IP(t)&&!gr(mr(e,t),"authorization"),p=l&&e instanceof Request?e.clone():e,d=await rc(o,e,t,a,i);if(d.status!==401||!l)return d;let g=await EP(a);return!g||g===a?d:rc(o,p,t,g,i)}async function Oe(e,t,n,r){let s=await dt(e,t,n);if(s.ok)return s;let o=await s.text().catch(()=>"");throw new P(o||`${r} (HTTP ${s.status})`,{status:s.status,response:s})}var oc=()=>I().backendUrl||"",MP=new Set([502,503,504]),OP=e=>MP.has(e),ic=e=>{let t=(e??"GET").toUpperCase();return t==="GET"||t==="HEAD"},DP=e=>ic(e)||(e??"GET").toUpperCase()==="DELETE",jP=2,yr=e=>e?.name==="AbortError"||e?.name==="AbortSignal"||e instanceof Error&&e.message.includes("aborted");async function De(e,t={}){let{showErrors:n=!0,errorContext:r,timeout:s=3e4,deadlineCoversBody:o=!1,...i}=t,a=new AbortController,l={activeController:a,timeoutId:null,isAborted:!1,didTimeout:!1},p=()=>l.activeController.abort();i.signal?.addEventListener("abort",p,{once:!0});try{return await LP(e,i,n,r,s,o,a,l)}finally{i.signal?.removeEventListener("abort",p)}}async function LP(e,t,n,r,s,o,i,a){try{if(t.signal?.aborted)throw ke();a.timeoutId=setTimeout(()=>{!a.isAborted&&!i.signal.aborted&&(a.isAborted=!0,a.didTimeout=!0,i.abort())},s);let l={...t.body instanceof FormData?{}:{"Content-Type":"application/json"},...t.headers},p=await UP(e,t,l,s,o,i,a);if(p instanceof ie)return{error:p,success:!1};if(!p.ok)return await Va(p,a.activeController.signal,n,r);let d,g=p.headers.get("content-type");return g?.includes("application/json")?d=await ve(p.json(),a.activeController.signal):g?.includes("text/")?d=await ve(p.text(),a.activeController.signal):d=await ve(p.blob(),a.activeController.signal),{data:d,success:!0,headers:p.headers}}catch(l){return FP(l,e,t.method,n,r,s,a)}finally{hr(a)}}function hr(e){e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=null}async function $P(e,t,n){try{await ve(e.arrayBuffer(),t)}catch(r){if(yr(r))throw r}finally{hr(n)}}async function UP(e,t,n,r,s,o,i){let a=ic(t.method),l=DP(t.method),p=l?jP+1:1,d;for(let g=0;g<p;g++){g>0&&await pr(250*2**(g-1),t.signal??void 0);let m=g===0?o:new AbortController;i.activeController=m,t.signal?.aborted&&m.abort(),g>0&&(i.timeoutId=setTimeout(()=>{i.didTimeout=!0,m.abort()},r));try{d=await ve(dt(e,{...t,headers:n,signal:m.signal,credentials:t.credentials??"omit"},{timeoutMs:null}),m.signal)}catch(f){if(i.timeoutId&&(clearTimeout(i.timeoutId),i.timeoutId=null),f instanceof ie)return new ie;if(i.didTimeout&&yr(f)&&!t.signal?.aborted&&l&&g<p-1){i.didTimeout=!1;continue}if(yr(f)||g===p-1)throw f;continue}if(!a||!OP(d.status)||g===p-1)return s||hr(i),d;await $P(d,m.signal,i)}return d}function FP(e,t,n,r,s,o,i){hr(i);let a=yr(e);a&&(i.isAborted=!0);let l;if(a){if(!i.didTimeout)return{error:new P("Request aborted",{name:"AbortError",code:"ABORTED"}),success:!1};let p=t.replace(oc(),"")||t;l=new P(`Request timed out after ${Math.round(o/1e3)}s: ${p}`,{code:"TIMEOUT",url:t,endpoint:p,timeout:o})}else e instanceof Error?(l=new P(n==="POST"&&e instanceof TypeError&&e.message==="Failed to fetch"?`Failed to fetch: POST ${t.replace(oc(),"")||t}`:e.message,{name:e.name||"ApiError",stack:e.stack}),r&&I().onError?.(l,s)):(l=new P(String(e)),r&&I().onError?.(l,s));return{error:l,success:!1}}var je=()=>I().backendUrl||"",za="feature_not_supported",Ya="model_not_servable",Ja="provision_in_flight",Qa="sandbox_state_change_in_progress",Xa="analytics_unavailable",Za="accounts_list_unavailable",CO={async execute(e,t){try{let{data:n,error:r}=await e();if(r){let s=new P(r.message||"Database error",{code:r.code,details:r});return I().onError?.(s,t),{error:s,success:!1}}return{data:n,success:!0}}catch(n){let r=n instanceof Error?new P(n.message,{name:n.name||"ApiError",stack:n.stack}):new P(String(n));return I().onError?.(r,t),{error:r,success:!1}}}};async function NP(e,t,n={}){let{timeout:r=3e4,fetch:s}=n,o=new AbortController,i=setTimeout(()=>o.abort(),r);try{return await dt(`${je()}${e}`,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(t),signal:o.signal,credentials:"omit"},{timeoutMs:null,fetch:s})}catch(a){if(a instanceof ie)return cr();throw a}finally{clearTimeout(i)}}var c={putRaw:(e,t,n)=>De(`${je()}${e}`,{...n,method:"PUT",body:t,headers:{"Content-Type":"application/octet-stream",...n?.headers}}),get:(e,t)=>De(`${je()}${e}`,{...t,method:"GET"}),post:(e,t,n)=>De(`${je()}${e}`,{...n,method:"POST",body:t?JSON.stringify(t):void 0}),put:(e,t,n)=>De(`${je()}${e}`,{...n,method:"PUT",body:t?JSON.stringify(t):void 0}),patch:(e,t,n)=>De(`${je()}${e}`,{...n,method:"PATCH",body:t?JSON.stringify(t):void 0}),delete:(e,t)=>De(`${je()}${e}`,{...t,method:"DELETE"}),upload:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],De(`${je()}${e}`,{...s,method:"POST",body:t,headers:o})},uploadPut:(e,t,n)=>{let{headers:r,...s}=n||{},o={...r};return delete o["Content-Type"],De(`${je()}${e}`,{...s,method:"PUT",body:t,headers:o})},postStream:NP};function u(e,t="Project request failed"){if(!e.success||e.data===void 0)throw e.error??new Error(t);return e.data}function ao(e){return e.replace(/\/v1\/?$/,"")}async function At(e,t){if(!e.backendUrl||!e.accessToken)return null;let n=ao(e.backendUrl);try{let r=await fetch(`${n}${t}`,{headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},signal:AbortSignal.timeout(e.timeoutMs??8e3)});return r.ok?await r.json():null}catch{return null}}async function ac(){return u(await c.get("/accounts"))}async function cc(e){return u(await c.post("/accounts",e))}async function lc(e){return u(await c.get(`/accounts/${e}`))}async function uc(e,t){return u(await c.patch(`/accounts/${e}`,{name:t}))}async function pc(e){return u(await c.get(`/accounts/${e}/branding`))}async function dc(e,t){return u(await c.put(`/accounts/${e}/branding`,t))}async function gc(e,t,n,r){let s=new FormData;return s.append("file",n,r??(n instanceof File?n.name:t)),u(await c.upload(`/accounts/${e}/branding/assets/${t}`,s))}async function mc(e,t){return u(await c.delete(`/accounts/${e}/branding/assets/${t}`))}async function fc(e){return u(await c.delete(`/accounts/${e}/branding`))}async function yc(e){return u(await c.get(`/accounts/${e}/members`))}async function hc(e,t){return u(await c.post(`/accounts/${e}/members`,t,{showErrors:!1}))}async function _c(e){return u(await c.get(`/accounts/${e}/invites`))}async function bc(e,t){return u(await c.delete(`/accounts/${e}/invites/${t}`))}async function Sc(e,t){return u(await c.post(`/accounts/${e}/invites/${t}/resend`,{}))}async function xc(){return u(await c.get("/account-invites",{showErrors:!1})).invites}async function Pc(e){return u(await c.get(`/account-invites/${e}`,{showErrors:!1}))}async function co(e){return u(await c.post(`/account-invites/${e}/accept`,{}))}function BP(e,t){let n=e.bootstrap_grants_applied?.[0]??t?.projects?.[0];return n?{kind:"project",projectId:n.project_id,accountId:e.account_id}:{kind:"account",accountId:e.account_id}}async function wc(e,t){let n=await co(e);return{accepted:n,landing:BP(n,t)}}async function kc(e){return u(await c.post(`/account-invites/${e}/decline`,{}))}async function vc(e,t){return u(await c.delete(`/accounts/${e}/members/${t}`))}async function Ac(e,t,n){return u(await c.patch(`/accounts/${e}/members/${t}`,{role:n}))}async function Rc(e){return u(await c.post(`/accounts/${e}/leave`,{}))}async function jO(e){return At(e,"/v1/accounts")}async function Cc(){let e=await c.get("/accounts/me",{showErrors:!1});return!e.success||!e.data?{valid:!1,error:e.error}:{valid:!0,identity:e.data}}var NO=["marketplace","connectors_api_discover","agentmail_email","meta_agent","monitors","reminders","warm_sessions","secrets_egress","pooled_provider_secrets","pi_harness","genui","us_region","event_triggers","notification_center","volumes","drives","session_log_restore","connectors_v2","agent_rooms","goals"];async function Rt(){return u(await c.get("/projects"))}async function Ic(e){let t=e?`?account_id=${encodeURIComponent(e)}`:"";return u(await c.get(`/projects${t}`))}async function Ct(e,t){return u(await c.get(`/projects/${e}`,t))}async function Ec(e,t,n="write"){return u(await c.post(`/projects/${e}/git/collaborators`,{github_username:t,permission:n}))}async function Mc(e,t){return u(await c.post(`/projects/${e}/manifest/validate`,{raw:t}),"Failed to validate manifest")}async function Oc(e){return u(await c.post(`/projects/${e}/git-token`,{}),"Failed to mint git token")}function BO(e){let t=e.metadata?.git;return t?.provider==="github"&&t?.managed===!0}async function _r(e,t){let n=u(await c.get(`/projects/${e}/detail`,{showErrors:!1,...t}));return{...n,config:{...n.config,default_agent:n.config.default_agent??n.config.open_code_default_agent??null}}}async function br(e,t){return u(await c.get(`/projects/${e}/llm-catalog`,{showErrors:!1,...t}))}async function Sr(e,t){return u(await c.get(`/projects/${e}/model-picker`,{showErrors:!1,...t}))}async function KO(e,t){return u(await c.get(`/projects/${e}/llm-catalog/providers`,{showErrors:!1,...t}))}async function Dc(e){return u(await c.post("/projects",e))}async function jc(e){return u(await c.post("/projects/create-repo",e,{showErrors:!1}))}async function Lc(e,t={}){return u(await c.post("/projects/provision",{seed_starter:!0,...e},{timeout:12e4,...t}))}var KP="provision_stream_unterminated",Tc=200;function qP(e){let t=e.split(`
|
|
2
2
|
`).filter(r=>r.startsWith("data:")).map(r=>r.slice(5).replace(/^ /,""));if(t.length===0)return null;let n=t.join(`
|
|
3
|
-
`);try{return JSON.parse(n)}catch(r){let
|
|
3
|
+
`);try{return JSON.parse(n)}catch(r){let s=n.length>Tc?`${n.slice(0,Tc)}\u2026`:n;throw new Error(`provisionProjectStream: received an unparseable SSE frame (${s})`,{cause:r})}}async function qO(e,t,n={}){let r=await c.postStream("/projects/provision-stream",{seed_starter:!0,...e},n);if(!r.ok){let l=await r.json().catch(()=>null);throw new P(l?.error||`Provision failed: HTTP ${r.status}`,{status:r.status,code:l?.code})}let s=r.body?.getReader();if(!s)throw new Error("Provision stream is unavailable on this runtime (no response body)");let o=new TextDecoder,i="",a=null;try{for(;;){let{done:l,value:p}=await s.read();if(l)break;i+=o.decode(p,{stream:!0});let d=i.indexOf(`
|
|
4
4
|
|
|
5
5
|
`);for(;d!==-1;){let g=i.slice(0,d);i=i.slice(d+2),d=i.indexOf(`
|
|
6
6
|
|
|
7
|
-
`);let m=Fx(g);if(m){if(t(m),m.type==="error")throw new S(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{o.cancel().catch(()=>{})}if(!a)throw new S("Provision stream ended without a result",{code:Ux});return a}async function UO(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await c.get(`/projects/quota${t}`))}async function FO(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function Pr(e,t){return u(await c.patch(`/projects/${e}`,t))}async function Uc(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Fc(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function Nc(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function NO(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function BO(e,t){throw F("updateTemplateWarmPool")}async function Bc(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function KO(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Sr(e){return u(await c.delete(`/projects/${e}`))}async function qO(e,t){return At(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function GO(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=cs(e.backendUrl);try{let r=await fetch(`${n}/v1/projects/provision`,{method:"POST",headers:{Authorization:`Bearer ${e.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify({seed_starter:!0,...t}),signal:AbortSignal.timeout(e.timeoutMs??9e4)});if(r.ok){let o=await r.json().catch(()=>null);return o?.project_id?{ok:!0,project:o}:{ok:!1,limitReached:!1}}return r.status===403?{ok:!1,limitReached:(await r.json().catch(()=>null))?.code==="project_limit_reached"}:{ok:!1,limitReached:!1}}catch{return{ok:!1,limitReached:!1}}}async function Kc(e,t,n){return u(await c.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function qc(e,t,n){return u(await c.post(`/projects/${e}/skills/remove`,t,{showErrors:!1,...n}))}async function QO(e){return u(await c.get(`/projects/${e}/git/connection`),"Failed to read the Git connection")}async function Gc(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function Wc(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Hc(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Vc(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function zc(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function Yc(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let o=n?.search?.trim();return o&&r.set("search",o),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await c.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function Jc(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 Qc(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function Xc(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Zc(e){return u(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function el(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 tl(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function nl(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 oD(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function rl(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function ol(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function sl(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function il(e){return u(await c.get(`/projects/${e}/access`))}async function al(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function cl(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function sD(e){return"status"in e&&e.status==="invited"}async function ll(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 ul(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function pl(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function dl(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function gl(e){return u(await c.get(`/projects/${e}/group-grants`))}async function ml(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 fl(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 yl(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function hl(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function _l(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 bl(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function Pl(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Sl(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function xl(e,t,n,r={}){let o=r.note?.trim();return u(await c.post(`/projects/${e}/approvals/${t}`,{decision:n,...o?{note:o}:{}}))}async function wl(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function kl(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function vl(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function Al(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Rl(e){return u(await c.get(`/projects/${e}/oauth`)).items??[]}async function us(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 ps(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Cl(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var Nx=2e3,Bx=3e3,Kx=10*6e4;async function lD(e){let{projectId:t,provider:n,input:r,onChallenge:o,isCancelled:s,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,l=()=>s?.()??!1,p=await us(t,n,r);if(l())return{status:"cancelled"};o?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(Nx,p.interval_ms||Bx),g=p.expires_at||a()+Kx;for(;!l()&&a()<g;){if(await i(d),l())return{status:"cancelled"};let m;try{m=await ps(t,n,p.flow_id)}catch{continue}if(l())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return l()?{status:"cancelled"}:{status:"expired"}}async function Tl(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function xr(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Il(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function El(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var ds=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Tt=(e,t)=>`${ds(e)}/${encodeURIComponent(t)}`,Ml=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Ol(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${ds(e)}${n}`))}async function Dl(e,t){return u(await c.post(ds(e),t))}async function Ll(e,t,n){return u(await c.put(`${Tt(e,t)}/value`,{value:n}))}async function jl(e,t){return u(await c.post(`${Tt(e,t)}/retry`))}async function $l(e,t){return u(await c.delete(Tt(e,t)))}async function Ul(e,t,n,r){return u(await c.put(`${Tt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function Fl(e,t,n,r){return u(await c.delete(`${Tt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function Nl(e,t,n,r){return u(await c.put(`${Tt(e,t)}/access`,{mode:n,user_ids:r}))}async function Bl(e,t,n){return u(await c.get(Ml(e,t,n)))}async function Kl(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function ql(e,t,n,r){return u(await c.put(Ml(e,t,n),{secret_ids:r}))}async function gs(){return as()}async function qx(e){return ir(()=>C().getToken(),e,ms)}function ms(){rn()}function _D(e){e===null&&rn()}function bD(e){}async function on(){return gs()}async function PD(e){return qx(e)}async function $(e,t,n){try{return await dt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof ie)return ar();throw r}}function wr(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)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`${wr(e,"catalog")}${r}`)).connectors??[]}async function fs(e){let t=[];for(let n of await sn(e,{includeSchemas:!1}))for(let r of n.actions)t.push({tool:`${n.slug}.${r.path}`,connector:n.slug,action:r.path,risk:r.risk,description:r.description||r.name,inputSchema:r.inputSchema});return t}async function Gl(e,t="",n={}){let r=t.trim().toLowerCase(),o=r.split(/\s+/).filter(Boolean),s=[],i=[];for(let a of await fs(e)){let l=`${a.tool} ${a.description}`.toLowerCase();!r||l.includes(r)?s.push(a):o.every(p=>l.includes(p))&&i.push(a)}return[...s,...i].slice(0,n.limit??20)}async function ys(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let o=(await sn(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(s=>s.slug===r);if(!o)return null;for(let s of o.actions){let i=`${o.slug}.${s.path}`;if(i===t)return{tool:i,connector:o.slug,action:s.path,risk:s.risk,description:s.description||s.name,inputSchema:s.inputSchema,outputSchema:s.outputSchema??null}}return null}function Gx(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var Wx=9e4;async function It(e,t,n={},r={}){let{connector:o,action:s}=Gx(t),i=r.account?.trim(),a=r.approvalContext?.trim(),l=u(await c.post(wr(e,"call"),{connector:o,action:s,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??Wx,signal:r.signal}));return l.ok&&l.binding!==void 0&&!("output"in l)&&(l.output=l.data),l}async function hs(e,t){let n=await c.get(wr(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function Hx(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 Vx(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 _s(e,t,n){let r=n.filename.trim(),o=n.contentType.trim();if(!r)throw new Error("filename is required");if(!o)throw new Error("contentType is required");let s={"Content-Type":o,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(s["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(s["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=Vx(C().backendUrl),a=wr(e,"attachments"),l=await $(`${i}${a}`,{method:"POST",headers:s,body:t},{timeoutMs:6e4}),p=await l.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!l.ok)throw new S(Hx(d,l.status),{status:l.status,code:String(d&&typeof d=="object"?d.code??l.status:l.status),details:d,response:l,endpoint:a});return d}function RD(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 Wl(e){return u(await c.get(`/projects/${e}/connections`))}async function Hl(e){return u(await c.get(`/projects/${e}/connections/all`))}async function Vl(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function zl(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function Yl(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function je(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function CD(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function TD(e,t,n){return u(await c.put(je(e,t,"application"),n))}async function ID(e,t){return u(await c.get(je(e,t,"application")))}async function ED(e,t,n){return u(await c.post(je(e,t,"discover"),n))}async function MD(e,t,n={}){return u(await c.post(je(e,t,"discover-resource"),n))}async function OD(e,t,n){return u(await c.post(je(e,t,"register"),n))}async function DD(e,t,n){return u(await c.post(je(e,t,"authorize"),n))}async function LD(e,t,n){return u(await c.post(je(e,t,"device"),n))}async function jD(e,t,n){return u(await c.post(je(e,t,`device/${encodeURIComponent(n)}`),{}))}async function $D(e,t){return u(await c.get(je(e,t,"status")))}async function Jl(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Ql(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Xl(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function Zl(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function eu(e,t){return u(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function tu(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function nu(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function ru(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function ou(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 su(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function iu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function au(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function cu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function lu(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function uu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function UD(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function FD(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function pu(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function du(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function zx(e,t,n={}){return u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var gu=zx;async function ND(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function mu(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function fu(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function BD(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function yu(e){return u(await c.get(`/projects/${e}/connector-moves`)).moves}async function hu(e,t,n={}){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/move`,n.connectionId?{connection_id:n.connectionId}:{}))}async function _u(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function bu(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/apps${s?`?${s}`:""}`))}async function Pu(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 KD(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),o=u(await c.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in o)return o;let s=o.cursor?.trim()||void 0;return{provider:"composio",toolkits:o.items,nextCursor:s,hasMore:!!s}}async function qD(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 bs(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,o=new URLSearchParams;r.q&&o.set("q",r.q),r.category&&o.set("category",r.category),r.cursor&&o.set("cursor",r.cursor),r.limit&&o.set("limit",String(r.limit));let s=o.toString();return u(await c.get(`/connectors/projects/${e}/discover/connectors${s?`?${s}`:""}`))}async function Su(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 Ps(e,t){let n=new URLSearchParams({id:t});return u(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var GD=bs,WD=Ps;async function xu(){return u(await c.get("/connectors/connect-status"))}async function wu(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 ku(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function HD(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function Yx(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 vu=Yx;var kr=class extends S{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:o,action:s,binding:i,upstreamStatus:a,retryAfterSeconds:l,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=o,this.action=s,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=l??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},Ss=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},xs=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,o){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=o,Object.setPrototypeOf(this,new.target.prototype)}},Ae=e=>typeof e=="string"&&e?e:null;function Au(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function Jx(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function Qx(e,t,n){if(!(e instanceof S)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},o=Ae(r.reason)??Ae(r.error)??e.message,s=/^upstream_(\d{3})\b/.exec(o),i=typeof r.upstream_status=="number"?r.upstream_status:s?Number(s[1]):null;return new kr(Ae(r.message)??Ae(r.hint)??o,{status:e.status,code:i===null?Au(o):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:o,connector:Ae(r.connector)??t,action:Ae(r.action)??n,binding:Ae(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:Jx(e.response),connectUrl:Ae(r.connect_url),hint:Ae(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Ae(r.requested_account)})}function Xx(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function ws(e,t,n,r={},o={}){let s=t.trim(),i=n.trim();if(!s||!i)throw new Error("connector slug and action are required");let a;try{a=await It(e,`${s}.${i}`,r,o)}catch(l){throw Qx(l,s,i)}if(a.status==="pending_approval")throw new Ss(s,i,a);if(!a.ok||a.upstream_error){let l=a.upstream_error??a.reason??"connector_error";throw new kr(l,{status:200,code:a.upstream_error?"upstream_error":Au(l),details:a,data:a,reason:l,connector:s,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return Xx(a)}async function*Ru(e,t,n,r,o){let{next:s,maxPages:i=100,...a}=o,l=r;for(let p=0;l;p++){if(p>=i)throw new xs(t,n,i,l);let d=await ws(e,t,n,l,a);yield d,l=s(d,l)}}async function Cu(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function Tu(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Iu(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Eu(e){return u(await c.get(`/projects/${e}/snapshots`))}async function vr(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Mu(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Ou(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Du(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function Lu(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function ju(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function $u(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function Uu(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Ar(e){let t=new URL(C().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Kortix backend: ${n.origin}`);let{headers:r}=await vt(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function Fu(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 Nu(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),t?.cursor&&n.set("cursor",t.cursor),t?.limit!==void 0&&n.set("limit",String(t.limit)),u(await c.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function Bu(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 Ku(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await c.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var Zx=10*6e4;async function qu(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"",s=`${C().backendUrl||""}/projects/${e}/files/archive${o}`;return await(await Oe(s,{method:"GET"},{timeoutMs:Zx},"Failed to download")).blob()}async function Gu(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let o=r.toString()?`?${r.toString()}`:"";return Ar(`${C().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${o}`)}async function pL(e,t,n,r){let o=new URLSearchParams({path:t});n&&o.set("ref",n);let s=o.toString()?`?${o.toString()}`:"",i=`${C().backendUrl||""}/projects/${e}/files/raw${s}`;return await(await Oe(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var ks=52428800,ew=104857600,Wu=20;var Cr=e=>`/projects/${encodeURIComponent(e)}/attachments`,Tr={showErrors:!1,deadlineCoversBody:!0},Hu=3e4,tw=12e4,nw=6e4,rw=5*6e4,ow=6e4,sw=6e4;function Rr(){return new S("Request aborted",{name:"AbortError",code:"ABORTED"})}function an(e){if(e?.aborted)throw Rr()}function iw(e){return!(e instanceof S)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function cn(e,t,n=!1){let r;for(let o=0;;o++){an(t);try{return await e()}catch(s){let i=n&&s instanceof S&&s.status===409&&s.code==="attachment_processing";if(t?.aborted||!(iw(s)||i))throw s;r??=Date.now()+(n?rw:nw);let a=Math.min(8e3,500*2**o)*(.5+Math.random()/2);if(Date.now()+a>=r)throw s;try{await ur(a,t)}catch{throw an(t),s}}}}function aw(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function vs(e,t,n){let r=e?.upload,o=e?.received_bytes,s=Number.isSafeInteger(o)&&o>=0&&o<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&aw(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(o===0||o===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(o===t.size||o%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!s||!i)throw new Error("Invalid attachment upload handle");return e}async function Vu(e,t,n,r){return u(await c.post(Cr(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Tr,signal:n,timeout:Hu}),"Failed to start attachment upload")}async function zu(e,t,n,r){let o=vs({...await cn(()=>Vu(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(o),o}function Yu(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new S(r,{status:e,details:n,code:String(n?.statusCode??e)})}function cw(e){if(!(e instanceof S))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function lw(e,t,n,r){return new Promise((o,s)=>{let i=new e,a=0,l=!1,p,d=f=>{l||(l=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?s(f):o())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new S("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},ow)},m=()=>{d(Rr()),i.abort()};i.open(t.method,t.url);for(let[f,_]of Object.entries(t.headers))i.setRequestHeader(f,_);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d(Yu(i.status,i.responseText))},i.onerror=()=>d(new S("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(Rr()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function uw(e,t,n){let r=C().fetch??fetch,o;try{o=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(s){throw n.signal?.aborted||s instanceof Error&&s.name==="AbortError"?Rr():new S(s instanceof Error?s.message:String(s),{name:s instanceof Error?s.name:"TypeError"})}if(!o.ok)throw Yu(o.status,await o.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function pw(e,t,n){an(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?lw(r,e,t,n):uw(e,t,n)}async function dw(e,t,n,r){let o=n,s=!1;for(r.onProgress?.(0,t.size);o.upload.kind==="direct";){let i=o.upload;try{await cn(()=>pw(i,t,r),r.signal)}catch(a){let l=cw(a);if(l!==409){if(s||!(l===400||l===401||l===403))throw a;s=!0,o=await zu(e,t,o,r);continue}}return o={...o,received_bytes:t.size},r.onUpload?.(o),o}return Ju(e,t,o,r)}async function Ju(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let o=n.upload.chunk_size,s=`${Cr(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){an(r.signal);let a=i.received_bytes,l=Math.min(a+o,t.size),p=t.slice(a,l),d=await cn(async()=>u(await c.putRaw(`${s}/chunks/${a/o}`,p,{...Tr,signal:r.signal,timeout:Hu}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==l)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:l},r.onUpload?.(i),r.onProgress?.(l,t.size)}return i}async function Ir(e,t,n={}){if(!e)throw new Error("A project is required to upload attachments");if(!Number.isSafeInteger(t.size)||t.size<=0||t.size>52428800)throw new Error("Attachment must contain 1 byte to 50 MiB");an(n.signal);let r=n.resume?vs({...n.resume},t):vs({...await cn(()=>Vu(e,t,n.signal),n.signal),received_bytes:0},t);n.onUpload?.(r),r.received_bytes<t.size&&(r.upload.kind==="direct"&&Date.parse(r.upload.expires_at)-Date.now()<sw&&(r=await zu(e,t,r,n)),r=r.upload.kind==="direct"?await dw(e,t,r,n):await Ju(e,t,r,n)),n.onProcessing?.();let o=`${Cr(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await cn(async()=>u(await c.post(`${o}/complete`,{},{...Tr,signal:n.signal,timeout:tw}),"Failed to complete attachment upload"),n.signal,!0)}catch(s){throw r.upload.kind==="direct"&&s instanceof S&&s.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),s}}async function ln(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${Cr(e)}/${encodeURIComponent(t)}`,{...Tr,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function Qu(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 Xu(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 Zu(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function ep(e,t,n){let r=new URLSearchParams;n?.path&&r.set("path",n.path);let o=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}/diff${o}`))}async function tp(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 np(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 rp(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit)),n?.cursor&&r.set("cursor",n.cursor);let o=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/change-requests${o}`,{showErrors:!1,timeout:15e3}))}async function op(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function sp(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function ip(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function ap(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function cp(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function lp(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function up(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function pp(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function dp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function gp(e,t,n){return u(await c.patch(`/projects/${e}/change-requests/${t}`,n))}var Et=new Set,gw=500;function Er(e){e&&(Et.add(e),Et.size>gw&&Et.delete(Et.values().next().value))}function mp(e){return!!e&&Et.has(e)}function vL(e){e&&Et.delete(e)}var le="kortix.session/2",Pe=1,mw=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),V=e=>typeof e=="string",Re=e=>V(e)&&e.length>0,Ue=e=>e===null||V(e),Y=(e,t)=>e===void 0||t(e),$e=(...e)=>t=>e.includes(t),un=e=>Number.isInteger(e)&&e>=0,Mt=e=>typeof e=="number",hp=e=>e.schema===le&&un(e.v),gt=e=>Y(e,V),As=e=>e===void 0||re(e)&&Object.values(e).every(t=>re(t)&&V(t.version)),_p=e=>e===null||re(e)&&V(e.provider)&&V(e.model)&>(e.variant),fw=e=>e===null||re(e)&&Mt(e.input)&&Mt(e.output)&&Mt(e.cache_read)&&Mt(e.cache_write)&&Y(e.reasoning,Mt)&&Y(e.cost,Mt),fp=e=>re(e)&&(e.type==="text"&&V(e.text)||e.type==="attachment"&&V(e.mime)),yw=e=>re(e)&&Array.isArray(e.content)&&e.content.every(fp)&&Y(e.model_content,t=>Array.isArray(t)&&t.every(fp))&&typeof e.is_error=="boolean",yp={text:e=>V(e.text)&&Y(e.bytes,un)&>(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>V(e.text),attachment:e=>V(e.mime)&>(e.ref)&&Y(e.bytes,un)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>V(e.call_id)&&V(e.name)&&Re(e.kind)&&$e("pending","running","complete","error")(e.status)&&Y(e.result,yw),compaction:e=>Ue(e.summary)&&Ue(e.first_kept_message_id),subtask:e=>V(e.thread_id)&&V(e.agent)&&V(e.description),step:e=>$e("start","finish")(e.phase),harness:e=>Re(e.harness)&&Re(e.kind)&&typeof e.model_visible=="boolean"};function hw(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!re(r)||!Re(r.id)||n.has(r.id)||!Object.hasOwn(yp,r.type)||!yp[r.type](r)||!As(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function Rs(e){return re(e)&&hp(e)&&Re(e.message_id)&&Re(e.thread_id)&&Number.isInteger(e.seq)&&$e("user","assistant","system")(e.role)&&$e("turn","compaction","context")(e.kind)&&$e("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&Y(e.hidden_reason,$e("failed_attempt","aborted","retracted","reverted","superseded"))&&Y(e.origin,$e("prompt","steer","command","automation","subagent","notification"))&&Y(e.agent,Ue)&&Y(e.reply_to,Ue)&&Y(e.parent_message_id,Ue)&>(e.native_agent_id)&>(e.context_ref)&&_p(e.model)&&fw(e.usage)&&$e("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||re(e.error)&&Re(e.error.code)&&V(e.error.message))&&V(e.created_at)&&Ue(e.completed_at)&&re(e.producer)&&Re(e.producer.harness)&&V(e.producer.harness_version)&&V(e.producer.adapter_version)&&As(e.ext)&&hw(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function Cs(e){return re(e)&&hp(e)&&Re(e.thread_id)&&Ue(e.parent_thread_id)&&(e.spawned_by===null||re(e.spawned_by))&&V(e.created_at)}function _w(e){return re(e)&&Y(e.schema,t=>t===le)&&Y(e.v,un)&>(e.session_id)&&Y(e.title,Ue)&>(e.created_at)&&Y(e.restore_grade,$e("native","converted","partial"))&&Y(e.todos,Array.isArray)&&Y(e.pending,t=>re(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&Y(e.selection,t=>re(t)&&Y(t.agent,Ue)&&_p(t.model??null))&&Y(e.harness,t=>re(t)&&V(t.current)&&Array.isArray(t.history))&&As(e.ext)}function Ot(e){return re(e)&&un(e.generation)&&typeof e.has_more=="boolean"&&_w(e.session)&&Array.isArray(e.threads)&&e.threads.every(Cs)&&(e.thread_id===null||Re(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>Rs(t)&&t.thread_id===e.thread_id)}var bw=e=>Ot(e)&&e.messages.length>0;function Pw(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let o=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(o.length<=t)return o}return null}var bp={paintable:bw,fit:Pw,capturedAt:()=>0},Sw=new WeakMap;function Pp(e,t,n){Sw.set(e,{read:(r,o)=>t.read(r,o),write:async(r,o,s)=>{await t.write(r,o,s),await n(r,o)}})}function Mr(e){return!!e&&typeof e.then=="function"}function Sp(e,t){return Mr(e)?e.then(t):t(e)}function xp(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:o,now:s}=e,i=`${n}index`,a=R=>{try{let I=t.getItem(R);return Mr(I)?I.catch(()=>null):I}catch{return null}},l=async R=>{try{await t.removeItem(R)}catch{}},p=R=>{if(!R)return[];try{let I=JSON.parse(R);return I?.v===1&&Array.isArray(I.entries)?I.entries:[]}catch{return[]}},d=Promise.resolve(),g=R=>{let I=d.then(R,R);return d=I.catch(()=>{}),I},m=async R=>{try{await t.setItem(i,JSON.stringify({v:1,entries:R}))}catch{}},f=async()=>p(await a(i));return{indexKey:i,safeGet:a,safeRemove:l,enqueue:g,loadIndex:f,saveIndex:m,evict:async(R,I)=>{let b=[...R].sort((h,x)=>h.u-x.u),M=b.reduce((h,x)=>h+x.b,0);for(;b.length>r||M>o;){let h=b.findIndex(P=>P.s!==I);if(h===-1)break;let[x]=b.splice(h,1);M-=x.b,await l(`${n}${x.s}`)}return b},touch:R=>{g(async()=>{let I=await f(),b=I.find(M=>M.s===R);b&&(b.u=s(),await m(I))})},forgetScope:R=>g(async()=>{await l(`${n}${R}`);let I=await f(),b=I.filter(M=>M.s!==R);b.length!==I.length&&await m(b)})}}function xw(e){return!!e&&e.available===!0&&e.source==="mirror"&&Array.isArray(e.messages)&&e.messages.length>0&&!!(e.runtime_session_id??e.opencode_session_id)}var ww=12,kw=15e5,vw=3e5,Aw=336*60*60*1e3,vp="kortix.saved-copy";function Rw(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let o=a=>{let l=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:l,message_count:l.length,complete:!1,next_cursor:String(l[0].info.id)}})},s=o(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(s+a>t)break;s+=a,i+=1}for(;i>0;i-=1){let a=o(i);if(a.length<=t)return a}return null}function Cw(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var Tw={paintable:xw,fit:Rw,capturedAt:Cw};function LL(e){let t=kp(e,Tw),n=kp({...e,namespace:`${e.namespace??vp}.log`},bp),r={...t,remove:async(o,s)=>{await Promise.all([t.remove(o,s),n.remove(o,s)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return Pp(r,n,t.remove),r}function kp(e,t){let{storage:n,userId:r,maxSessions:o=ww,maxBytes:s=kw,maxEnvelopeBytes:i=vw,maxAgeMs:a=Aw,namespace:l=vp,now:p=()=>Date.now()}=e,d=`${l}:${r}:`,g=xp({storage:n,prefix:d,maxSessions:o,maxBytes:s,now:p}),{indexKey:m,safeGet:f,safeRemove:_,enqueue:y,loadIndex:k,saveIndex:R,evict:I,touch:b,forgetScope:M}=g,h=(P,v)=>`${d}${P}/${v}`,x=P=>{try{let v=n.removeItem(P);Mr(v)&&v.catch(()=>{})}catch{}};return{keyFor:h,read(P,v){let T=`${P}/${v}`;return Sp(f(h(P,v)),L=>{if(!L)return null;let w;try{w=JSON.parse(L)}catch{return x(h(P,v)),M(T),null}return!w||w.v!==1||w.user!==r||p()-w.at>a||!t.paintable(w.e)?(x(h(P,v)),M(T),null):(b(T),w.e)})},write(P,v,T){let L=`${P}/${v}`;if(!t.paintable(T))return M(L);let w={v:1,user:r,at:p(),e:T},D=t.fit(w,i);if(D===null)return M(L);let be=t.capturedAt(T);return y(async()=>{let N=await k(),z=N.find(ct=>ct.s===L);if(z&&be>0&&z.c>be)return;let G=N.filter(ct=>ct.s!==L),K={s:L,b:D.length,u:p(),c:be},Me=await I([...G,K],L),Qo=h(P,v);try{await n.setItem(Qo,D)}catch{let ct=Me.filter(lt=>lt.s!==L).sort((lt,tx)=>lt.u-tx.u)[0];ct&&(await _(`${d}${ct.s}`),Me=Me.filter(lt=>lt.s!==ct.s));try{await n.setItem(Qo,D)}catch{await _(Qo),Me=Me.filter(lt=>lt.s!==L)}}await R(Me)})},remove(P,v){return M(`${P}/${v}`)},clear(){return y(async()=>{let P=await k();for(let v of P)await _(`${d}${v.s}`);await _(m)})}}}var Ap=null;function jL(e){Ap=e}function Rp(){return Ap}var Iw=new Set;function Cp(e){for(let t of Iw)try{t(e)}catch{}}var Ew=new Set;function Tp(e){for(let t of Ew)try{t(e)}catch{}}var pn=async(e,t,n,r)=>{let o=new URLSearchParams;n.thread!==void 0&&o.set("thread",n.thread),n.before_seq!==void 0&&o.set("before_seq",String(n.before_seq)),n.limit!==void 0&&o.set("limit",String(n.limit));let s=o.toString(),i=await c.get(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/log${s?`?${s}`:""}`,{showErrors:!1,signal:r});if(!i.success)throw i.error??new Error("Session log request failed");return i.data},Mw=40;async function Ow(e,t,n,r,o){try{let s=await e(t,n,r,o);return Ot(s)?s:null}catch{return null}}function Ip(e,t,n,r){return Ow(e,t,n,{limit:Mw},r)}function YL(e){let t=typeof e.parent_session_id=="string"?e.parent_session_id:e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var JL=50,Dw=200,QL=Dw;function Ep(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return e?.view&&t.set(e.view,"only"),t.size>0?`?${t}`:""}async function Mp(e,t){let n=await c.get(`/projects/${e}/sessions${Ep(t)}`,{showErrors:!1});return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Dt(e,t){return u(await c.get(`/projects/${e}/sessions${Ep(t)}`))}async function Op(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Dp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Lp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function jp(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function $p(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function Up(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function XL(e,t){let n=e.public_url??e.public_path??e.proxy_path??e.public_token??"";if(!n)return"";if(/^https?:\/\//.test(n))return n;if(t)try{return new URL(n,t).toString()}catch{return n}return n}function ZL(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 Fp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function Np(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Bp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Kp(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function Lt(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return!t?.initial_prompt&&!t?.fork_from_session_id&&Er(n?.session_id),n}async function qp(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||Er(r.session.session_id),r}async function Gp(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Er(n.session_id),n}async function Or(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Wp(e,t,n,r){let o=new URLSearchParams;n&&o.set("limit",String(n)),r?.cursor&&o.set("cursor",r.cursor),r?.includeEvents!=null&&o.set("include_events",String(r.includeEvents));let s=o.toString();return u(await c.get(`/projects/${e}/sessions/${t}/audit${s?`?${s}`:""}`,{showErrors:r?.showErrors}))}async function Hp(e,t,n){let r=new URLSearchParams;n?.limit!=null&&r.set("limit",String(n.limit)),n?.chars!=null&&r.set("chars",String(n.chars));let o=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/transcript${o?`?${o}`:""}`))}async function Dr(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await c.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Vp(e,t,n={},r){let o;try{o=await pn(e,t,n,r?.signal)}catch(s){if(s?.status===404)return null;throw s}if(!Ot(o))throw new Error("The response is not a session log page");return o}async function Lr(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function ej(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let o=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/snapshot${o?`?${o}`:""}`,{signal:n?.signal,showErrors:!1}))}function Lw(e){if(e)return e==="interrupt"?"transcript":"composer"}async function jr(e,t,n){let r=n.placement??Lw(n.delivery);return u(await c.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function zp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function Yp(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Jp(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Qp(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function Xp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Zp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function ed(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function td(e,t){let n=u(await c.delete(`/projects/${e}/sessions/${t}`));return Rp()?.remove(e,t),Tp(t),n}async function nd(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function rd(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function $r(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Ur(e,t){let n=u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}));return Cp(t),n}async function od(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function jw(e){let t=e.split(`
|
|
7
|
+
`);let m=qP(g);if(m){if(t(m),m.type==="error")throw new P(m.error,{status:m.status,code:m.code});m.type==="done"&&(a=m.project)}}}}finally{s.cancel().catch(()=>{})}if(!a)throw new P("Provision stream ended without a result",{code:KP});return a}async function GO(e){let t=e?.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return u(await c.get(`/projects/quota${t}`))}async function WO(){try{return u(await c.get("/projects/managed-git/status",{showErrors:!1}))}catch{return{configured:!1,provider:"github"}}}async function xr(e,t){return u(await c.patch(`/projects/${e}`,t))}async function $c(e,t,n){return u(await c.patch(`/projects/${e}/features`,{feature:t,enabled:n}))}async function Uc(e,t,n){return u(await c.patch(`/projects/${e}/experimental`,{feature:t,enabled:n}))}async function Fc(e,t){return u(await c.patch(`/projects/${e}/sandbox-provider`,{provider:t}))}async function HO(e,t){return u(await c.get(`/projects/${e}/sandbox-provider/transition`,{showErrors:!1,...t}))}async function VO(e,t){throw N("updateTemplateWarmPool")}async function Nc(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{completed:t}))}async function zO(e,t){return u(await c.patch(`/projects/${e}/onboarding`,{profile:t}))}async function Pr(e){return u(await c.delete(`/projects/${e}`))}async function YO(e,t){return At(e,`/v1/projects?account_id=${encodeURIComponent(t)}`)}async function JO(e,t){if(!e.backendUrl||!e.accessToken)return{ok:!1,limitReached:!1};let n=ao(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 Bc(e,t,n){return u(await c.post(`/projects/${e}/skills`,t,{showErrors:!1,...n}))}async function Kc(e,t,n){return u(await c.post(`/projects/${e}/skills/remove`,t,{showErrors:!1,...n}))}async function rD(e){return u(await c.get(`/projects/${e}/git/connection`),"Failed to read the Git connection")}async function qc(e){return u(await c.post("/projects/link-repository",e,{showErrors:!1}))}async function Gc(e){let{project_id:t,...n}=e;return u(await c.put(`/projects/${encodeURIComponent(t)}/git/repository`,n,{showErrors:!1}))}async function Wc(e){return u(await c.get(`/projects/github/installation?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Hc(e){return u(await c.get(`/projects/github/installations?account_id=${encodeURIComponent(e)}`,{showErrors:!1}))}async function Vc(e){return u(await c.post("/projects/github/installations/linkable",e,{showErrors:!1}))}async function zc(e,t,n){let r=new URLSearchParams({account_id:e});t&&r.set("installation_id",t);let s=n?.search?.trim();return s&&r.set("search",s),n?.limit!==void 0&&r.set("limit",String(n.limit)),u(await c.get(`/projects/github/repositories?${r.toString()}`,{showErrors:!1}))}async function Yc(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 Jc(e){return u(await c.post("/projects/github/installation",e,{showErrors:!1}))}async function Qc(e){return u(await c.post("/projects/github/installations/link",e,{showErrors:!1}))}async function Xc(e){return u(await c.post("/projects/github/user-token",e,{showErrors:!1}))}async function Zc(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 el(){return u(await c.get("/projects/git/backend",{showErrors:!1}))}async function tl(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 uD(e,t){return u(await c.post(`/projects/${e}/access-requests`,{message:t?.trim()||void 0},{showErrors:!1}))}async function nl(e,t){return u(await c.get(`/projects/${e}/access-requests`,t))}async function rl(e,t,n="member"){return u(await c.post(`/projects/${e}/access-requests/${t}/approve`,{role:n}))}async function sl(e,t){return u(await c.post(`/projects/${e}/access-requests/${t}/reject`,{}))}async function ol(e){return u(await c.get(`/projects/${e}/access`))}async function il(e,t,n){return u(await c.put(`/projects/${e}/access/${t}`,{role:n}))}async function al(e,t){return u(await c.delete(`/projects/${e}/access/${t}`))}function pD(e){return"status"in e&&e.status==="invited"}async function cl(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 ll(e){return u(await c.get(`/projects/${e}/access/pending-invites`))}async function ul(e,t){return u(await c.delete(`/projects/${e}/access/pending-invites/${t}`))}async function pl(e,t){return u(await c.post(`/projects/${e}/access/pending-invites/${t}/resend`))}async function dl(e){return u(await c.get(`/projects/${e}/group-grants`))}async function gl(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 ml(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 fl(e,t){return u(await c.delete(`/projects/${e}/group-grants/${t}`))}async function yl(e){return u(await c.get(`/projects/${e}/resource-grants`))}async function hl(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 _l(e,t){return u(await c.delete(`/projects/${e}/resource-grants/${t}`))}async function bl(e,t){return u(await c.get(`/projects/${e}/approvals`,{showErrors:t?.showErrors}))}async function Sl(e,t){return u(await c.get(`/projects/${e}/approvals/needs-input`,{showErrors:t?.showErrors}))}async function xl(e,t,n,r={}){let s=r.note?.trim();return u(await c.post(`/projects/${e}/approvals/${t}`,{decision:n,...s?{note:s}:{}}))}async function Pl(e){return u(await c.get(`/projects/${e}/secrets`,{showErrors:!1}))}async function wl(e,t){return u(await c.post(`/projects/${e}/secrets`,t))}async function kl(e,t,n,r={}){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/strategy`,{strategy:n,...r}))}async function vl(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/broker`,n))}async function Al(e){return u(await c.get(`/projects/${e}/oauth`)).items??[]}async function lo(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 uo(e,t,n){return u(await c.post(`/projects/${e}/oauth/${t}/poll`,{flow_id:n}))}async function Rl(e,t){return u(await c.delete(`/projects/${e}/oauth/${encodeURIComponent(t)}`))}var GP=2e3,WP=3e3,HP=10*6e4;async function fD(e){let{projectId:t,provider:n,input:r,onChallenge:s,isCancelled:o,sleep:i=m=>new Promise(f=>setTimeout(f,m)),now:a=()=>Date.now()}=e,l=()=>o?.()??!1,p=await lo(t,n,r);if(l())return{status:"cancelled"};s?.({verification_url:p.verification_url,user_code:p.user_code});let d=Math.max(GP,p.interval_ms||WP),g=p.expires_at||a()+HP;for(;!l()&&a()<g;){if(await i(d),l())return{status:"cancelled"};let m;try{m=await uo(t,n,p.flow_id)}catch{continue}if(l())return{status:"cancelled"};if(m.status==="success")return{status:"success",credential:m.credential};if(m.status==="failed")return{status:"failed",error:m.error};if(m.status==="expired")return{status:"expired"}}return l()?{status:"cancelled"}:{status:"expired"}}async function Cl(e,t){return u(await c.put(`/projects/${e}/git-credential`,t))}async function wr(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}`))}async function Tl(e,t,n){return u(await c.put(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`,n))}async function Il(e,t){return u(await c.delete(`/projects/${e}/secrets/${encodeURIComponent(t)}/personal`))}var po=e=>`/accounts/${encodeURIComponent(e)}/secret-resources`,Tt=(e,t)=>`${po(e)}/${encodeURIComponent(t)}`,El=(e,t,n)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools/${encodeURIComponent(n)}`;async function Ml(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return u(await c.get(`${po(e)}${n}`))}async function Ol(e,t){return u(await c.post(po(e),t))}async function Dl(e,t,n){return u(await c.put(`${Tt(e,t)}/value`,{value:n}))}async function jl(e,t){return u(await c.post(`${Tt(e,t)}/retry`))}async function Ll(e,t){return u(await c.delete(Tt(e,t)))}async function $l(e,t,n,r){return u(await c.put(`${Tt(e,t)}/grants/${encodeURIComponent(n)}`,{},r))}async function Ul(e,t,n,r){return u(await c.delete(`${Tt(e,t)}/grants/${encodeURIComponent(n)}`,r))}async function Fl(e,t,n,r){return u(await c.put(`${Tt(e,t)}/access`,{mode:n,user_ids:r}))}async function Nl(e,t,n){return u(await c.get(El(e,t,n)))}async function Bl(e,t){let n=`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/provider-secret-pools`;return u(await c.get(n))}async function Kl(e,t,n,r){return u(await c.put(El(e,t,n),{secret_ids:r}))}async function go(){return io()}async function VP(e){return ar(()=>I().getToken(),e,mo)}function mo(){rn()}function kD(e){e===null&&rn()}function vD(e){}async function sn(){return go()}async function AD(e){return VP(e)}async function U(e,t,n){try{return await dt(e,t,{retryOnAuthError:n?.retryOnAuthError,timeoutMs:n?.timeoutMs})}catch(r){if(r instanceof ie)return cr();throw r}}function kr(e,t){return e?`/connectors/projects/${encodeURIComponent(e)}/${t}`:`/connectors/${t}`}async function on(e,t){let n=new URLSearchParams;t?.slug&&n.set("slug",t.slug),t?.includeSchemas!==void 0&&n.set("include_schemas",String(t.includeSchemas)),t?.includeOutputSchemas&&n.set("include_output_schemas","true");let r=n.toString()?`?${n.toString()}`:"";return u(await c.get(`${kr(e,"catalog")}${r}`)).connectors??[]}async function fo(e){let t=[];for(let n of await on(e,{includeSchemas:!1}))for(let r of n.actions)t.push({tool:`${n.slug}.${r.path}`,connector:n.slug,action:r.path,risk:r.risk,description:r.description||r.name,inputSchema:r.inputSchema});return t}async function ql(e,t="",n={}){let r=t.trim().toLowerCase(),s=r.split(/\s+/).filter(Boolean),o=[],i=[];for(let a of await fo(e)){let l=`${a.tool} ${a.description}`.toLowerCase();!r||l.includes(r)?o.push(a):s.every(p=>l.includes(p))&&i.push(a)}return[...o,...i].slice(0,n.limit??20)}async function yo(e,t){let n=t.indexOf(".");if(n<0)return null;let r=t.slice(0,n).trim();if(!r)return null;let s=(await on(e,{slug:r,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===r);if(!s)return null;for(let o of s.actions){let i=`${s.slug}.${o.path}`;if(i===t)return{tool:i,connector:s.slug,action:o.path,risk:o.risk,description:o.description||o.name,inputSchema:o.inputSchema,outputSchema:o.outputSchema??null}}return null}function zP(e){let t=e.indexOf("."),n=t<0?"":e.slice(0,t).trim(),r=t<0?"":e.slice(t+1).trim();if(!n||!r)throw new Error("tool must use the connector.action format");return{connector:n,action:r}}var YP=9e4;async function It(e,t,n={},r={}){let{connector:s,action:o}=zP(t),i=r.account?.trim(),a=r.approvalContext?.trim(),l=u(await c.post(kr(e,"call"),{connector:s,action:o,args:n,...i?{account:i}:{},...a?{approval_context:a}:{}},{timeout:r.timeoutMs??YP,signal:r.signal}));return l.ok&&l.binding!==void 0&&!("output"in l)&&(l.output=l.data),l}async function ho(e,t){let n=await c.get(kr(e,`connectors/${encodeURIComponent(t)}/accounts`));return u(n).accounts??[]}function JP(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 QP(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 _o(e,t,n){let r=n.filename.trim(),s=n.contentType.trim();if(!r)throw new Error("filename is required");if(!s)throw new Error("contentType is required");let o={"Content-Type":s,"X-Kortix-Attachment-Filename":encodeURIComponent(r),"X-Kortix-Attachment-Disposition":n.contentDisposition??"attachment"};n.contentId?.trim()&&(o["X-Kortix-Attachment-Content-Id"]=encodeURIComponent(n.contentId.trim())),n.connector?.trim()&&(o["X-Kortix-Attachment-Connector"]=encodeURIComponent(n.connector.trim()));let i=QP(I().backendUrl),a=kr(e,"attachments"),l=await U(`${i}${a}`,{method:"POST",headers:o,body:t},{timeoutMs:6e4}),p=await l.text(),d=null;if(p)try{d=JSON.parse(p)}catch{d=p}if(!l.ok)throw new P(JP(d,l.status),{status:l.status,code:String(d&&typeof d=="object"?d.code??l.status:l.status),details:d,response:l,endpoint:a});return d}function OD(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 Gl(e){return u(await c.get(`/projects/${e}/connections`))}async function Wl(e){return u(await c.get(`/projects/${e}/connections/all`))}async function Hl(e,t){return u(await c.post(`/projects/${e}/connections`,t))}async function Vl(e,t){return u(await c.post(`/projects/${e}/connections/me`,t))}async function zl(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/credential`,n))}function Le(e,t,n){return`/projects/${e}/connections/${t}/oauth2/${n}`}async function DD(e,t){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/oauth2/connection`,{}))}async function jD(e,t,n){return u(await c.put(Le(e,t,"application"),n))}async function LD(e,t){return u(await c.get(Le(e,t,"application")))}async function $D(e,t,n){return u(await c.post(Le(e,t,"discover"),n))}async function UD(e,t,n={}){return u(await c.post(Le(e,t,"discover-resource"),n))}async function FD(e,t,n){return u(await c.post(Le(e,t,"register"),n))}async function ND(e,t,n){return u(await c.post(Le(e,t,"authorize"),n))}async function BD(e,t,n){return u(await c.post(Le(e,t,"device"),n))}async function KD(e,t,n){return u(await c.post(Le(e,t,`device/${encodeURIComponent(n)}`),{}))}async function qD(e,t){return u(await c.get(Le(e,t,"status")))}async function Yl(e,t){return u(await c.put(`/projects/${e}/connections/${t}/revoke`,{}))}async function Jl(e,t){return u(await c.put(`/projects/${e}/connections/${t}/activate`,{}))}async function Ql(e,t){return u(await c.put(`/projects/${e}/connections/${t}/default`,{}))}async function Xl(e,t,n){return u(await c.put(`/projects/${e}/connections/${t}/label`,{label:n}))}async function Zl(e,t){return u(await c.post(`/projects/${e}/computers`,{tunnel_id:t.tunnelId,...t.share?{share:t.share}:{}}))}async function eu(e,t,n=[]){return u(await c.post(`/projects/${e}/connections/${t}/share`,{principals:n}))}async function tu(e,t,n={}){return u(await c.post(`/projects/${e}/connections/${t}/connect`,n))}async function nu(e,t){return u(await c.post(`/projects/${e}/connections/${t}/connect/finalize`,{}))}async function ru(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 su(e){return u(await c.post(`/connectors/projects/${e}/connectors/sync`,{}))}async function ou(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential-mode`,{mode:n}))}async function iu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/authorization-strategy`,{authorization_strategy:n}))}async function au(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/sensitive`,{sensitive:n}))}async function cu(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`))}async function lu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/policies`,{policies:n}))}async function GD(e,t){throw new Error("Connection-specific policies were removed. Use getConnectorPolicies(projectId, slug).")}async function WD(e,t,n){throw new Error("Connection-specific policies were removed. Use setConnectorPolicies(projectId, slug, policies).")}async function uu(e,t){return u(await c.get(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/config`))}async function pu(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/name`,{name:n}))}async function XP(e,t,n={}){return u(await c.post(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/connect`,{...n.owner?{owner:n.owner}:{},...n.successRedirectUri?{success_redirect_uri:n.successRedirectUri}:{},...n.errorRedirectUri?{error_redirect_uri:n.errorRedirectUri}:{}}))}var du=XP;async function HD(e,t){return u(await c.get(`/connectors/projects/${e}/sessions/${encodeURIComponent(t)}/connect-requests`)).connectors??[]}async function gu(e,t){return u(await c.post(`/connectors/projects/${e}/connectors`,t))}async function mu(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/auth-discovery`,t))}async function VD(e,t){return u(await c.post(`/connectors/projects/${e}/connectors/mcp-sign-in-check`,{url:t}))}async function fu(e){return u(await c.get(`/projects/${e}/connector-moves`)).moves}async function yu(e,t,n={}){return u(await c.post(`/projects/${e}/connectors/${encodeURIComponent(t)}/move`,n.connectionId?{connection_id:n.connectionId}:{}))}async function hu(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}`))}async function _u(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await c.get(`/connectors/projects/${e}/pipedream/apps${o?`?${o}`:""}`))}async function bu(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 zD(e,t={}){let n=new URLSearchParams;t.q&&n.set("q",t.q),t.category&&n.set("category",t.category),t.cursor&&n.set("cursor",t.cursor),t.limit&&n.set("limit",String(t.limit));let r=n.toString(),s=u(await c.get(`/connectors/projects/${e}/connect/toolkits${r?`?${r}`:""}`));if("toolkits"in s)return s;let o=s.cursor?.trim()||void 0;return{provider:"composio",toolkits:s.items,nextCursor:o,hasMore:!!o}}async function YD(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 bo(e,t,n){let r=typeof t=="string"||t===void 0?{...t?{q:t}:{},...n?{cursor:n}:{}}:t,s=new URLSearchParams;r.q&&s.set("q",r.q),r.category&&s.set("category",r.category),r.cursor&&s.set("cursor",r.cursor),r.limit&&s.set("limit",String(r.limit));let o=s.toString();return u(await c.get(`/connectors/projects/${e}/discover/connectors${o?`?${o}`:""}`))}async function Su(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 So(e,t){let n=new URLSearchParams({id:t});return u(await c.get(`/connectors/projects/${e}/discover/connectors/detail?${n.toString()}`))}var JD=bo,QD=So;async function xu(){return u(await c.get("/connectors/connect-status"))}async function Pu(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 wu(e,t){return u(await c.delete(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/credential`))}async function XD(e,t,n){return u(await c.put(`/connectors/projects/${e}/connectors/${encodeURIComponent(t)}/secret-binding`,{secret_identifier:n}))}async function ZP(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 ku=ZP;var vr=class extends P{reason;connector;action;binding;upstreamStatus;retryAfterSeconds;connectUrl;hint;availableAccounts;requestedAccount;constructor(t,n){let{reason:r,connector:s,action:o,binding:i,upstreamStatus:a,retryAfterSeconds:l,connectUrl:p,hint:d,availableAccounts:g,requestedAccount:m,...f}=n;super(t,{...f,name:"ConnectorCallError"}),this.reason=r,this.connector=s,this.action=o,this.binding=i??null,this.upstreamStatus=a??null,this.retryAfterSeconds=l??null,this.connectUrl=p??null,this.hint=d??null,this.availableAccounts=g??[],this.requestedAccount=m??null}},xo=class extends Error{connector;action;reason;executionId;approvalUrl;approvalSummary;approvalInstructions;retryable;constructor(t,n,r){super(`${t}.${n} is waiting for approval`+(r.approval_url?`: ${r.approval_url}`:"")),this.name="ConnectorApprovalPendingError",this.connector=t,this.action=n,this.reason=r.reason??null,this.executionId=r.execution_id??null,this.approvalUrl=r.approval_url??null,this.approvalSummary=r.approval_summary??null,this.approvalInstructions=r.approval_instructions??null,this.retryable=r.retryable??!1,Object.setPrototypeOf(this,new.target.prototype)}},Po=class extends Error{code="max_pages_exceeded";connector;action;maxPages;nextArgs;constructor(t,n,r,s){super(`${t}.${n} has more than ${r} pages; resume with nextArgs`),this.name="ConnectorPageLimitError",this.connector=t,this.action=n,this.maxPages=r,this.nextArgs=s,Object.setPrototypeOf(this,new.target.prototype)}},Ae=e=>typeof e=="string"&&e?e:null;function vu(e){return/^([a-z][a-z0-9_]*)(?::|$)/.exec(e)?.[1]??"connector_error"}function ew(e){let t=e?.headers?.get("retry-after");return t&&/^\d+$/.test(t.trim())?Number(t):null}function tw(e,t,n){if(!(e instanceof P)||typeof e.status!="number")return e;let r=e.details&&typeof e.details=="object"?e.details:{},s=Ae(r.reason)??Ae(r.error)??e.message,o=/^upstream_(\d{3})\b/.exec(s),i=typeof r.upstream_status=="number"?r.upstream_status:o?Number(o[1]):null;return new vr(Ae(r.message)??Ae(r.hint)??s,{status:e.status,code:i===null?vu(s):`upstream_${i}`,details:e.details,data:e.details,response:e.response,reason:s,connector:Ae(r.connector)??t,action:Ae(r.action)??n,binding:Ae(r.binding),upstreamStatus:i,retryAfterSeconds:typeof r.retry_after_seconds=="number"?r.retry_after_seconds:ew(e.response),connectUrl:Ae(r.connect_url),hint:Ae(r.hint),availableAccounts:Array.isArray(r.available_accounts)?r.available_accounts:[],requestedAccount:Ae(r.requested_account)})}function nw(e){if("output"in e)return e.output;let t=e.data;return t?.provider==="composio"&&"result"in t?t.result:t?.jsonrpc==="2.0"&&t.result?t.result.structuredContent??t.result.content:e.data}async function wo(e,t,n,r={},s={}){let o=t.trim(),i=n.trim();if(!o||!i)throw new Error("connector slug and action are required");let a;try{a=await It(e,`${o}.${i}`,r,s)}catch(l){throw tw(l,o,i)}if(a.status==="pending_approval")throw new xo(o,i,a);if(!a.ok||a.upstream_error){let l=a.upstream_error??a.reason??"connector_error";throw new vr(l,{status:200,code:a.upstream_error?"upstream_error":vu(l),details:a,data:a,reason:l,connector:o,action:i,binding:a.binding??null,upstreamStatus:a.upstream_status??null})}return nw(a)}async function*Au(e,t,n,r,s){let{next:o,maxPages:i=100,...a}=s,l=r;for(let p=0;l;p++){if(p>=i)throw new Po(t,n,i,l);let d=await wo(e,t,n,l,a);yield d,l=o(d,l)}}async function Ru(e){return u(await c.get(`/connectors/projects/${e}/policies`))}async function Cu(e,t,n){return u(await c.put(`/connectors/projects/${e}/policies`,{policies:t,defaultMode:n}))}async function Tu(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Iu(e){return u(await c.get(`/projects/${e}/snapshots`))}async function Ar(e){return u(await c.get(`/projects/${e}/sandbox-health`,{showErrors:!1,timeout:15e3}))}async function Eu(e,t){return u(await c.post(`/projects/${e}/snapshots/rebuild`,t?{slug:t}:{}))}async function Mu(e){return u(await c.post(`/projects/${e}/snapshots/fix-with-agent`,{}))}async function Ou(e,t){return u(await c.post(`/projects/${e}/sandbox-templates`,t))}async function Du(e,t,n){return u(await c.patch(`/projects/${e}/sandbox-templates/${t}`,n))}async function ju(e,t){return u(await c.delete(`/projects/${e}/sandbox-templates/${t}`))}async function Lu(e,t){return u(await c.post(`/projects/${e}/sandbox-templates/${t}/build`,{}))}async function $u(e){return u(await c.get(`/projects/${e}/sandboxes`))}async function Rr(e){let t=new URL(I().backendUrl,globalThis.location?.href),n=new URL(e);if(n.origin!==t.origin)throw new Error(`Refusing to attach credentials to a URL outside the Kortix backend: ${n.origin}`);let{headers:r}=await vt(e);return{url:e,headers:Object.fromEntries(r.entries())}}async function Uu(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 Fu(e,t){let n=new URLSearchParams;return t?.ref&&n.set("ref",t.ref),t?.path&&n.set("path",t.path),n.set("depth","1"),t?.cursor&&n.set("cursor",t.cursor),t?.limit!==void 0&&n.set("limit",String(t.limit)),u(await c.get(`/projects/${e}/files?${n.toString()}`,{showErrors:!1}))}async function Nu(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 Bu(e,t,n){let r=new URLSearchParams({path:t});return n&&r.set("ref",n),u(await c.get(`/projects/${e}/files/content?${r.toString()}`,{showErrors:!1}))}var rw=10*6e4;async function Ku(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"",o=`${I().backendUrl||""}/projects/${e}/files/archive${s}`;return await(await Oe(o,{method:"GET"},{timeoutMs:rw},"Failed to download")).blob()}async function qu(e,t,n){let r=new URLSearchParams;t&&r.set("ref",t),n&&r.set("path",n);let s=r.toString()?`?${r.toString()}`:"";return Rr(`${I().backendUrl}/projects/${encodeURIComponent(e)}/files/archive${s}`)}async function hj(e,t,n,r){let s=new URLSearchParams({path:t});n&&s.set("ref",n);let o=s.toString()?`?${s.toString()}`:"",i=`${I().backendUrl||""}/projects/${e}/files/raw${o}`;return await(await Oe(i,{method:"GET",...r?.signal?{signal:r.signal}:{}},{},"Failed to read file")).blob()}var ko=52428800,sw=104857600,Gu=20;var Tr=e=>`/projects/${encodeURIComponent(e)}/attachments`,Ir={showErrors:!1,deadlineCoversBody:!0},Wu=3e4,ow=12e4,iw=6e4,aw=5*6e4,cw=6e4,lw=6e4;function Cr(){return new P("Request aborted",{name:"AbortError",code:"ABORTED"})}function an(e){if(e?.aborted)throw Cr()}function uw(e){return!(e instanceof P)||e.code==="ABORTED"||e.code==="attachment_budget_exceeded"?!1:e.code==="TIMEOUT"||e.name==="TypeError"||e.status===429||e.status!==void 0&&e.status>=500}async function cn(e,t,n=!1){let r;for(let s=0;;s++){an(t);try{return await e()}catch(o){let i=n&&o instanceof P&&o.status===409&&o.code==="attachment_processing";if(t?.aborted||!(uw(o)||i))throw o;r??=Date.now()+(n?aw:iw);let a=Math.min(8e3,500*2**s)*(.5+Math.random()/2);if(Date.now()+a>=r)throw o;try{await pr(a,t)}catch{throw an(t),o}}}}function pw(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function vo(e,t,n){let r=e?.upload,s=e?.received_bytes,o=Number.isSafeInteger(s)&&s>=0&&s<=t.size,i=r?.kind==="direct"?typeof r.url=="string"&&/^https?:\/\//i.test(r.url)&&r.method==="PUT"&&pw(r.headers)&&Number.isFinite(Date.parse(r.expires_at))&&(s===0||s===t.size):r?.kind==="chunked"&&Number.isSafeInteger(r.chunk_size)&&r.chunk_size>0&&(s===t.size||s%r.chunk_size===0);if(!e?.attachment_id||n!==void 0&&e.attachment_id!==n||e.size!==t.size||!o||!i)throw new Error("Invalid attachment upload handle");return e}async function Hu(e,t,n,r){return u(await c.post(Tr(e),{...r?{attachment_id:r}:{},filename:t.name,mime:t.type||"application/octet-stream",size:t.size},{...Ir,signal:n,timeout:Wu}),"Failed to start attachment upload")}async function Vu(e,t,n,r){let s=vo({...await cn(()=>Hu(e,t,r.signal,n.attachment_id),r.signal),received_bytes:0},t,n.attachment_id);return r.onUpload?.(s),s}function zu(e,t){let n;try{n=JSON.parse(t)}catch{}let r=typeof n?.message=="string"?n.message:typeof n?.error=="string"?n.error:`HTTP ${e}`;return new P(r,{status:e,details:n,code:String(n?.statusCode??e)})}function dw(e){if(!(e instanceof P))return;let t=Number(e.details?.statusCode);return Number.isInteger(t)&&t>=400?t:e.status}function gw(e,t,n,r){return new Promise((s,o)=>{let i=new e,a=0,l=!1,p,d=f=>{l||(l=!0,p&&clearTimeout(p),r.signal?.removeEventListener("abort",m),f?o(f):s())},g=()=>{p&&clearTimeout(p),p=setTimeout(()=>{d(new P("Attachment upload stalled",{code:"TIMEOUT"})),i.abort()},cw)},m=()=>{d(Cr()),i.abort()};i.open(t.method,t.url);for(let[f,h]of Object.entries(t.headers))i.setRequestHeader(f,h);i.upload.onprogress=f=>{g(),a=Math.min(f.loaded,n.size),r.onProgress?.(a,n.size)},i.onload=()=>{i.status>=200&&i.status<300?(a<n.size&&r.onProgress?.(n.size,n.size),d()):d(zu(i.status,i.responseText))},i.onerror=()=>d(new P("Network error during attachment upload",{name:"TypeError"})),i.onabort=()=>d(Cr()),r.signal?.addEventListener("abort",m,{once:!0}),g(),i.send(n)})}async function mw(e,t,n){let r=I().fetch??fetch,s;try{s=await r(e.url,{method:e.method,headers:e.headers,body:t,signal:n.signal,credentials:"omit"})}catch(o){throw n.signal?.aborted||o instanceof Error&&o.name==="AbortError"?Cr():new P(o instanceof Error?o.message:String(o),{name:o instanceof Error?o.name:"TypeError"})}if(!s.ok)throw zu(s.status,await s.text().catch(()=>""));n.onProgress?.(t.size,t.size)}function fw(e,t,n){an(n.signal);let r=globalThis.XMLHttpRequest;return typeof r=="function"?gw(r,e,t,n):mw(e,t,n)}async function yw(e,t,n,r){let s=n,o=!1;for(r.onProgress?.(0,t.size);s.upload.kind==="direct";){let i=s.upload;try{await cn(()=>fw(i,t,r),r.signal)}catch(a){let l=dw(a);if(l!==409){if(o||!(l===400||l===401||l===403))throw a;o=!0,s=await Vu(e,t,s,r);continue}}return s={...s,received_bytes:t.size},r.onUpload?.(s),s}return Yu(e,t,s,r)}async function Yu(e,t,n,r){if(n.upload.kind!=="chunked")throw new Error("Invalid attachment upload handle");let s=n.upload.chunk_size,o=`${Tr(e)}/${encodeURIComponent(n.attachment_id)}`,i=n;for(;i.received_bytes<t.size;){an(r.signal);let a=i.received_bytes,l=Math.min(a+s,t.size),p=t.slice(a,l),d=await cn(async()=>u(await c.putRaw(`${o}/chunks/${a/s}`,p,{...Ir,signal:r.signal,timeout:Wu}),"Failed to upload attachment chunk"),r.signal);if(d.size!==t.size||d.received_bytes!==l)throw new Error("Invalid attachment chunk acknowledgment");i={...i,received_bytes:l},r.onUpload?.(i),r.onProgress?.(l,t.size)}return i}async function Er(e,t,n={}){if(!e)throw new Error("A project is required to upload attachments");if(!Number.isSafeInteger(t.size)||t.size<=0||t.size>52428800)throw new Error("Attachment must contain 1 byte to 50 MiB");an(n.signal);let r=n.resume?vo({...n.resume},t):vo({...await cn(()=>Hu(e,t,n.signal),n.signal),received_bytes:0},t);n.onUpload?.(r),r.received_bytes<t.size&&(r.upload.kind==="direct"&&Date.parse(r.upload.expires_at)-Date.now()<lw&&(r=await Vu(e,t,r,n)),r=r.upload.kind==="direct"?await yw(e,t,r,n):await Yu(e,t,r,n)),n.onProcessing?.();let s=`${Tr(e)}/${encodeURIComponent(r.attachment_id)}`;try{return await cn(async()=>u(await c.post(`${s}/complete`,{},{...Ir,signal:n.signal,timeout:ow}),"Failed to complete attachment upload"),n.signal,!0)}catch(o){throw r.upload.kind==="direct"&&o instanceof P&&o.code==="attachment_not_uploaded"&&n.onUpload?.({...r,received_bytes:0}),o}}async function ln(e,t,n={}){if(!e)throw new Error("A project is required to remove attachments");let r=await c.delete(`${Tr(e)}/${encodeURIComponent(t)}`,{...Ir,signal:n.signal});if(!r.success)throw r.error??new Error("Failed to remove attachment")}async function Ju(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 Qu(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 Xu(e,t){return u(await c.get(`/projects/${e}/commits/${encodeURIComponent(t)}`))}async function Zu(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 ep(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 tp(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 np(e,t,n){let r=new URLSearchParams;t&&r.set("status",t),n?.originSessionId&&r.set("origin_session_id",n.originSessionId),n?.limit!=null&&r.set("limit",String(n.limit)),n?.cursor&&r.set("cursor",n.cursor);let s=r.toString()?`?${r.toString()}`:"";return u(await c.get(`/projects/${e}/change-requests${s}`,{showErrors:!1,timeout:15e3}))}async function rp(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}`))}async function sp(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/diff`))}async function op(e,t){return u(await c.get(`/projects/${e}/change-requests/${t}/merge-preview`))}async function ip(e,t){return u(await c.post(`/projects/${e}/change-requests`,t))}async function ap(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/merge`,n??{},{showErrors:!1}))}async function cp(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/close`,{}))}async function lp(e,t){return u(await c.post(`/projects/${e}/change-requests/${t}/reopen`,{}))}async function up(e,t,n){return u(await c.post(`/projects/${e}/change-requests/${t}/request-changes`,{feedback:n}))}async function pp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/commit-push`,n??{}))}async function dp(e,t,n){return u(await c.patch(`/projects/${e}/change-requests/${t}`,n))}var Et=new Set,hw=500;function Mr(e){e&&(Et.add(e),Et.size>hw&&Et.delete(Et.values().next().value))}function gp(e){return!!e&&Et.has(e)}function Ej(e){e&&Et.delete(e)}var ue="kortix.session/2",Se=1,_w=["shell","read","write","edit","patch","list","glob","grep","web_fetch","web_search","todo","task","question","plan","mcp","other"];var re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),z=e=>typeof e=="string",Re=e=>z(e)&&e.length>0,Ue=e=>e===null||z(e),J=(e,t)=>e===void 0||t(e),$e=(...e)=>t=>e.includes(t),un=e=>Number.isInteger(e)&&e>=0,Mt=e=>typeof e=="number",yp=e=>e.schema===ue&&un(e.v),gt=e=>J(e,z),Ao=e=>e===void 0||re(e)&&Object.values(e).every(t=>re(t)&&z(t.version)),hp=e=>e===null||re(e)&&z(e.provider)&&z(e.model)&>(e.variant),bw=e=>e===null||re(e)&&Mt(e.input)&&Mt(e.output)&&Mt(e.cache_read)&&Mt(e.cache_write)&&J(e.reasoning,Mt)&&J(e.cost,Mt),mp=e=>re(e)&&(e.type==="text"&&z(e.text)||e.type==="attachment"&&z(e.mime)),Sw=e=>re(e)&&Array.isArray(e.content)&&e.content.every(mp)&&J(e.model_content,t=>Array.isArray(t)&&t.every(mp))&&typeof e.is_error=="boolean",fp={text:e=>z(e.text)&&J(e.bytes,un)&>(e.ref)&&(e.ref===void 0||e.bytes!==void 0),reasoning:e=>z(e.text),attachment:e=>z(e.mime)&>(e.ref)&&J(e.bytes,un)&&e.ref===void 0==(e.bytes===void 0),tool_call:e=>z(e.call_id)&&z(e.name)&&Re(e.kind)&&$e("pending","running","complete","error")(e.status)&&J(e.result,Sw),compaction:e=>Ue(e.summary)&&Ue(e.first_kept_message_id),subtask:e=>z(e.thread_id)&&z(e.agent)&&z(e.description),step:e=>$e("start","finish")(e.phase),harness:e=>Re(e.harness)&&Re(e.kind)&&typeof e.model_visible=="boolean"};function xw(e,t){if(!Array.isArray(e))return!1;let n=new Set;for(let r of e){if(!re(r)||!Re(r.id)||n.has(r.id)||!Object.hasOwn(fp,r.type)||!fp[r.type](r)||!Ao(r.ext)||t&&r.type==="tool_call"&&(r.status==="pending"||r.status==="running"||!r.result))return!1;n.add(r.id)}return!0}function Ro(e){return re(e)&&yp(e)&&Re(e.message_id)&&Re(e.thread_id)&&Number.isInteger(e.seq)&&$e("user","assistant","system")(e.role)&&$e("turn","compaction","context")(e.kind)&&$e("streaming","complete","error","aborted","interrupted")(e.status)&&typeof e.in_context=="boolean"&&J(e.hidden_reason,$e("failed_attempt","aborted","retracted","reverted","superseded"))&&J(e.origin,$e("prompt","steer","command","automation","subagent","notification"))&&J(e.agent,Ue)&&J(e.reply_to,Ue)&&J(e.parent_message_id,Ue)&>(e.native_agent_id)&>(e.context_ref)&&hp(e.model)&&bw(e.usage)&&$e("stop","tool_calls","length","error","aborted",null)(e.finish)&&(e.error===null||re(e.error)&&Re(e.error.code)&&z(e.error.message))&&z(e.created_at)&&Ue(e.completed_at)&&re(e.producer)&&Re(e.producer.harness)&&z(e.producer.harness_version)&&z(e.producer.adapter_version)&&Ao(e.ext)&&xw(e.blocks,e.status!=="streaming"&&e.in_context===!0)}function Co(e){return re(e)&&yp(e)&&Re(e.thread_id)&&Ue(e.parent_thread_id)&&(e.spawned_by===null||re(e.spawned_by))&&z(e.created_at)}function Pw(e){return re(e)&&J(e.schema,t=>t===ue)&&J(e.v,un)&>(e.session_id)&&J(e.title,Ue)&>(e.created_at)&&J(e.restore_grade,$e("native","converted","partial"))&&J(e.todos,Array.isArray)&&J(e.pending,t=>re(t)&&Array.isArray(t.questions)&&Array.isArray(t.permissions))&&J(e.selection,t=>re(t)&&J(t.agent,Ue)&&hp(t.model??null))&&J(e.harness,t=>re(t)&&z(t.current)&&Array.isArray(t.history))&&Ao(e.ext)}function Ot(e){return re(e)&&un(e.generation)&&typeof e.has_more=="boolean"&&Pw(e.session)&&Array.isArray(e.threads)&&e.threads.every(Co)&&(e.thread_id===null||Re(e.thread_id))&&Array.isArray(e.messages)&&e.messages.every(t=>Ro(t)&&t.thread_id===e.thread_id)}var ww=e=>Ot(e)&&e.messages.length>0;function kw(e,t){let{messages:n}=e.e;for(let r=0;r<n.length;r++){let s=JSON.stringify(r===0?e:{...e,e:{...e.e,messages:n.slice(r),has_more:!0}});if(s.length<=t)return s}return null}var _p={paintable:ww,fit:kw,capturedAt:()=>0},vw=new WeakMap;function bp(e,t,n){vw.set(e,{read:(r,s)=>t.read(r,s),write:async(r,s,o)=>{await t.write(r,s,o),await n(r,s)}})}function Or(e){return!!e&&typeof e.then=="function"}function Sp(e,t){return Or(e)?e.then(t):t(e)}function xp(e){let{storage:t,prefix:n,maxSessions:r,maxBytes:s,now:o}=e,i=`${n}index`,a=T=>{try{let _=t.getItem(T);return Or(_)?_.catch(()=>null):_}catch{return null}},l=async T=>{try{await t.removeItem(T)}catch{}},p=T=>{if(!T)return[];try{let _=JSON.parse(T);return _?.v===1&&Array.isArray(_.entries)?_.entries:[]}catch{return[]}},d=Promise.resolve(),g=T=>{let _=d.then(T,T);return d=_.catch(()=>{}),_},m=async T=>{try{await t.setItem(i,JSON.stringify({v:1,entries:T}))}catch{}},f=async()=>p(await a(i));return{indexKey:i,safeGet:a,safeRemove:l,enqueue:g,loadIndex:f,saveIndex:m,evict:async(T,_)=>{let b=[...T].sort((y,w)=>y.u-w.u),O=b.reduce((y,w)=>y+w.b,0);for(;b.length>r||O>s;){let y=b.findIndex(x=>x.s!==_);if(y===-1)break;let[w]=b.splice(y,1);O-=w.b,await l(`${n}${w.s}`)}return b},touch:T=>{g(async()=>{let _=await f(),b=_.find(O=>O.s===T);b&&(b.u=o(),await m(_))})},forgetScope:T=>g(async()=>{await l(`${n}${T}`);let _=await f(),b=_.filter(O=>O.s!==T);b.length!==_.length&&await m(b)})}}function Aw(e){return!!e&&e.available===!0&&e.source==="mirror"&&Array.isArray(e.messages)&&e.messages.length>0&&!!(e.runtime_session_id??e.opencode_session_id)}var Rw=12,Cw=15e5,Tw=3e5,Iw=336*60*60*1e3,kp="kortix.saved-copy";function Ew(e,t){let n=JSON.stringify(e);if(n.length<=t)return n;let{messages:r}=e.e;if(r.length===0)return null;let s=a=>{let l=r.slice(r.length-a);return JSON.stringify({...e,e:{...e.e,messages:l,message_count:l.length,complete:!1,next_cursor:String(l[0].info.id)}})},o=s(1).length-JSON.stringify(r[r.length-1]).length,i=0;for(;i<r.length;){let a=JSON.stringify(r[r.length-1-i]).length+(i>0?1:0);if(o+a>t)break;o+=a,i+=1}for(;i>0;i-=1){let a=s(i);if(a.length<=t)return a}return null}function Mw(e){let t=e.captured_at?Date.parse(e.captured_at):Number.NaN;return Number.isFinite(t)?t:0}var Ow={paintable:Aw,fit:Ew,capturedAt:Mw};function Bj(e){let t=wp(e,Ow),n=wp({...e,namespace:`${e.namespace??kp}.log`},_p),r={...t,remove:async(s,o)=>{await Promise.all([t.remove(s,o),n.remove(s,o)])},clear:async()=>{await Promise.all([t.clear(),n.clear()])}};return bp(r,n,t.remove),r}function wp(e,t){let{storage:n,userId:r,maxSessions:s=Rw,maxBytes:o=Cw,maxEnvelopeBytes:i=Tw,maxAgeMs:a=Iw,namespace:l=kp,now:p=()=>Date.now()}=e,d=`${l}:${r}:`,g=xp({storage:n,prefix:d,maxSessions:s,maxBytes:o,now:p}),{indexKey:m,safeGet:f,safeRemove:h,enqueue:S,loadIndex:v,saveIndex:T,evict:_,touch:b,forgetScope:O}=g,y=(x,k)=>`${d}${x}/${k}`,w=x=>{try{let k=n.removeItem(x);Or(k)&&k.catch(()=>{})}catch{}};return{keyFor:y,read(x,k){let C=`${x}/${k}`;return Sp(f(y(x,k)),j=>{if(!j)return null;let R;try{R=JSON.parse(j)}catch{return w(y(x,k)),O(C),null}return!R||R.v!==1||R.user!==r||p()-R.at>a||!t.paintable(R.e)?(w(y(x,k)),O(C),null):(b(C),R.e)})},write(x,k,C){let j=`${x}/${k}`;if(!t.paintable(C))return O(j);let R={v:1,user:r,at:p(),e:C},L=t.fit(R,i);if(L===null)return O(j);let le=t.capturedAt(C);return S(async()=>{let D=await v(),q=D.find(ct=>ct.s===j);if(q&&le>0&&q.c>le)return;let W=D.filter(ct=>ct.s!==j),K={s:j,b:L.length,u:p(),c:le},Me=await _([...W,K],j),Js=y(x,k);try{await n.setItem(Js,L)}catch{let ct=Me.filter(lt=>lt.s!==j).sort((lt,oP)=>lt.u-oP.u)[0];ct&&(await h(`${d}${ct.s}`),Me=Me.filter(lt=>lt.s!==ct.s));try{await n.setItem(Js,L)}catch{await h(Js),Me=Me.filter(lt=>lt.s!==j)}}await T(Me)})},remove(x,k){return O(`${x}/${k}`)},clear(){return S(async()=>{let x=await v();for(let k of x)await h(`${d}${k.s}`);await h(m)})}}}var vp=null;function Kj(e){vp=e}function Ap(){return vp}var Dw=new Set;function Rp(e){for(let t of Dw)try{t(e)}catch{}}var jw=new Set;function Cp(e){for(let t of jw)try{t(e)}catch{}}var pn=async(e,t,n,r)=>{let s=new URLSearchParams;n.thread!==void 0&&s.set("thread",n.thread),n.before_seq!==void 0&&s.set("before_seq",String(n.before_seq)),n.limit!==void 0&&s.set("limit",String(n.limit));let o=s.toString(),i=await c.get(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/log${o?`?${o}`:""}`,{showErrors:!1,signal:r});if(!i.success)throw i.error??new Error("Session log request failed");return i.data},Lw=40;async function $w(e,t,n,r,s){try{let o=await e(t,n,r,s);return Ot(o)?o:null}catch{return null}}function Tp(e,t,n,r){return $w(e,t,n,{limit:Lw},r)}function tL(e){let t=typeof e.parent_session_id=="string"?e.parent_session_id:e.metadata?.spawned_by_session;if(typeof t!="string")return null;let n=t.trim();return!n||n===e.session_id?null:n}var nL=50,Uw=200,rL=Uw;function Ip(e){let t=new URLSearchParams;e?.scope&&e.scope!=="visible"&&t.set("scope",e.scope),e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor),e?.parent&&t.set("parent",e.parent),e?.startedBy&&t.set("started_by",e.startedBy);let n=e?.q?.trim();n&&t.set("q",n);for(let r of e?.labels??[])t.append("label",r);return e?.view&&t.set(e.view,"only"),t.size>0?`?${t}`:""}async function Ep(e,t){let n=await c.get(`/projects/${e}/sessions${Ip(t)}`,{showErrors:!1});return{items:u(n),next_cursor:n.headers?.get("x-next-cursor")??null}}async function Dt(e,t){return u(await c.get(`/projects/${e}/sessions${Ip(t)}`))}async function Mp(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/sharing`,n))}async function Op(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/participants`,{showErrors:!1}))}async function Dp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/watch`,{showErrors:!1}))}async function jp(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/watch`,{watching:n}))}async function Lp(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/pin`,{pinned:n}))}async function $p(e,t,n){return u(await c.put(`/projects/${e}/sessions/${t}/archive`,{archived:n}))}function sL(e,t){let n=e.public_url??e.public_path??e.proxy_path??e.public_token??"";if(!n)return"";if(/^https?:\/\//.test(n))return n;if(t)try{return new URL(n,t).toString()}catch{return n}return n}function oL(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 Up(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/previews`))}async function Fp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/public-shares`,{showErrors:!1}))}async function Np(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/public-shares`,n))}async function Bp(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/public-shares/${n}`))}async function jt(e,t){let n=u(await c.post(`/projects/${e}/sessions`,t??{}));return!t?.initial_prompt&&!t?.fork_from_session_id&&Mr(n?.session_id),n}async function Kp(e,t){let n=t?.excludeSessionId?{exclude_session_id:t.excludeSessionId}:{},r=u(await c.post(`/projects/${e}/sessions/warm`,n,{showErrors:!1}));return r.reused||Mr(r.session.session_id),r}async function qp(e,t){let n=u(await c.post(`/projects/${e}/sessions/warm/claim`,t,{showErrors:!1}));return Mr(n.session_id),n}async function Dr(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}`,{showErrors:n?.showErrors}))}async function Gp(e,t,n,r){let s=new URLSearchParams;n&&s.set("limit",String(n)),r?.cursor&&s.set("cursor",r.cursor),r?.includeEvents!=null&&s.set("include_events",String(r.includeEvents));let o=s.toString();return u(await c.get(`/projects/${e}/sessions/${t}/audit${o?`?${o}`:""}`,{showErrors:r?.showErrors}))}async function Wp(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 jr(e,t,n){let r=new URLSearchParams({shape:"sync"});return n?.limit!=null&&r.set("limit",String(n.limit)),n?.history&&r.set("history","true"),n?.before&&r.set("before",n.before),n?.child&&r.set("child",n.child),u(await c.get(`/projects/${e}/sessions/${t}/transcript?${r.toString()}`,{showErrors:!1,signal:n?.signal}))}async function Hp(e,t,n={},r){let s;try{s=await pn(e,t,n,r?.signal)}catch(o){if(o?.status===404)return null;throw o}if(!Ot(s))throw new Error("The response is not a session log page");return s}async function Lr(e,t,n){return u(await c.get(`/projects/${e}/sessions/${t}/turn`,n?.showErrors===!1?{showErrors:!1}:void 0))}async function iL(e,t,n){let r=new URLSearchParams;n?.transcript!=null&&r.set("transcript",String(n.transcript));let s=r.toString();return u(await c.get(`/projects/${e}/sessions/${t}/snapshot${s?`?${s}`:""}`,{signal:n?.signal,showErrors:!1}))}function Fw(e){if(e)return e==="interrupt"?"transcript":"composer"}async function $r(e,t,n){let r=n.placement??Fw(n.delivery);return u(await c.post(`/projects/${e}/sessions/${t}/prompts`,{client_message_id:n.clientMessageId,message_id:n.messageId,parts:n.parts,...r?{placement:r}:{},...n.delivery?{delivery:n.delivery}:{},...n.overrides?{overrides:n.overrides}:{},...n.remintOnDelivery?{remint_on_delivery:!0}:{},...typeof n.clientSentAtMs=="number"?{client_sent_at_ms:Math.trunc(n.clientSentAtMs)}:{}}))}async function Vp(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/prompts`,{showErrors:!1}))}async function zp(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/prompts/${n}`,{showErrors:!1})).removed}async function Yp(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{text:r},{showErrors:!1}))}async function Jp(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}/prompts/${n}`,{delivery:"interrupt"},{showErrors:!1}))}async function Qp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/${n}/retry`,{},{showErrors:!1}))}async function Xp(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/prompts/hold`,{held:n},{showErrors:!1}))}async function Zp(e,t,n){return u(await c.patch(`/projects/${e}/sessions/${t}`,n))}async function ed(e,t){let n=u(await c.delete(`/projects/${e}/sessions/${t}`));return Ap()?.remove(e,t),Cp(t),n}async function td(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/recover`,{},{showErrors:!1}))}async function nd(e,t){return u(await c.post(`/projects/${e}/sessions/${t}/restore`,{},{showErrors:!1}))}async function Ur(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${t}/restart`,{}))}async function Fr(e,t){let n=u(await c.post(`/projects/${e}/sessions/${t}/stop`,{}));return Rp(t),n}async function rd(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/config`,{showErrors:!1}))}function Nw(e){let t=e.split(`
|
|
8
8
|
`).filter(n=>n.startsWith("data:")).map(n=>n.slice(5).replace(/^ /,""));if(t.length===0)return null;try{return JSON.parse(t.join(`
|
|
9
|
-
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function sd(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function
|
|
9
|
+
`))}catch(n){throw new Error("reloadProjectSessionConfigStream received an invalid SSE frame",{cause:n})}}async function sd(e,t,n={}){return u(await c.post(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload`,n,{showErrors:!1}))}async function od(e,t,n,r,s={}){let o=await c.postStream(`/projects/${e}/sessions/${encodeURIComponent(t)}/reload-stream`,n,s);if(!o.ok){let d=await o.json().catch(()=>null);throw new P(d?.error||`Reload failed: HTTP ${o.status}`,{status:o.status,code:d?.code,data:d})}let i=o.body?.getReader();if(!i)throw new Error("Reload stream is unavailable on this runtime (no response body)");let a=new TextDecoder,l="",p=null;try{for(;;){let{done:d,value:g}=await i.read();if(d)break;l+=a.decode(g,{stream:!0});let m=l.indexOf(`
|
|
10
10
|
|
|
11
11
|
`);for(;m!==-1;){let f=l.slice(0,m);l=l.slice(m+2),m=l.indexOf(`
|
|
12
12
|
|
|
13
|
-
`);let _=jw(f);if(_){if(r(_),_.type==="error")throw new S(_.error,{status:_.status,code:_.code,data:{reason:_.reason}});_.type==="done"&&(p=_.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function ad(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function cd(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function ld(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Fr(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function ud(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function pd(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function nj(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function dd(e){return u(await c.get(`/projects/${e}/triggers`))}async function gd(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function md(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function fd(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function ij(e){return u(await c.get(`/accounts/${e}/automations`))}async function aj(e,t){return u(await c.patch(`/accounts/${e}/automations`,{paused:t},{showErrors:!1}))}async function yd(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function hd(e){let t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.limit!=null&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function _d(e,t,n){let r={};return n?.payload!==void 0&&(r.payload=n.payload),n?.dryRun!==void 0&&(r.dry_run=n.dryRun),u(await c.post(`/projects/${e}/triggers/${t}/fire`,r))}async function bd(e,t,n){return u(await c.get(`/projects/${e}/triggers/${t}/runs${hd(n)}`))}async function Pd(e,t){return u(await c.get(`/projects/${e}/trigger-runs${hd(t)}`))}async function Sd(e,t,n,r){return u(await c.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function xd(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await c.get(`/projects/${e}/triggers/event-types?${n}`))}async function wd(e){return u(await c.get(`/projects/${e}/triggers/event-apps`))}var Xe=new Map;function Ts(e,t){return`${e}::${t}`}function kd(e,t){Xe.delete(e),Xe.set(e,t)}function vd(e,t){let n=Ts(e,t),r=Xe.get(n);return r&&kd(n,r),r}function Nr(e,t,n){let r=Ts(e,t);if(!Xe.has(r)&&Xe.size>=512){let o=Xe.keys().next().value;o!==void 0&&Xe.delete(o)}kd(r,n)}function Ad(e,t){Xe.delete(Ts(e,t))}function $w(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function dn(){return $w(C().backendUrl||"http://localhost:8008/v1")}function Rd(){let e=C().sandboxId;return e?`${dn()}/p/${e}/8000`:""}function Uw(e,t=8e3){return`${dn()}/p/${e}/${t}`}function Fe(e,t=8e3){return Uw(e,t)}function Cd(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var Is=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 yj(e){return e instanceof Error&&e.name==="SessionStartError"}function Fw(e){let t=e,n=t?.status,r=t?.code??t?.details?.code??t?.details?.error,o=t?.message||"Unable to start this session";return n&&n>=400&&n<500&&n!==408&&n!==429?new Is(o,{status:n,code:r,terminal:!0}):null}function Td(e,t,n){let r=typeof n=="number"?n:n?.waitMs,o=typeof n=="number"?void 0:n?.repositoryMode,s=new URLSearchParams;r&&r>0&&s.set("wait_ms",String(Math.floor(r))),o&&s.set("repository_mode",o),typeof n=="object"&&n?.keepStopped&&s.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&s.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=s.size>0?`?${s.toString()}`:"";return c.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function mt(e,t,n){let r=await Td(e,t,n);if(!r.success||!r.data){let o=Fw(r.error);if(o&&!(o.status===404&&mp(t)))throw o;return null}return Ed(e,t,r.data)}async function Id(e,t,n){let r=await Td(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return Ed(e,t,r.data)}function Ed(e,t,n){let r=n.sandbox?.external_id,o=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&o&&Nr(e,t,{runtimeSessionId:o,opencodeSessionId:o,runtimeUrl:Fe(r),sandboxId:r}),n}function hj(e,t){return["session-start",e,t]}async function Md(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function Od(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function Dd(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 kj(e,t){return u(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Ld(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Nw(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Br(e){let t=e.connectors_required?Ld(e.connectors_required):void 0,n=e.connectors_personal?Ld(e.connectors_personal):void 0;if(t&&n&&!Nw(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 jd(e,t,n){let r=Br(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function Dj(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Es(n.block):null}}async function Lj(e,t,n){let r=Es(n,!0),o=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...o,block:o.block?Es(o.block):null}}function Es(e,t=!1){let n=Br(e);if(n.workspace===void 0)return n;let r=n.workspace==="branch";if(n.repository_access!==void 0&&n.repository_access!==r)throw new Error("repository_access conflicts with workspace");if(t&&n.workspace==="read"&&n.repository_access===void 0)throw new Error("Legacy read is unavailable. Set repository_access explicitly.");return n.repository_access??=r,delete n.workspace,n}async function jj(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function $d(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}var Kr="Use setBillingPlan().",Ud="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Fd(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",monthly_usd:null,status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function Bw(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function Bj(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,monthlyUsd:t.monthly_usd??null};let n=e??Fd(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),o=(n.tier?.display_name||"").trim()||r;return{family:Bw(r),label:o,sublabel:null,monthlyUsd:null}}function Kw(e){return!!e&&e.can_manage_billing!==!1}function Kj(e){return e?.subscription?.can_purchase_credits===!0&&Kw(e)}async function Nd(e){let t=await c.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?Fd():t.data}function Bd(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString();return n?`?${n}`:""}async function Kd(e){return Nd(`/billing/account-state${Bd(e)}`)}async function qd(e){return Nd(`/billing/account-state/minimal${Bd(e)}`)}async function Gd(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 Wd(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 Hd(){return u(await c.get("/billing/credit-breakdown"))}async function Vd(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function zd(){return u(await c.get("/billing/tier-configurations"))}async function qj(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return At(e,`/v1/billing/account-state${t}`)}async function Yd(e){throw F("createCheckoutSession",Kr)}async function Jd(e,t){throw F("confirmCheckoutSession",Kr)}async function Qd(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Xd(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Zd(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function eg(e,t,n){throw F("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function tg(e){throw F("cancelScheduledChange",Ud)}async function ng(e,t){throw F("getProrationPreview",Ud)}async function rg(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 og(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 Gj(e){return u(await c.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function sg(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 Wj(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 ig(e){return u(await c.post("/billing/plan/preview",{monthly_usd:e.monthlyUsd,account_id:e.accountId}),"Failed to preview the plan change")}async function ag(e){return u(await c.post("/billing/plan",{monthly_usd:e.monthlyUsd,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale,account_id:e.accountId}),"Failed to set billing plan")}async function cg(e){return u(await c.post("/billing/enterprise-offer/checkout",{success_url:e.successUrl,cancel_url:e.cancelUrl,account_id:e.accountId}),"Failed to start the Enterprise checkout")}async function lg(e={}){return u(await c.post("/billing/enterprise/contact",{account_id:e.accountId,...e.note?{note:e.note}:{}}),"Failed to reach Kortix sales")}async function Hj(e){throw F("createPerSeatCheckout",Kr)}async function Vj(e){throw F("claimPerSeatBilling",Kr)}async function zj(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function ug(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 Ms(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function qr(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Gr(e){return e.size>0?`?${e}`:""}async function dg(e={}){let t=new URLSearchParams;return Ms(t,e),e.ownerId&&t.set("owner_id",e.ownerId),qr(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${Gr(t)}`))}async function Wr(e,t={}){let n=new URLSearchParams;return Ms(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Gr(n)}`))}async function e$(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),qr(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${Gr(t)}`))}async function t$(e={}){let t=new URLSearchParams;return Ms(t,e),e.sessionId&&t.set("session_id",e.sessionId),qr(t,e),u(await c.get(`/usage/cost-summary${Gr(t)}`))}function pg(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let o=t;o.ownerId&&n.set("owner_id",o.ownerId)}qr(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`${C().backendUrl||""}${r}?${n}`}async function n$(e,t={}){let n=pg(e==="projects"?"projects":"sessions",t),r=await Oe(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),o=r.headers.get("x-kortix-row-cap"),s=o!=null?Number(o):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(s)?s:null}}async function gg(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function i$(e){return gg("slack",e)}function a$(e){return gg("teams",e)}async function mg(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function c$(e){return mg("slack",e)}function l$(e){return mg("teams",e)}async function fg(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function yg(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var qw={oauth_available:!1,install_url:null};async function hg(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?qw:t.data}async function _g(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 bg(e,t){return _g("slack",e,t)}function Pg(e,t){return _g("teams",e,t)}async function Sg(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function xg(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 u$(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/telegram/installation`,{showErrors:!1});return t.success?t.data??null:null}async function p$(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/telegram/connect`,t,{showErrors:!1}),"Failed to connect Telegram")}async function d$(e,t){return u(await c.put(`/projects/${encodeURIComponent(e)}/channels/telegram/allowed-users`,{user_ids:t},{showErrors:!1}),"Failed to update allowed Telegram users")}async function g$(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/telegram`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect Telegram")}async function wg(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 kg(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 Os(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 Gw={provider:"agentmail",managed_available:!1};async function vg(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?Os(r.data):null}async function Ag(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?Gw:t.data}async function Rg(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return Os(n)}async function Cg(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 Tg(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 Os(r)}async function m$(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function f$(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 Ig(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Eg(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Mg(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Og(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Dg(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 Lg(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function jg(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function $g(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ug(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Fg(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ng(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Bg(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Kg(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function qg(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function Gg(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Wg(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Hg(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Vg(e,t,n,r,o){return u(await c.post(`/projects/${e}/gateway/playground`,{prompt:t,models:n,...r?{system:r}:{},...o&&Object.keys(o).length?{generationConfig:o}:{}}),"Gateway request failed")}async function b$(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function x$(){throw F("getReferralCode")}async function w$(){throw F("refreshReferralCode")}async function k$(e){throw F("validateReferralCode")}async function v$(){throw F("getReferralStats")}async function A$(e={}){throw F("listReferrals")}async function R$(e){throw F("sendReferralEmails")}var Ds="call:";function Yg(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Ds)&&e.length>Ds.length?{type:"connector_call",executionId:e.slice(Ds.length)}:{type:"review_item",reviewItemId:e}}function Ww(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function T$(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Ww(n.status)]+=1;return t}function I$(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 Ls(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Jg(e){let t=e.indexOf(".");return t<=0?Ls(e):`(${Ls(e.slice(0,t))}) ${Ls(e.slice(t+1))}`}function Hw(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var jt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},j=e=>typeof e=="string"&&e?e:void 0,Ce=e=>Array.isArray(e)?e:void 0,zg=e=>typeof e=="number"?e:0,Vw=e=>e.split(`
|
|
14
|
-
`).map(t=>t.trim()).filter(Boolean);function zw(e,t){let n=jt(e.advanced),r=j(e.description),o=Ce(e.whatChanged)??(r?Vw(r):t.summary?[t.summary]:[]);return{crId:j(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:o,impact:j(e.impact)??"",verification:Ce(e.verification)??[],previewUrl:j(e.previewUrl)??j(e.preview_url),conflicts:Ce(e.conflicts),requestedChanges:Ce(e.requested_changes)??[],advanced:{headRef:j(n.headRef)??j(e.head_ref)??"",baseRef:j(n.baseRef)??j(e.base_ref)??"",headSha:j(n.headSha)??j(e.head_sha)??j(e.head_commit_sha)??"",baseSha:j(n.baseSha)??j(e.base_sha)??"",additions:zg(n.additions),deletions:zg(n.deletions),files:Ce(n.files)??[],mergeMode:j(n.mergeMode)??"merge"}}}function Yw(e,t){let n=Ce(e.actions);if(n)return{actions:n.map((l,p)=>({id:j(l.id)??`${t.review_item_id}-${p}`,title:j(l.title)??"Action",connector:j(l.connector)??"",action:j(l.action)??"",consequence:j(l.consequence)??"",risk:j(l.risk)??t.risk,icon:j(l.icon)??"generic",argsPreview:Ce(l.argsPreview)??[],policySource:j(l.policySource)??"Requires approval",decided:l.decided==="approved"||l.decided==="denied"?l.decided:void 0}))};let r=j(e.action_path)??"",{connector:o,action:s}=Hw(r),i=jt(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:j(e.execution_id)??t.review_item_id,title:r?Jg(r):t.title||"Run action",connector:o,connectorName:j(e.connector_name),action:s,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([l,p])=>({key:l,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:j(e.approval_context),...Object.keys(jt(e.resolved_preview)).length>0?{resolvedPreview:jt(e.resolved_preview)}:{},...j(e.resolved_error)?{resolvedError:j(e.resolved_error)}:{},connectorRisk:j(e.risk)??null,policySource:"Requires approval",expiresAt:j(t.expires_at)}]}}function Jw(e,t){return{artifactKind:j(e.artifactKind)??"document",artifactLabel:j(e.artifactLabel)??"Output",previewUrl:j(e.previewUrl)??j(e.preview_url),preview:j(e.preview),files:Ce(e.files),note:j(e.note)??t.summary??""}}function Qw(e,t){return{question:j(e.question)??t.title??"",context:j(e.context),options:Ce(e.options)??[]}}function Xw(e,t){return{note:j(e.note)??t.summary??"",children:Ce(e.children)??[]}}function Zw(e){let t=jt(e.detail);switch(e.kind){case"change":return zw(t,e);case"approval":return Yw(t,e);case"output":return Jw(t,e);case"decision":return Qw(t,e);case"batch":return Xw(t,e)}}function ek(e,t){let n=typeof e.number=="number"?e.number:void 0,r=j(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function E$(e,t={}){let n=jt(e.detail),r=e.origin_session_id??void 0,o=r?t.sessionLabels?.[r]:void 0,s=e.kind==="approval"?j(n.action_path):void 0,i=e.kind==="change"?ek(n,e.summary):e.kind==="approval"?o??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:s?Jg(s):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,expiresAt:j(e.expires_at),detail:Zw(e)}}var Z={PROJECT_READ:"project.read",PROJECT_WRITE:"project.write",PROJECT_DELETE:"project.delete",PROJECT_SESSION_READ:"project.session.read",PROJECT_SESSION_START:"project.session.start",PROJECT_SESSION_STOP:"project.session.stop",PROJECT_SESSION_BINDINGS_WRITE:"project.session.bindings.write",PROJECT_MEMBERS_READ:"project.members.read",PROJECT_MEMBERS_MANAGE:"project.members.manage",PROJECT_TRIGGER_READ:"project.trigger.read",PROJECT_TRIGGER_CREATE:"project.trigger.create",PROJECT_TRIGGER_UPDATE:"project.trigger.update",PROJECT_TRIGGER_DELETE:"project.trigger.delete",PROJECT_TRIGGER_FIRE:"project.trigger.fire",PROJECT_GATEWAY_LOGS_READ:"project.gateway.logs.read",PROJECT_GATEWAY_SPEND_READ:"project.gateway.spend.read",PROJECT_USAGE_READ:"project.usage.read",PROJECT_GATEWAY_BUDGET_SET:"project.gateway.budget.set",PROJECT_GATEWAY_KEYS_MANAGE:"project.gateway.keys.manage",PROJECT_AGENT_READ:"project.agent.read",PROJECT_AGENT_WRITE:"project.agent.write",PROJECT_SKILL_READ:"project.skill.read",PROJECT_SKILL_WRITE:"project.skill.write",PROJECT_COMMAND_READ:"project.command.read",PROJECT_COMMAND_WRITE:"project.command.write",PROJECT_FILE_READ:"project.file.read",PROJECT_FILE_WRITE:"project.file.write",PROJECT_SETTINGS_WRITE:"project.settings.write",PROJECT_SANDBOX_WRITE:"project.sandbox.write",PROJECT_MODEL_READ:"project.model.read",PROJECT_MODEL_WRITE:"project.model.write",PROJECT_GITOPS_READ:"project.gitops.read",PROJECT_GITOPS_PUSH:"project.gitops.push",PROJECT_GITOPS_MERGE:"project.gitops.merge",PROJECT_GITOPS_REF_ANY:"project.gitops.ref.any",PROJECT_GITOPS_REF_DELETE:"project.gitops.ref.delete",PROJECT_SECRET_READ:"project.secret.read",PROJECT_SECRET_WRITE:"project.secret.write",PROJECT_CONNECTOR_READ:"project.connector.read",PROJECT_CONNECTOR_CONNECTIONS_MANAGE:"project.connector.connections.manage",PROJECT_CONNECTOR_WRITE:"project.connector.write",PROJECT_APP_READ:"project.app.read",PROJECT_APP_WRITE:"project.app.write",PROJECT_APP_DEPLOY:"project.app.deploy",PROJECT_APP_ADMIN:"project.app.admin",PROJECT_REVIEW_READ:"project.review.read",PROJECT_REVIEW_SUBMIT:"project.review.submit",PROJECT_REVIEW_ACT:"project.review.act",PROJECT_ROOM_READ:"project.room.read",PROJECT_ROOM_WRITE:"project.room.write",PROJECT_CREDENTIALS_ISSUE:"project.credentials.issue"},D$=[Z.PROJECT_WRITE,Z.PROJECT_TRIGGER_CREATE,Z.PROJECT_TRIGGER_FIRE,Z.PROJECT_TRIGGER_UPDATE,Z.PROJECT_TRIGGER_DELETE];function L$(e){let t=r=>e[r]?.allowed===!0,n=t(Z.PROJECT_WRITE);return{canCreate:n&&t(Z.PROJECT_TRIGGER_CREATE),canFire:t(Z.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(Z.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(Z.PROJECT_TRIGGER_DELETE)}}var j$=[Z.PROJECT_WRITE,Z.PROJECT_GITOPS_PUSH,Z.PROJECT_GITOPS_MERGE,Z.PROJECT_REVIEW_ACT];function tk(e){let t=r=>e[r]?.allowed===!0,n=t(Z.PROJECT_WRITE);return{canOpen:n&&t(Z.PROJECT_GITOPS_PUSH),canMerge:n&&t(Z.PROJECT_GITOPS_MERGE),canClose:n}}function $$(e,t,n){let r=Yg(e.id);if(r.type==="connector_call"){let o=e.kind==="approval"?e.detail.actions?.[0]:void 0;return(t==="approve"||t==="reject")&&o?.canResolve!==!1&&o?.previewAuthorized!==!1}if(r.type==="change_request"){if(t==="answer")return!1;if(t==="approve")return tk(n).canMerge}return n[Z.PROJECT_WRITE]?.allowed===!0&&n[Z.PROJECT_REVIEW_ACT]?.allowed===!0}function U(e){return c.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function Qg(e){return A(await U(`/accounts/${e}/iam/groups`)).groups}async function Xg(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}`))}async function Zg(e,t){return A(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function em(e,t,n){return A(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function tm(e,t){return A(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function nm(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}/members`)).members}async function rm(e,t,n){return A(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function G$(e,t){return A(await U(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function om(e,t,n){return A(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function W$(e,t){return A(await U(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function H$(e,t){let n=A(await U(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function Ze(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}async function Q$(e,t={}){let n=Ze({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await U(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function n0(e,t={}){let n=Ze({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await U(`/accounts/${e}/iam/policies${n}`)).policies}async function r0(e,t){return A(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function o0(e,t,n){return A(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function s0(e,t){return A(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function i0(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function a0(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function sm(e){return A(await U(`/accounts/${e}/iam/roles`)).roles}async function im(e){return A(await U(`/accounts/${e}/iam/agent-identities`)).agents}async function am(e){return A(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function cm(e,t){return A(await U(`/accounts/${e}/iam/roles/${t}/permissions`))}async function p0(e){return A(await U(`/accounts/${e}/iam/actions`)).actions}async function lm(e,t){return A(await U(`/accounts/${e}/iam/roles/${t}/usage`))}async function um(e,t){return A(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function pm(e,t,n){return A(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function dm(e,t,n){return A(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function gm(e,t){return A(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function d0(e,t,n){return A(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function y0(e){return A(await U(`/accounts/${e}/iam/scim/tokens`)).tokens}async function h0(e,t){return A(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function _0(e,t){return A(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function x0(e){return A(await U(`/accounts/${e}/iam/mfa-required`))}async function w0(e){return A(await U(`/accounts/${e}/iam/mfa-required/preview`))}async function k0(e,t){return A(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function v0(e){return A(await U(`/accounts/${e}/iam/session-oversight`))}async function A0(e,t){return A(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function I0(e){return A(await U(`/accounts/${e}/iam/sso/provider`)).provider}async function E0(e,t){return A(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function M0(e,t){return A(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function O0(e){return A(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function D0(e){return A(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function L0(e){return A(await U(`/accounts/${e}/iam/sso/mappings`)).mappings}async function j0(e,t){return A(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function $0(e,t){return A(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function B0(e){return A(await U(`/accounts/${e}/iam/session-policy`))}async function K0(e,t){return A(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function q0(e){return A(await U(`/accounts/${e}/iam/sessions`)).sessions}async function G0(e,t){return A(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function W0(e){return A(await U(`/accounts/${e}/iam/pat-policy`))}async function H0(e,t){return A(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function J0(e){return A(await U(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function Q0(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function X0(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function Z0(e,t){return A(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function oU(e){return A(await U(`/accounts/${e}/audit/webhooks`)).webhooks}async function sU(e,t){return A(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function iU(e,t,n){return A(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function aU(e,t){return A(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function cU(e,t={}){let n=Ze({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return A(await U(`/accounts/${e}/audit${n}`))}async function mm(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),A(await U(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function fm(e,t,n){return n.length===0?[]:A(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function fU(e){return A(await U(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function yU(e,t){return A(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function ym(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function hm(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function _m(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function bm(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function Pm(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Sm(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function nk(e){return Ze({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function xm(e,t){return u(await U(`/accounts/${e}/iam/assignments${nk(t)}`)).assignments}async function wm(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 km(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function vm(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await U(`/accounts/${e}/iam/permissions${n}`)).permissions}async function CU(){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 TU(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function IU(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function EU(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function MU(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function jU(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function $U(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function UU(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function FU(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function NU(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function BU(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function KU(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var Am="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function WU(e){throw F("getGoogleAuthUrl",Am)}async function HU(e,t){throw F("convertPresentationToGoogleSlides",Am)}async function Rm(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind),t?.sessionId&&n.set("session_id",t.sessionId),t?.limit!=null&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);let r=n.toString();return u(await c.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function Cm(e){return u(await c.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function Tm(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function Im(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function Em(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function Mm(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}async function Om(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Dm(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 Lm(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 js=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function jm(e,t=""){return`${dn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function $m(e){let t=await fetch(e,{method:"GET",headers:{Accept:"application/json"}}),n=await t.text().catch(()=>""),r=null;try{r=n?JSON.parse(n):null}catch{}if(!t.ok){let o=(r&&typeof r=="object"&&"error"in r&&typeof r.error=="string"?r.error:null)||t.statusText||`HTTP ${t.status}`;throw new js(o,t.status)}return r}async function tF(e){return $m(jm(e))}async function nF(e){return $m(jm(e,"/messages"))}async function Um(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function Fm(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function $s(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Us(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}var rk=4;async function Nm(e,t){let n=new Array(e.length),r=0,o=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(rk,e.length)},o));let s={done:[],failed:[]};return e.forEach((i,a)=>{let l=n[a];l.ok?s.done.push(i):s.failed.push({reminder:i,error:l.error})}),s}function Bm(e,t,n){return Nm(t,r=>$s(e,r.sessionId,r.reminderId,n))}function Km(e,t){return Nm(t,n=>Us(e,n.sessionId,n.reminderId))}async function qm(e){return u(await c.get(`/projects/${e}/reminders`))}var Se=e=>`/projects/${e}/rooms`;function Fs(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o!==void 0&&o!==!1&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}async function Gm(e,t={}){return u(await c.get(`${Se(e)}${Fs({name:t.name,archived:t.archived,mine:t.mine})}`))}async function Wm(e,t){return u(await c.post(Se(e),t))}async function Hm(e,t){return u(await c.get(`${Se(e)}/${t}`))}async function Vm(e,t,n){return u(await c.patch(`${Se(e)}/${t}`,n))}async function zm(e,t,n={}){return u(await c.get(`${Se(e)}/${t}/messages${Fs({after:n.after,before:n.before,limit:n.limit,top:n.top,thread:n.thread})}`))}async function Ym(e,t,n){return u(await c.post(`${Se(e)}/${t}/messages`,n))}async function Jm(e,t,n){return u(await c.post(`${Se(e)}/${t}/read`,n===void 0?{}:{seq:n}))}async function Qm(e,t,n,r={}){return u(await c.put(`${Se(e)}/${t}/members/sessions/${n}`,r))}async function Xm(e,t,n){return u(await c.delete(`${Se(e)}/${t}/members/sessions/${n}`))}async function Zm(e,t,n,r={}){return u(await c.put(`${Se(e)}/${t}/members/people/${n}`,r))}async function ef(e,t,n){return u(await c.delete(`${Se(e)}/${t}/members/people/${n}`))}async function tf(e,t){return u(await c.get(`${Se(e)}/people${Fs({q:t})}`))}async function nf(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 rf(e){let{accountId:t,expiresAt:n,projectId:r,name:o}=e;return u(await c.post("/accounts/tokens",{name:o,...t?{account_id:t}:{},...n?{expires_at:n}:{},...r?{project_id:r}:{}}))}async function of(e,t,n){let r=new URLSearchParams;t&&r.set("account_id",t),n?.deleteRevoked&&r.set("delete_revoked","true");let o=r.size>0?`?${r.toString()}`:"";return u(await c.delete(`/accounts/tokens/${encodeURIComponent(e)}${o}`))}async function sf(){return u(await c.get("/oauth/grants")).grants}async function af(e){return u(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function dF(){return u(await c.get("/accounts/me/devices")).devices}async function gF(e){return u(await c.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function cf(e){return u(await c.get(`/projects/${e}/cli-token`))}async function lf(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function uf(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}function $t(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,o]of Object.entries(e))n.includes(` ${r} `)&&o!=null&&o!==""&&t.set(r,String(o));return t}function Ns(e={}){return{format:e.format,action:e.action,actor:e.actor,actor_type:e.actorType,project_id:e.projectId,session_id:e.sessionId,source:e.source,credential_kind:e.credentialKind,phase:e.phase,outcome:e.outcome,resource_type:e.resourceType,request_id:e.requestId,correlation_id:e.correlationId,since:e.since,until:e.until,q:e.q,cursor:e.cursor,limit:e.limit}}async function pf(e,t){let n=$t(Ns(t)).toString();return u(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function df(e,t){let n=$t(Ns({...t,projectId:void 0})).toString();return u(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function gf(e,t){let n=$t(Ns(t)).toString();return u(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function mf(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function ff(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function yf(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function hf(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function _f(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 bf(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 xF(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function Pf(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 Sf(){return u(await c.get("/marketplace/marketplaces"))}async function xf(){return u(await c.get("/marketplace/marketplaces/featured"))}async function wf(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function kf(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function vf(){return u(await c.get("/marketplace/sources"))}async function Af(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Rf(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function AF(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function TF(e){throw F("getTemplate")}async function IF(e,t){throw F("installTemplate")}async function Cf(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Tf(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Bs(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function If(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Ef(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Mf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function Of(e,t){let n=await Bs(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await c.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),o=new TextEncoder().encode(JSON.stringify(r)),s="";for(let i of o)s+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(s)}`}}async function Df(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function Lf(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 jf(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function $f(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Ks(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function qs(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function ok(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function sk(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 Uf(e,t,n={}){let r=await ok(t),o=n.mediaType??"application/gzip",s=await Ks(e,{kind:"archive",media_type:o});if(!s.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>s.upload.max_bytes)throw new Error(`App artifact exceeds ${s.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(s.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:o}),signal:n.signal,headers:{"content-type":o,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),qs(e,s.artifact.artifact_id,{sha256:await sk(r),size_bytes:r.byteLength})}async function Ff(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Nf(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Bf(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Kf(e,t,n,r={}){let o=new URLSearchParams;r.after!==void 0&&o.set("after",String(r.after)),r.limit!==void 0&&o.set("limit",String(r.limit));let s=o.size?`?${o.toString()}`:"";return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${s}`),"Failed to load App logs")}async function qf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Gf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Wf(e,t,n){return u(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Hf(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var fe=(e,t)=>`/projects/${e}/apps/${t}`;async function Vf(e,t){return u(await c.get(`${fe(e,t)}/machines`),"Failed to list machines").machines}async function Gs(e,t,n,r){return u(await c.post(`${fe(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var zf=(e,t,n)=>Gs(e,t,n,"start"),Yf=(e,t,n)=>Gs(e,t,n,"stop"),Jf=(e,t,n)=>Gs(e,t,n,"restart");async function Qf(e,t,n){return u(await c.delete(`${fe(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Xf(e,t,n,r={}){return u(await c.put(`${fe(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function Zf(e,t,n){return u(await c.post(`${fe(e,t)}/exec`,n),"Failed to run the command")}async function ey(e,t){return u(await c.get(`${fe(e,t)}/volumes`),"Failed to list volumes").volumes}async function ty(e,t,n){return u(await c.post(`${fe(e,t)}/volumes`,n),"Failed to create the volume")}async function ny(e,t,n,r){return u(await c.patch(`${fe(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function ry(e,t,n,r){u(await c.delete(`${fe(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function oy(e,t,n){return u(await c.get(`${fe(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function sy(e,t,n){return u(await c.post(`${fe(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function iy(e,t,n,r){return u(await c.post(`${fe(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function ay(e,t,n,r){return u(await c.post(`${fe(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function ue(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var de=e=>`/drives/${encodeURIComponent(e)}`;async function WF(e){let t=u(await c.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new S("Files not found",{status:404});return t[0]}async function HF(e,t){return u(await c.get(`${de(e)}/access?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load sharing")}async function VF(e,t){return u(await c.put(`${de(e)}/access`,t),"Failed to share folder")}async function zF(e,t){let n=u(await c.delete(`${de(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function YF(e){return u(await c.get(`${de(e)}/principals`),"Failed to load people")}async function JF(e){return u(await c.get(`${de(e)}/conflicts`),"Failed to load conflicts").conflicts}async function QF(e,t){u(await c.post(`${de(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function XF(e,t="/"){return(await ik(e,t)).entries}async function ik(e,t="/"){return u(await c.get(`${de(e)}/files?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load files")}function cy(e,t,n){let r=ue(C().backendUrl),o={path:t};return n?.download&&(o.download="1"),`${r}${de(e)}/files/content?${new URLSearchParams(o)}`}async function ZF(e,t,n){let r=await $(cy(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new S(o?.message||"Could not download file",{status:r.status})}return r.blob()}async function eN(e,t,n){let r=await $(cy(e,t),{signal:n});if(!r.ok){let o=await r.json().catch(()=>null);throw new S(o?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function tN(e,t,n,r){let o=`${de(e)}/files/content?${new URLSearchParams({path:t})}`,s=r?.ifMatch?{"If-Match":r.ifMatch}:{},i=r?.onProgress,a=globalThis.XMLHttpRequest;if(i&&a){let d=n instanceof Blob?n:new Blob([n]);return ak(a,o,d,s,i,r?.signal)}let l=u(await c.putRaw(o,n,{signal:r?.signal,headers:s}),"Failed to upload file"),p=n instanceof Blob?n.size:n.byteLength;return i?.(p,p),l}async function ak(e,t,n,r,o,s){let i=`${ue(C().backendUrl)}${t}`,{headers:a,rejected:l}=await vt(i,{"Content-Type":"application/octet-stream",...r});return new Promise((p,d)=>{let g=new e,m=()=>new S("Request aborted",{name:"AbortError",code:"ABORTED"});if(s?.aborted)return d(m());let f=()=>g.abort();s?.addEventListener("abort",f,{once:!0});let _=()=>s?.removeEventListener("abort",f);g.open("PUT",i),a.forEach((y,k)=>g.setRequestHeader(k,y)),g.upload.onprogress=y=>o(y.loaded,n.size),g.onload=()=>{_();let y=null;try{y=g.responseText?JSON.parse(g.responseText):null}catch{y=null}if(g.status>=200&&g.status<300)return p(y);g.status===401&&l(),d(new S(y?.message||"Failed to upload file",{status:g.status,code:y?.code,url:i}))},g.onerror=()=>{_(),d(new S("Network error while uploading",{name:"TypeError",url:i}))},g.onabort=()=>{_(),d(m())},g.send(n)})}async function nN(e,t){return u(await c.post(`${de(e)}/files/mkdir`,{path:t},{showErrors:!1}),"Failed to create folder")}async function rN(e,t,n){return u(await c.post(`${de(e)}/files/move`,{from:t,to:n},{showErrors:!1}),"Failed to move")}async function oN(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await c.delete(`${de(e)}/files?${new URLSearchParams(r)}`,{showErrors:!1}),"Failed to delete")}async function sN(e){return u(await c.get(`${de(e)}/versions`),"Failed to load versions").versions}async function iN(e,t){u(await c.post(`${de(e)}/restore`,{versionId:t}),"Failed to restore version")}var ck=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function aN(e,t){return(await lk(e,t)).drives}async function lk(e,t){return u(await c.get(ck(e,t)),"Failed to load session files")}function et(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}var tt={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function nt(){let e=et("BACKEND_URL")||C().backendUrl;return e||"http://localhost:8008/v1"}function Ne(e){let t=ue(e);return t.endsWith("/v1")?t:`${t}/v1`}function gn(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=gn(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return gn(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function uk(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 Hr(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"platinum",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${nt()}/p/${n.external_id}/${tt.KORTIX_MASTER}`:""),status:uk(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 Ws(){let e=await Rt(),t=[];for(let n of e){let r=await Dt(n.project_id).catch(()=>[]);for(let o of r)t.push({project:n,session:o,runtime:null,sandbox:Hr(n,o,null)})}return t.sort((n,r)=>{let o={active:0,provisioning:1,stopped:2,error:3},s=(o[n.sandbox.status]??99)-(o[r.sandbox.status]??99);return s!==0?s:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Hs(e){let t=await c.get(`/sessions/${encodeURIComponent(e)}`,{showErrors:!1});if(t.success&&t.data)return t.data;if(t.error?.status===400||t.error?.status===404)return null;throw t.error??new Error("Session request failed")}async function Vr(e){let t=await Hs(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await mn(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function mn(e){let t=await Ws();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}async function ly(e){return u(await c.post("/notifications/device-token",e))}async function uy(e,t){return u(await c.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}async function py(e,t){let n=C().fetch??((s,i)=>fetch(s,i)),r=Ne(t?.backendUrl??C().backendUrl),o=await n(`${r}/notifications/device-token/release`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({device_token:e}),credentials:"omit",...t?.signal?{signal:t.signal}:{}});if(!o.ok)throw new S(`Device token release failed (HTTP ${o.status})`,{status:o.status,response:o});return{ok:!0}}var wN=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered","message"];async function dy(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return u(await c.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function gy(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await c.post("/notifications/read",t))}var kN={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1},capture_device_down:{push:!0,email:!0},capture_device_recovered:{push:!0,email:!1},message:{push:!0,email:!0}};async function my(){return u(await c.get("/notifications/preferences",{showErrors:!1}))}async function fy(e){return u(await c.put("/notifications/preferences",e))}async function yy(){return u(await c.get("/notifications/web-push/key",{showErrors:!1}))}async function hy(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await c.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function _y(e,t){return u(await c.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function zr(e){return u(await c.get(`/projects/${e}/model-access`))}async function Yr(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}async function Jr(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/custom-providers`)).providers}async function Qr(e,t,n){return u(await c.put(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,n))}var by=e=>e?.status===404;async function Xr(e,t){let n=await c.delete(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,{showErrors:!1});if(!n.success&&!by(n.error))throw n.error??new Error("Failed to delete the custom provider");let r=`CUSTOM_${t.toUpperCase().replace(/-/g,"_")}_API_KEY`;await xr(e,r).catch(o=>{if(!by(o))throw o})}function ON(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:o,previewHasError:s,previewIsLinkOnly:i}=e;return t||n?!1:o?s&&!i:r==="error"}function Vs(e){return typeof e=="string"&&e.trim().length>0}function Py(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Vs(t)||Vs(n)||Vs(r)}function pk(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 Zr(e){if(!e)return!0;let t=pk(e.items);return t?!t.some(Py):!Py(e)}var Te="kortix.transcript.v1",dk=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function Sy(e){return typeof e=="string"&&dk.includes(e)}var LN=["once","always","reject"],jN=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var ky="kortix-v1-import",gk={harness:ky,harness_version:Te,adapter_version:"1"},zs={schema:le,v:1},mk={opencode:"[Tool execution was interrupted]",pi:"No result provided"},fk="[Old tool result content cleared]",yk="The following tool was executed by the user",hk=new Map(Object.entries({bash:"shell",powershell:"shell",read:"read",write:"write",edit:"edit",multiedit:"edit",patch:"patch",apply_patch:"patch",list:"list",ls:"list",glob:"glob",find:"glob",grep:"grep",webfetch:"web_fetch",websearch:"web_search",codesearch:"web_search",todowrite:"todo",todoread:"todo",task:"task",question:"question",plan_enter:"plan",plan_exit:"plan"})),_k=e=>hk.get(e)??(e.includes("_")?"mcp":"other"),bk=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),Pk=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),J=e=>typeof e=="string"?e:void 0,Be=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ro=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,vy=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Ut=e=>Be(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Ft=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function Ys(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,o)=>Ys(r,t[o]));if(!B(e)||!B(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0);return n.length===Object.keys(t).filter(r=>t[r]!==void 0).length&&n.every(r=>Ys(e[r],ro(t,r)))}function to(e,t){if(Ys(e,t))return;if(e===void 0)return{del:!0};if(!B(e)||!B(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let o=to(ro(e,r),ro(t,r));o&&vy(n,r,o)}return{sub:n}}function no(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=B(e)?{...e}:{};for(let[r,o]of Object.entries(t.sub)){let s=no(ro(n,r),o);s===void 0?delete n[r]:vy(n,r,s)}return n}var fn=e=>Object.values(e??{}).find(t=>t.version===Te),oo=(e,t)=>({[e]:{version:Te,...t}}),Ay=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},xy=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),Sk=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),xk=e=>{if(B(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==Te&&B(n.data?.details));return t?t.data.details:{}};function wk(e,t,n){let r=e.result,o=e.input===null||e.input===void 0?{}:{input:e.input},s=Ft(e.started_at)??t.created,i=Ft(e.ended_at)??s,a=r?.exit_code!==void 0?{exit:r.exit_code}:{};if(e.status==="pending")return{status:"pending",input:e.input??{},raw:""};if(e.status==="running")return{status:"running",input:e.input??{},...e.title&&{title:e.title},time:{start:s}};if(e.status==="error")return{status:"error",...o,error:xy(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:s,end:i}};let l=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...Ay(d,t)}]:[]),p=Ft(r?.cleared_at);return{status:"completed",...o,output:xy(r?.content),title:e.title??"",metadata:{...xk(e),...a},time:{start:s,end:i,...p!==void 0&&{compacted:p}},...l.length&&{attachments:l}}}function Ry(e,t){let n=Sk(e,t);switch(e.type){case"text":return{...n,type:"text",text:e.text,...e.synthetic!==void 0&&{synthetic:e.synthetic}};case"reasoning":return{...n,type:"reasoning",text:e.text,time:{start:t.created}};case"attachment":return{...n,type:"file",mime:e.mime,...e.name!==void 0&&{filename:e.name},...Ay(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:wk(e,t,{...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID})};case"step":return e.phase==="start"?{...n,type:"step-start"}:{...n,type:"step-finish",reason:"stop",cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};case"compaction":return{...n,type:"compaction",auto:e.trigger==="auto"||e.trigger==="overflow",...e.trigger==="overflow"&&{overflow:!0},...e.first_kept_message_id!==null&&{tail_start_id:e.first_kept_message_id}};case"harness":return t.fromV1&&(e.harness==="opencode"||e.harness==="pi")?e.data:e.model_visible&&e.fallback_text!==void 0?{...n,type:"text",text:e.fallback_text,synthetic:!0}:void 0;case"subtask":return}}function kk(e){return Sy(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function Cy(e,t,n={}){let r=e.usage,o=e.finish===null?void 0:Pk.get(e.finish);return{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"assistant",time:{created:t.created,...e.completed_at!==null&&{completed:Ft(e.completed_at)}},...e.reply_to&&{parentID:e.reply_to},modelID:e.model?.model??"",providerID:e.model?.provider??"",...e.model?.variant!==void 0&&{variant:e.model.variant},mode:e.agent??"",agent:e.agent??"",path:{cwd:"",root:""},cost:r?.cost??0,tokens:{input:r?.input??0,output:r?.output??0,reasoning:r?.reasoning??0,cache:{read:r?.cache_read??0,write:r?.cache_write??0}},...o&&{finish:o},...e.error&&{error:kk(e.error)},...n}}function Ty(e,t){return e.role==="assistant"?Cy(e,t):{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"user",time:{created:t.created},agent:e.agent??"",model:{providerID:e.model?.provider??"",modelID:e.model?.model??"",...e.model?.variant!==void 0&&{variant:e.model.variant}}}}function Iy(e,t,n){let r=`${e.message_id}-summary`;return{info:Cy({...e,reply_to:e.message_id,agent:"compaction",finish:e.status==="complete"?"stop":null},n,{id:r,summary:!0}),parts:[{id:`${r}-p0`,...n.sessionID!==null&&{sessionID:n.sessionID},messageID:r,type:"text",text:t.summary}]}}function vk(e,t,n){let r=n||e.producer.harness===ky;if(!r&&(e.role==="system"||e.kind==="context"))return[];let o=fn(e.ext)?.data,s=o&&"runtime_session_id"in o?o.runtime_session_id??null:t,i={sessionID:s,messageID:e.message_id,created:Ft(e.created_at),fromV1:r},a=o&&"parts"in o?o.parts:e.blocks.flatMap(d=>{let g=Ry(d,i);return g===void 0?[]:[no(g,fn(d.ext)?.data)]}),l=[{runtime_session_id:s,info:no(Ty(e,i),o?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=no(Iy(e,p,i),o?.summary);l.push({runtime_session_id:s,info:d.info,parts:d.parts})}return l}var Js=e=>Be(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,eo=e=>String(B(e.info)?e.info.id:""),Ey=(e,t)=>Js(e)-Js(t)||(eo(e)<eo(t)?-1:eo(e)>eo(t)?1:0),wy=e=>{let t=fn(e.ext);return t?t.native_id??null:e.thread_id};function so(e){let t=structuredClone(e),n=t.threads.find(i=>i.parent_thread_id===null)??t.threads[0],r=t.threads.flatMap(i=>i.messages.flatMap(a=>vk(a,wy(i),fn(i.ext)!==void 0))),o=fn(t.ext)?.data,s=o&&"root_id"in o?o.root_id??null:n?wy(n):null;return{session_id:t.session_id,root_id:s,rows:r.sort(Ey)}}function Ak(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:B(e.model)?{p:e.model.providerID,m:e.model.modelID,v:e.model.variant}:{},n=J(t.p),r=J(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...J(t.v)!==void 0&&{variant:t.v}}}function Rk(e){if(!B(e.tokens))return null;let t=e.tokens,n=B(t.cache)?t.cache:{};return{input:Be(t.input)??0,output:Be(t.output)??0,cache_read:Be(n.read)??0,cache_write:Be(n.write)??0,...Be(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Be(e.cost)!==void 0&&{cost:e.cost}}}var Ck=e=>({code:J(e.code)||J(e.name)||"UnknownError",message:J(B(e.data)?e.data.message:void 0)??""});function My(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:J(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...J(e.url)!==void 0&&{url:e.url}}}function Tk(e,t,n,r){let o=e.state,s=B(o.time)?o.time:{};B(o.input)||r.tool_input++;let i=B(o.metadata)&&Be(o.metadata.exit)!==void 0?{exit_code:o.metadata.exit}:{},a,l,p=o.input??null;if(o.status==="completed"){let m=(Array.isArray(o.attachments)?o.attachments:[]).filter(B).map(_=>{let{bytes:y,...k}=My(_,n,r);return{type:"attachment",...k}}),f=Ut(s.compacted);a="complete",l={content:[...J(o.output)!==void 0?[{type:"text",text:o.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:fk}],cleared_at:f}}}else if(o.status==="error"){let m=J(o.error);a="error",l={content:m!==void 0?[{type:"text",text:m}]:[],is_error:!0,...m!==void 0&&{error:{message:m}},...i}}else if(n.live)a=o.status==="pending"?"pending":"running",a==="pending"&&J(o.raw)&&!(B(o.input)&&Object.keys(o.input).length)&&(p=o.raw);else{let m=mk[n.h];a="error",l={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=Ut(s.start),g=Ut(s.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:_k(e.tool),input:p,status:a,...l&&{result:l},...J(o.title)&&{title:o.title},...d&&{started_at:d},...g&&{ended_at:g}}}function Ik(e,t,n,r,o,s){let i=(a,l=!1)=>({type:"harness",id:t,harness:o.h,kind:a,data:e,model_visible:l,...l&&{fallback_text:yk}});if(!B(e))return i("unknown");switch(e.type){case"text":return typeof e.text!="string"||e.ignored===!0?i("text"):{type:"text",id:t,text:e.text,...typeof e.synthetic=="boolean"&&{synthetic:e.synthetic}};case"reasoning":return typeof e.text!="string"?i("reasoning"):{type:"reasoning",id:t,text:e.text};case"file":return e.mime==="text/plain"||e.mime==="application/x-directory"?i("file"):{type:"attachment",id:t,...My(e,o,s),...J(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&B(e.state)?Tk(e,t,o,s):i("tool");case"step-start":case"step-finish":return{type:"step",id:t,phase:e.type==="step-start"?"start":"finish"};case"compaction":{if(e!==n)return i("compaction");let a=e.overflow===!0?"overflow":e.auto===!0?"auto":"manual";return{type:"compaction",id:t,summary:r,first_kept_message_id:J(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(J(e.type)||"unknown")}}function Ek(e){let t=e.map((o,s)=>B(o)&&typeof o.id=="string"&&o.id?o.id:`#${s}`),n=new Set(t),r=new Set;return t.map(o=>{if(!r.has(o))return r.add(o),o;let s=2;for(;n.has(`${o}#${s}`);)s++;return n.add(`${o}#${s}`),`${o}#${s}`})}function Mk(e,t,n,r,o,s){let i=B(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],l=i.role==="user"?a.find(w=>B(w)&&w.type==="compaction"):void 0,p=t&&B(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",g=l?p:d==="assistant"?i:void 0,m=g&&B(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",_=g&&B(g.time)?Ut(g.time.completed):null,y=s.live?"streaming":"interrupted",k=g?m?f?"aborted":"error":_?"complete":y:l?y:"complete",R=Ut(B(i.time)?i.time.created:void 0)??"",I=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(w=>B(w)&&w.type==="text"&&typeof w.text=="string"?[w.text]:[]).join(""):null,b={tool_input:0,cut_point:0,attachment:0},M=Ek(a),h=a.map((w,D)=>Ik(w,M[D],l,I,s,b)),x=h.some(w=>w.type==="text"||w.type==="attachment"||w.type==="tool_call"||w.type==="harness"&&w.model_visible),P=!o&&d!=="system"&&(l?k==="complete":!m||f&&x),v=s.live&&P&&k!=="streaming"&&h.some(w=>w.type==="tool_call"&&(w.status==="pending"||w.status==="running"))?"streaming":k,T=o?"superseded":P||!m?void 0:f?"aborted":"failed_attempt";return l&&B(l)&&J(l.tail_start_id)===void 0&&b.cut_point++,{m:{...zs,message_id:J(i.id)??"",thread_id:n,seq:r,role:d,kind:l?"compaction":"turn",status:v,in_context:P,...T&&{hidden_reason:T},agent:J(i.agent)??null,...d==="assistant"&&{reply_to:J(i.parentID)??null},model:Ak(i),usage:g?Rk(g):null,finish:!g||l?null:f?"aborted":m?"error":bk.get(i.finish)??null,error:m?Ck(m):null,created_at:R,completed_at:g||l?_:R||null,producer:gk,blocks:h},lost:b}}function Ok(e,t,n,r,o){let s={};t.runtime_session_id!==r&&(s.runtime_session_id=t.runtime_session_id);let i={sessionID:t.runtime_session_id,messageID:e.message_id,created:Ft(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=to(t.parts[d],Ry(p,i));g&&(p.ext=oo(o,{data:g}))}):s.parts=t.parts;let a=to(t.info,Ty(e,i));a&&(s.info=a);let l=e.blocks.find(p=>p.type==="compaction");if(n&&l){let p=to({info:n.info,parts:n.parts},Iy(e,l,i));p&&(s.summary=p)}Object.keys(s).length&&(e.ext=oo(o,{data:s}))}function Dk(e,t,n){if(t){for(let r of[!0,!1])for(let o of e)if(!(o.runtime_session_id===t||!Array.isArray(o.parts))){for(let s of o.parts)if(!(!B(s)||s.type!=="tool"||!B(s.state))&&(r?B(s.state.metadata)&&s.state.metadata.sessionId===t:n(s.state).includes(t)))return{row:o,part:s}}}}function io(e,t={}){let n={h:t.harness??"opencode",resolve:t.resolveAttachment??(()=>null),counts:{tool_input:0,cut_point:0,attachment:0},live:t.live===!0},r=structuredClone(e.rows).sort(Ey),o=new Map;for(let b of r){let M=o.get(b.runtime_session_id);M?M.push(b):o.set(b.runtime_session_id,[b])}let s=e.root_id,i=o.has(s),a=new Map,l=b=>a.get(b)??(a.set(b,JSON.stringify(b)),a.get(b)),p=new Map;for(let b of o.keys()){let M=i&&b===s?void 0:Dk(r,b,l);M&&p.set(b,M)}let d=[...r].reverse().find(b=>b.runtime_session_id===null||!p.has(b.runtime_session_id)),g=i||!d?s:d.runtime_session_id;o.has(g)||o.set(g,[]);let m=g||e.session_id,f=b=>b!==null&&p.has(b)?b:m,_=Ut(r.map(Js).find(Number.isFinite))??"",y=[];for(let[b,M]of o){if(b!==g&&(b===null||!p.has(b)))continue;let h=b===g,x=h?r.filter(N=>N.runtime_session_id!==g&&f(N.runtime_session_id)===m):[],P=[...x,...M],v=new Set(x),T=new Map,L=new Set;for(let N of P){let z=B(N.info)?N.info:{};if(z.role!=="user"||!Array.isArray(N.parts)||!N.parts.some(K=>B(K)&&K.type==="compaction"))continue;let G=P.find(K=>!L.has(K)&&K.runtime_session_id===N.runtime_session_id&&B(K.info)&&K.info.role==="assistant"&&K.info.summary===!0&&K.info.parentID===z.id);G&&(T.set(N,G),L.add(G))}let w=[];for(let N of P){if(L.has(N))continue;let z=T.get(N),{m:G,lost:K}=Mk(N,z,h?m:b,w.length+1,v.has(N),n);if(Ok(G,N,z,b,n.h),G.in_context)for(let Me of["tool_input","cut_point","attachment"])n.counts[Me]+=K[Me];w.push(G)}let D=b===null?void 0:p.get(b),be=w.find(N=>N.role==="user"&&N.kind==="turn");y.push({...zs,thread_id:h?m:b,parent_thread_id:D?f(D.row.runtime_session_id):null,spawned_by:D&&typeof D.part.callID=="string"?{message_id:J(D.row.info?.id)??"",call_id:D.part.callID}:null,agent:be?.agent??null,title:null,created_at:w[0]?.created_at||_,messages:w,ext:oo(n.h,b===null?{}:{native_id:b})})}y.sort((b,M)=>b.parent_thread_id===null?-1:M.parent_thread_id===null?1:I(b)-I(M));let k=y[0]?.messages.filter(b=>b.role==="user"&&b.kind==="turn").at(-1),R=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...zs,session_id:e.session_id,title:null,created_at:_,restore_grade:R?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:k?.agent??null,model:k?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:y,...g!==s&&{ext:oo(n.h,{data:{root_id:s}})}};function I(b){return r.findIndex(M=>M.runtime_session_id===b.thread_id)}}var Qs={schema:le,v:1},Lk=Object.freeze({}),Oy=new WeakMap;function ao(e){let t=Oy.get(e);if(t&&t.state===e.state)return t.block;let n=e.sessionID??null,r={id:e.messageID,sessionID:e.sessionID,role:"assistant"},s=io({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return Oy.set(e,{state:e.state,block:s}),s}var Xs=new WeakMap;function Zs(e){if(Xs.has(e))return Xs.get(e);let t={...Qs,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:Te}},messages:[{...Qs,message_id:"",thread_id:"",seq:1,role:"assistant",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:"",completed_at:null,producer:{harness:"",harness_version:"",adapter_version:""},blocks:[e]}]},{rows:n}=so({...Qs,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[t]}),r=n[0].parts[0];return Xs.set(e,r),r}function oe(e){return Zs(e)}var ge=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",Ke=e=>ge(e)?oe(e):e;function jk(e){let t=oe(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:Lk}var Ly=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function $k(e){return e.status==="complete"?"completed":e.status}var Dy=new WeakMap;function Uk(e){if(e.status!=="complete")return"";let t=Dy.get(e);return t===void 0&&Dy.set(e,t=Ly(e)),t}function Fk(e){return e.status==="error"?e.result?.error?.message||Ly(e):void 0}function ye(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function VN(e){return ye(e)==="bash"}function jy(e){let t=ye(e);return t==="question"||t==="ask"}function zN(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Nk=new Set(["show","show_user"]);function $y(e){return Nk.has(ye(e))}function YN(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Uy(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||ei(e))}function ei(e){let t=ge(e)?oe(e):e,n=ye(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:Zr(t.state?.input)}var Bk=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Fy(e){return Bk.has(ye(e))}var Kk=50*1024*1024,ti="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",qk=new RegExp(`^kortix-attachment://(${ti})/(${ti})/(${ti})$`);function ri(e){if(typeof e!="string")return null;let t=qk.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function nB(e){return ri(e)!==null}var ni=new WeakMap;async function Ny(e,t,n,r={}){if(n.size>Kk)throw new Error("Attachments must be 50 MiB or smaller.");let o=`${e}/${t}`,s=r.attachmentId?void 0:ni.get(n)?.get(o);if(s?.promise)return s.promise;let i=s??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let l=ni.get(n)??new Map;l.set(o,i),ni.set(n,l)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=c.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(l=>{throw i.promise=void 0,l}),i.promise}async function By(e,t){let n=ri(e);if(!n)throw new Error("Invalid attachment reference");let r=C().backendUrl.replace(/\/$/,""),o=await $(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!o.ok)throw new S("Could not load attachment",{status:o.status});return o.blob()}var Gk=new Set(["show","show_user"]);function Wk(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let o=r+5;if(o>=e.length||!/\s/.test(e[o])){n=o;continue}let s=e.indexOf(">",o);if(s===-1)return t;let i=e.indexOf("</file>",s+1);if(i===-1)return t;t.push(e.slice(o,s).trimStart()),n=i+7}}var qe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),yn=e=>typeof e=="string"&&e.length>0?e:null,Ky=e=>typeof e=="string"?yn(e.split("/").pop()):null;function co(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 Hk(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 Vk(e){let t=e.blocks.filter(qe).map(n=>n.type==="attachment"?{type:"file",url:n.ref??n.url,filename:n.name,mime:n.mime}:n.type==="tool_call"?{type:"tool",tool:n.name,state:{input:n.input}}:n.type==="harness"&&qe(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function zk(e,t){for(let n of Wk(e))t(co(n,"attachment"),co(n,"filename")??Ky(co(n,"path")),co(n,"mime"))}function Yk(e,t){for(let n of[e,...Hk(e.items)])qe(n)&&t(n.attachment,Ky(n.path),null)}function rB(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let o=qe(r)&&Array.isArray(r.blocks)?Vk(r):r;if(!qe(o)||!qe(o.info)||!Array.isArray(o.parts))continue;let s=yn(o.info.id);if(!s)continue;let i=yn(o.info.role)??"unknown",a=(l,p,d)=>{let g=ri(l);!g||n.has(l)||(n.add(l),t.push({url:l,attachment_id:g.attachmentId,filename:p,mime:d,message_id:s,role:i}))};for(let l of o.parts)qe(l)&&(l.type==="file"?a(l.url,yn(l.filename),yn(l.mime)):l.type==="text"&&typeof l.text=="string"?zk(l.text,a):l.type==="tool"&&typeof l.tool=="string"&&Gk.has(ye(l.tool))&&qe(l.state)&&qe(l.state.input)&&Yk(l.state.input,a))}return t}function Jk(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 aB(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 oi(e,t,n){return e!==void 0?e:Jk(et(t),n)}var qy={get disableMobileAdvertising(){return oi(C().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return oi(C().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return oi(C().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var Qk=new Set(["project-manager"]);function si(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:qy.enableProjects||!Qk.has(e.name)}function uB(e){let t=e.agents.filter(si),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function Gy(){return{projects:{list:Rt,listForAccount:Ec,get:Ct,detail:hr,create:Lc,createRepo:jc,provision:$c,update:Pr,archive:Sr,llmCatalog:_r,modelPicker:br,modelAccess:zr,setModelAccess:Yr,customLlmProviders:Jr,setCustomLlmProvider:Qr,deleteCustomLlmProvider:Xr,sandboxHealth:vr,sandboxTemplates:Iu,sessions:Dt,createSession:Lt},github:{linkRepository:Gc,replaceProjectRepository:Wc,getInstallation:Hc,listInstallations:Vc,listLinkableInstallations:zc,listRepositories:Yc,listRepositoryBranches:Jc,linkInstallation:Xc,saveInstallation:Qc,deleteInstallation:el,storeUserToken:Zc},gitBackend:{get:tl,repositories:nl},connectStatus:xu,marketplace:{items:s=>Pf(s),item:s=>wf(s),itemFile:(s,i)=>kf(s,i),marketplaces:()=>Sf(),featured:()=>xf(),sources:{list:()=>vf(),add:s=>Af(s),remove:s=>Rf(s)}}}}function Wy(){return{billing:{accountState:Kd,accountStateMinimal:qd,transactions:Gd,transactionsSummary:Wd,creditBreakdown:Hd,usageHistory:Vd,usageRollup:ug,sessionCosts:{list:dg,get:Wr},tierConfigurations:zd,setPlan:ag,previewPlan:ig,acceptEnterpriseOffer:cg,contactSales:lg,checkout:{createSession:n=>Yd(n),confirmSession:(n,r)=>Jd(n,r)},subscription:{createPortalSession:(n,r)=>Qd(n,r),cancel:(n,r)=>Xd(n,r),reactivate:n=>Zd(n),scheduleDowngrade:(n,r,o)=>eg(n,r,o),cancelScheduledChange:n=>tg(n),prorationPreview:(n,r)=>ng(n,r)},credits:{purchase:n=>rg(n),autoTopupSettings:n=>og(n),configureAutoTopup:n=>sg(n)}},sandboxShares:{list:Om,create:Dm,revoke:Lm}}}var hn=class extends Error{constructor(n,r,o){super(r);this.code=n;this.status=o;this.name="HeadlessAuthError"}code;status};async function se(e,t,n){let r=n?.fetch??C().fetch??((p,d)=>fetch(p,d)),o=ue(n?.backendUrl??C().backendUrl??"");if(!o)throw new hn("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let s={accept:"application/json"};t.body!==void 0&&(s["content-type"]="application/json"),t.bearer&&(s.authorization=`Bearer ${t.bearer}`);let i=await r(`${Ne(o)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:s,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),l=null;try{l=a?JSON.parse(a):null}catch{l=a}if(!i.ok){let p=l&&typeof l=="object"?l:{};throw new hn(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return l}function ii(e,t){return se("/auth/signup",{body:e},t)}function ai(e,t){return se("/auth/sign-in/password",{body:e},t)}function ci(e,t){return se("/auth/sign-in/magic-link",{body:e},t)}function li(e,t){return se("/auth/verify-otp",{body:e},t)}function ui(e,t){return se("/auth/sign-in/oauth",{body:e},t)}function pi(e,t){return se("/auth/oauth/exchange",{body:e},t)}function _n(e,t){return se("/auth/refresh",{body:e},t)}function di(e,t){return se("/auth/password/reset",{body:e},t)}function gi(e,t,n){return se("/auth/password/update",{body:e,bearer:t},n)}function mi(e,t){return se("/auth/user",{bearer:e},t)}function fi(e,t,n){return se("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function yi(e,t){return se("/auth/sign-in/sso",{body:e},t)}var hi={enroll:(e,t,n)=>se("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>se(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>se(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>se(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function _i(e,t={},n){return se("/auth/sign-out",{body:t,bearer:e},n)}function bi(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,o=null,s=!e.storage,i=null,a=null,l=0,p=new Set,d=y=>(y.expires_at??0)*1e3,g=y=>d(y)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:o})):await e.storage.remove());for(let y of[...p])try{y(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(s)return r;if(!i){let y=l,k=(async()=>{let R=await e.storage.get();if(y===l&&R)try{let I=JSON.parse(R);I.session?.access_token&&I.session?.refresh_token&&(r=I.session,o=I.user??null)}catch{r=null}return s=!0,r})();i=k,k.then(()=>{i===k&&(i=null)},()=>{i===k&&(i=null)})}return i}async function _(){if(await f(),!r)return null;if(!a){let y=r.refresh_token,k=l,R=_n({refresh_token:y},e.request).then(async I=>(k!==l||(r=I.session,I.user&&(o=I.user),await m()),r)).catch(async I=>{if(k!==l)return r;let b=I&&typeof I=="object"&&"status"in I?I.status:0;if(b>=400&&b<500)return r=null,o=null,await m(),null;throw I}).finally(()=>{a===R&&(a=null)});a=R}return a}return{subscribe(y){return p.add(y),()=>{p.delete(y)}},current:()=>r,user:()=>o,load:f,async set(y,k){await f(),l+=1,a=null,r=y,k!==void 0&&(o=k),y||(o=null),await m()},async getToken(){return await f(),r?g(r)?(await _().catch(()=>r))?.access_token??null:r.access_token:null},refresh:_,async clear(){l+=1,a=null,r=null,o=null,s=!0,await m()}}}function Hy(){return{list:cc,get:uc,create:lc,secretResources:{list:Ol,create:Dl,rotate:Ll,retry:jl,remove:$l,grant:Ul,revoke:Fl,setAccess:Nl},updateName:pc,branding:{get:dc,update:gc,uploadAsset:mc,removeAsset:fc,reset:yc},leave:Cc,members:hc,invite:_c,removeMember:Ac,updateMemberRole:Rc,invites:bc,cancelInvite:Pc,resendInvite:Sc,tokens:{list:nf,create:rf,revoke:of},connectedApps:{list:sf,revoke:af},audit:{log:pf,export:gf,webhooks:{list:mf,create:ff,update:yf,remove:hf}}}}function Vy(){return{assignments:{list:xm,create:wm,revoke:km},permissions:{list:vm,forRole:cm},roles:{list:sm,create:um,update:pm,setPermissions:dm,remove:gm,usage:lm},groups:{list:Qg,get:Xg,create:Zg,update:em,remove:tm,members:{list:nm,add:rm,remove:om}},agentIdentities:im,oauthClients:{list:ym,get:hm,create:_m,update:bm,rotateSecret:Pm,remove:Sm},can:mm,canBatch:fm}}function zy(){let e={signUp:ii,signInWithPassword:ai,sendMagicLink:ci,verifyOtp:li,signInWithProvider:ui,exchangeCode:pi,refresh:_n,resetPassword:di,updatePassword:gi,updateUserMetadata:fi,signInWithSso:yi,mfa:hi,user:mi,signOut:_i,session:bi},t=Hy(),n=Vy();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:xc,describe:wc,accept:ls,acceptAndLand:kc,decline:vc}}}var bn=new Map,Pi=new Map;function Si(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Yy(e){return bn.get(Si(e))??null}function Jy(){return[...bn.values()].filter(e=>typeof e=="string")}function Qy(e){return bn.has(Si(e))}async function ft(e){let t=Si(e),n=bn.get(t);if(n!==void 0)return n;let r=Pi.get(t);if(r)return r;let o=(async()=>{try{let s=await c.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!s.success)return null;let i=typeof s.data?.preview_url_template=="string"?s.data.preview_url_template:null;return bn.set(t,i),i}catch{return null}finally{Pi.delete(t)}})();return Pi.set(t,o),o}function Xy(e){let{apiBaseUrl:t}=e;return Qy(t)||ft(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:Yy(t)}}function Zy(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new S(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let o=C().backendUrl??e.backendUrl,s=80,i=t(o);return i&&(s=i.port?Number(i.port):i.protocol==="https:"?443:80),Xy({sandboxId:r,apiBaseUrl:o,backendPort:s})}}function eh(e,t){let n=null;async function r(){n||(n=Or(e,t,{showErrors:!1}).then(o=>{let s=Fr(o)??"",i=s.indexOf("/"),a=i>0&&i<s.length-1?{providerID:s.slice(0,i),modelID:s.slice(i+1)}:void 0,l=o.agent_name?.trim()||void 0;return{model:a,agent:l}}));try{return await n}catch(o){throw n=null,o}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var Nt={url:null,sandboxId:null,dbSandboxId:null,version:0},Zk=new Set;function lo(e,t=null,n=null){if(!(Nt.url===e&&Nt.sandboxId===t&&Nt.dbSandboxId===n)){Nt={url:e,sandboxId:t,dbSandboxId:n,version:Nt.version+1};for(let r of Zk)r()}}function th(){return Nt.url}var Pn=new Map;function nh(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let o=n?.evidence?.error;return o&&o!==n?.message&&r.push(o),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Bt=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function rh(e,t){async function n(r){let o=Date.now()+r,s=()=>Math.max(0,o-Date.now()),i=await mt(e,t,Math.min(3e4,s()));for(;Date.now()<o&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,s()))),i=await mt(e,t,Math.min(3e4,s()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new S(nh(i),{code:"RUNTIME_UNAVAILABLE"});let l=i.sandbox.external_id;if(!l)throw new S("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Fe(l);return lo(p,l),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:l}}return n}function oh(e,t,n){let r=null;function o(){if(r)return r;let p=vd(e,t);return p&&(r=p),r}let s=rh(e,t);async function i(p){let d=o();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=ft(C().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?Cd(p.session):null,_=f?.sandbox?.external_id,y=f?.runtime_session_id;if(_&&y){let b=Fe(_);return lo(b,_),r={runtimeSessionId:y,opencodeSessionId:y,runtimeUrl:b,sandboxId:_},Nr(e,t,r),await m,r}let k=`${e}
|
|
15
|
-
${t}`,
|
|
13
|
+
`);let h=Nw(f);if(h){if(r(h),h.type==="error")throw new P(h.error,{status:h.status,code:h.code,data:{reason:h.reason}});h.type==="done"&&(p=h.result)}}}}finally{i.cancel().catch(()=>{})}if(!p)throw new Error("Reload stream ended without a result");return p}async function id(e,t){return u(await c.get(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`))}async function ad(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/scope`,n))}async function cd(e,t,n){return u(await c.put(`/projects/${e}/sessions/${encodeURIComponent(t)}/model`,{model:n,opencode_model:n}))}function Nr(e){let t=e.metadata?.opencode_model;return typeof t=="string"&&t.trim()?t.trim():null}async function ld(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/message-authors`,{showErrors:!1}))}async function ud(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/model-usage`,{showErrors:!1}))}function cL(e,t){let n=e.author_user_id===void 0||!t.userId||e.author_user_id===t.userId;return{own:n,removable:n||t.managesSession===!0}}async function pd(e){return u(await c.get(`/projects/${e}/triggers`))}async function dd(e,t){return u(await c.post(`/projects/${e}/triggers`,t))}async function gd(e,t,n){return u(await c.patch(`/projects/${e}/triggers/${t}`,n))}async function md(e,t){return u(await c.delete(`/projects/${e}/triggers/${t}`))}async function dL(e){return u(await c.get(`/accounts/${e}/automations`))}async function gL(e,t){return u(await c.patch(`/accounts/${e}/automations`,{paused:t},{showErrors:!1}))}async function fd(e,t){return u(await c.patch(`/projects/${e}/triggers/activation`,{paused:t}))}function yd(e){let t=new URLSearchParams;e?.status&&t.set("status",e.status),e?.limit!=null&&t.set("limit",String(e.limit)),e?.cursor&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}async function hd(e,t,n){let r={};return n?.payload!==void 0&&(r.payload=n.payload),n?.dryRun!==void 0&&(r.dry_run=n.dryRun),u(await c.post(`/projects/${e}/triggers/${t}/fire`,r))}async function _d(e,t,n){return u(await c.get(`/projects/${e}/triggers/${t}/runs${yd(n)}`))}async function bd(e,t){return u(await c.get(`/projects/${e}/trigger-runs${yd(t)}`))}async function Sd(e,t,n,r){return u(await c.post(`/projects/${e}/triggers/${t}/runs/${n}/replay`,r?.confirmUnverified?{confirm_unverified:!0}:{}))}async function xd(e,t){let n="connector"in t?`connector=${encodeURIComponent(t.connector)}`:`app=${encodeURIComponent(t.app)}${t.source?`&source=${encodeURIComponent(t.source)}`:""}`;return u(await c.get(`/projects/${e}/triggers/event-types?${n}`))}async function Pd(e){return u(await c.get(`/projects/${e}/triggers/event-apps`))}var Xe=new Map;function To(e,t){return`${e}::${t}`}function wd(e,t){Xe.delete(e),Xe.set(e,t)}function kd(e,t){let n=To(e,t),r=Xe.get(n);return r&&wd(n,r),r}function Br(e,t,n){let r=To(e,t);if(!Xe.has(r)&&Xe.size>=512){let s=Xe.keys().next().value;s!==void 0&&Xe.delete(s)}wd(r,n)}function vd(e,t){Xe.delete(To(e,t))}function Bw(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function dn(){return Bw(I().backendUrl||"http://localhost:8008/v1")}function Ad(){let e=I().sandboxId;return e?`${dn()}/p/${e}/8000`:""}function Kw(e,t=8e3){return`${dn()}/p/${e}/${t}`}function Fe(e,t=8e3){return Kw(e,t)}function Rd(e){if(e.status!=="running"||!e.sandbox_id||!e.sandbox_provider||!e.sandbox_url||!(e.runtime_session_id??e.opencode_session_id))return null;let t=e.runtime_session_id??e.opencode_session_id,n=e.sandbox_url.match(/\/p\/([^/]+)\//)?.[1];return n?{stage:"ready",agent_name:e.agent_name??"default",retriable:!0,sandbox:{sandbox_id:e.sandbox_id,session_id:e.session_id,project_id:e.project_id,account_id:e.account_id,provider:e.sandbox_provider,external_id:n,base_url:e.sandbox_url,status:"active",config:{},metadata:e.metadata,last_used_at:e.updated_at,created_at:e.created_at,updated_at:e.updated_at},runtime_session_id:t,opencode_session_id:t,runtime_url:e.sandbox_url}:null}var Io=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 PL(e){return e instanceof Error&&e.name==="SessionStartError"}function qw(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 Io(s,{status:n,code:r,terminal:!0}):null}function Cd(e,t,n){let r=typeof n=="number"?n:n?.waitMs,s=typeof n=="number"?void 0:n?.repositoryMode,o=new URLSearchParams;r&&r>0&&o.set("wait_ms",String(Math.floor(r))),s&&o.set("repository_mode",s),typeof n=="object"&&n?.keepStopped&&o.set("keep_stopped","1"),typeof n=="object"&&n?.intentAgeMs&&n.intentAgeMs>0&&o.set("intent_age_ms",String(Math.floor(n.intentAgeMs)));let i=o.size>0?`?${o.toString()}`:"";return c.post(`/projects/${e}/sessions/${t}/start${i}`,{},{showErrors:!1})}async function mt(e,t,n){let r=await Cd(e,t,n);if(!r.success||!r.data){let s=qw(r.error);if(s&&!(s.status===404&&gp(t)))throw s;return null}return Id(e,t,r.data)}async function Td(e,t,n){let r=await Cd(e,t,n);if(!r.success||!r.data)throw r.error??new Error("Unable to start this session");return Id(e,t,r.data)}function Id(e,t,n){let r=n.sandbox?.external_id,s=n.runtime_session_id??n.opencode_session_id;return n.stage==="ready"&&r&&s&&Br(e,t,{runtimeSessionId:s,opencodeSessionId:s,runtimeUrl:Fe(r),sandboxId:r}),n}function wL(e,t){return["session-start",e,t]}async function Ed(e){return u(await c.get(`/projects/${e}/model-defaults`))}async function Md(e,t){return u(await c.put(`/projects/${e}/model-defaults`,t))}async function Od(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 IL(e,t){return u(await c.put(`/projects/${e}/model-enablement`,{modelOverrides:t}))}function Dd(e){let t=[];for(let n of e){let r=n.trim();r&&!t.includes(r)&&t.push(r)}return t}function Gw(e,t){if(e.length!==t.length)return!1;let n=new Set(t);return e.every(r=>n.has(r))}function Kr(e){let t=e.connectors_required?Dd(e.connectors_required):void 0,n=e.connectors_personal?Dd(e.connectors_personal):void 0;if(t&&n&&!Gw(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 jd(e,t,n){let r=Kr(n);return u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/scope`,r))}async function NL(e,t){let n=u(await c.get(`/projects/${e}/agents/${encodeURIComponent(t)}/config`));return{...n,block:n.block?Eo(n.block):null}}async function BL(e,t,n){let r=Eo(n,!0),s=u(await c.put(`/projects/${e}/agents/${encodeURIComponent(t)}/config`,r));return{...s,block:s.block?Eo(s.block):null}}function Eo(e,t=!1){let n=Kr(e);if(n.workspace===void 0)return n;let r=n.workspace==="branch";if(n.repository_access!==void 0&&n.repository_access!==r)throw new Error("repository_access conflicts with workspace");if(t&&n.workspace==="read"&&n.repository_access===void 0)throw new Error("Legacy read is unavailable. Set repository_access explicitly.");return n.repository_access??=r,delete n.workspace,n}async function KL(e,t,n){return u(await c.post(`/projects/${e}/secrets/${encodeURIComponent(t)}/grant`,{agent:n}))}async function Ld(e,t){return u(await c.put(`/projects/${e}/default-agent`,{agent:t}))}var qr="Use setBillingPlan().",$d="Change the plan with setBillingPlan(); manage the card in the Stripe customer portal (createPortalSession()).";function Ud(){return{credits:{total:0,daily:0,monthly:0,extra:0,can_run:!1,daily_refresh:null},subscription:{tier_key:"none",tier_display_name:"No Plan",monthly_usd:null,status:"no_subscription",billing_period:null,provider:"stripe",subscription_id:null,current_period_end:null,cancel_at_period_end:!1,is_cancelled:!1,cancellation_effective_date:null,has_scheduled_change:!1,scheduled_change:null,commitment:{has_commitment:!1,can_cancel:!0,commitment_type:null,months_remaining:null,commitment_end_date:null},can_purchase_credits:!1},models:[],limits:{concurrent_runs:{running_count:0,limit:0,can_start:!1,tier_name:"none"},ai_worker_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"},custom_mcp_count:{current_count:0,limit:0,can_create:!1,tier_name:"none"}},tier:{name:"none",display_name:"No Plan",monthly_credits:0,can_purchase_credits:!1}}}function Ww(e){let t=e.trim().toLowerCase();return t===""||t==="free"||t==="none"?"free":t==="enterprise"?"enterprise":"credits"}function VL(e){let t=e?.plan;if(t)return{family:t.family,label:t.label,sublabel:t.sublabel??null,monthlyUsd:t.monthly_usd??null};let n=e??Ud(),r=(n.subscription?.tier_key||n.tier?.name||"none").toString(),s=(n.tier?.display_name||"").trim()||r;return{family:Ww(r),label:s,sublabel:null,monthlyUsd:null}}function Hw(e){return!!e&&e.can_manage_billing!==!1}function zL(e){return e?.subscription?.can_purchase_credits===!0&&Hw(e)}async function Fd(e){let t=await c.get(e,{showErrors:!1}),n=t.error?.status===404&&/billing is not enabled/i.test(t.error.message||"");if(t.error&&t.error.status!==401&&!n)throw t.error;return t.error?Ud():t.data}function Nd(e){let t=new URLSearchParams;e?.skipCache&&t.set("skip_cache","true"),e?.accountId&&t.set("account_id",e.accountId);let n=t.toString();return n?`?${n}`:""}async function Bd(e){return Fd(`/billing/account-state${Nd(e)}`)}async function Kd(e){return Fd(`/billing/account-state/minimal${Nd(e)}`)}async function qd(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 Gd(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 Wd(){return u(await c.get("/billing/credit-breakdown"))}async function Hd(e){let t=e!=null?`?days=${e}`:"";return u(await c.get(`/billing/usage-history${t}`))}async function Vd(){return u(await c.get("/billing/tier-configurations"))}async function YL(e){let t=e.accountId?`?account_id=${encodeURIComponent(e.accountId)}`:"";return At(e,`/v1/billing/account-state${t}`)}async function zd(e){throw N("createCheckoutSession",qr)}async function Yd(e,t){throw N("confirmCheckoutSession",qr)}async function Jd(e,t){return u(await c.post("/billing/create-portal-session",{account_id:t,return_url:e}),"Failed to create portal session")}async function Qd(e,t){return u(await c.post("/billing/cancel-subscription",{account_id:t,feedback:e}),"Failed to cancel subscription")}async function Xd(e){return u(await c.post("/billing/reactivate-subscription",{account_id:e}),"Failed to reactivate subscription")}async function Zd(e,t,n){throw N("scheduleDowngrade","Change the plan in the Stripe customer portal (createPortalSession()).")}async function eg(e){throw N("cancelScheduledChange",$d)}async function tg(e,t){throw N("getProrationPreview",$d)}async function ng(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 rg(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 JL(e){return u(await c.post(`/accounts/${encodeURIComponent(e)}/top-up-requests`,{}),"Failed to ask the owners for credits")}async function sg(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 QL(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 og(e){return u(await c.post("/billing/plan/preview",{monthly_usd:e.monthlyUsd,account_id:e.accountId}),"Failed to preview the plan change")}async function ig(e){return u(await c.post("/billing/plan",{monthly_usd:e.monthlyUsd,success_url:e.successUrl,cancel_url:e.cancelUrl,locale:e.locale,account_id:e.accountId}),"Failed to set billing plan")}async function ag(e){return u(await c.post("/billing/enterprise-offer/checkout",{success_url:e.successUrl,cancel_url:e.cancelUrl,account_id:e.accountId}),"Failed to start the Enterprise checkout")}async function cg(e={}){return u(await c.post("/billing/enterprise/contact",{account_id:e.accountId,...e.note?{note:e.note}:{}}),"Failed to reach Kortix sales")}async function XL(e){throw N("createPerSeatCheckout",qr)}async function ZL(e){throw N("claimPerSeatBilling",qr)}async function e$(e){return u(await c.post("/billing/sync-subscription",{account_id:e}),"Failed to sync subscription")}async function lg(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 Mo(e,t){t.accountId&&e.set("account_id",t.accountId),t.projectId&&e.set("project_id",t.projectId)}function Gr(e,t){t.from&&e.set("from",t.from),t.to&&e.set("to",t.to)}function Wr(e){return e.size>0?`?${e}`:""}async function pg(e={}){let t=new URLSearchParams;return Mo(t,e),e.ownerId&&t.set("owner_id",e.ownerId),Gr(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/session-costs${Wr(t)}`))}async function Hr(e,t={}){let n=new URLSearchParams;return Mo(n,t),u(await c.get(`/usage/session-costs/${encodeURIComponent(e)}${Wr(n)}`))}async function i$(e={}){let t=new URLSearchParams;return e.accountId&&t.set("account_id",e.accountId),Gr(t,e),e.sort&&t.set("sort",e.sort),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),u(await c.get(`/usage/cost-by-project${Wr(t)}`))}async function a$(e={}){let t=new URLSearchParams;return Mo(t,e),e.sessionId&&t.set("session_id",e.sessionId),Gr(t,e),u(await c.get(`/usage/cost-summary${Wr(t)}`))}function ug(e,t={}){let n=new URLSearchParams;if(t.accountId&&n.set("account_id",t.accountId),t.projectId&&n.set("project_id",t.projectId),e==="sessions"){let s=t;s.ownerId&&n.set("owner_id",s.ownerId)}Gr(n,t),t.sort&&n.set("sort",t.sort),n.set("format","csv");let r=e==="projects"?"/usage/cost-by-project":"/usage/session-costs";return`${I().backendUrl||""}${r}?${n}`}async function c$(e,t={}){let n=ug(e==="projects"?"projects":"sessions",t),r=await Oe(n,{method:"GET"},{timeoutMs:10*6e4},"Failed to export CSV"),s=r.headers.get("x-kortix-row-cap"),o=s!=null?Number(s):NaN;return{blob:await r.blob(),rowCap:Number.isFinite(o)?o:null}}async function dg(e,t){return u(await c.post(`/channels/${e}/identity/bind`,{token:t}),"Failed to connect your account")}function d$(e){return dg("slack",e)}function g$(e){return dg("teams",e)}async function gg(e,t){return u(await c.post(`/channels/${e}/identity/preview`,{token:t},{showErrors:!1}),"This link is invalid or has expired")}function m$(e){return gg("slack",e)}function f$(e){return gg("teams",e)}async function mg(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/installation`,{showErrors:!1});return t.success?t.data??null:null}async function fg(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/slack/connect`,t,{showErrors:!1}),"Failed to connect")}var Vw={oauth_available:!1,install_url:null};async function yg(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/slack/mode`,{showErrors:!1});return!t.success||!t.data?Vw:t.data}async function hg(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 _g(e,t){return hg("slack",e,t)}function bg(e,t){return hg("teams",e,t)}async function Sg(e){return u(await c.get(`/webhooks/slack/${encodeURIComponent(e)}/manifest`,{showErrors:!1}),"Failed to load Slack manifest")}async function xg(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 y$(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/telegram/installation`,{showErrors:!1});return t.success?t.data??null:null}async function h$(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/channels/telegram/connect`,t,{showErrors:!1}),"Failed to connect Telegram")}async function _$(e,t){return u(await c.put(`/projects/${encodeURIComponent(e)}/channels/telegram/allowed-users`,{user_ids:t},{showErrors:!1}),"Failed to update allowed Telegram users")}async function b$(e){let t=await c.delete(`/projects/${encodeURIComponent(e)}/channels/telegram`,{showErrors:!1});if(!t.success)throw new Error(t.error?.message??"Failed to disconnect Telegram")}async function Pg(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 wg(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 Oo(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 zw={provider:"agentmail",managed_available:!1};async function kg(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?Oo(r.data):null}async function vg(e){let t=await c.get(`/projects/${encodeURIComponent(e)}/channels/email/mode`,{showErrors:!1});return!t.success||!t.data?zw:t.data}async function Ag(e,t){let n=u(await c.post(`/projects/${encodeURIComponent(e)}/channels/email/connect`,t,{showErrors:!1}),"Failed to connect email");return Oo(n)}async function Rg(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 Cg(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 Oo(r)}async function S$(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/channels/bindings`,{showErrors:!1}),"Failed to load channel bindings")}async function x$(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 Tg(e){return u(await c.get(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Ig(e,t){return u(await c.put(`/projects/${e}/gateway/routing-policy`,t),"Gateway routing policy request failed")}async function Eg(e){return u(await c.delete(`/projects/${e}/gateway/routing-policy`),"Gateway routing policy request failed")}async function Mg(e,t){return u(await c.post(`/projects/${e}/gateway/routing-policy/preview`,t),"Gateway route preview failed")}async function Og(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 Dg(e,t){return u(await c.get(`/projects/${e}/gateway/logs/${t}`),"Gateway request failed")}async function jg(e,t){return u(await c.get(`/projects/${e}/gateway/overview${t?`?days=${t}`:""}`),"Gateway request failed")}async function Lg(e,t){return u(await c.get(`/projects/${e}/gateway/series${t?`?days=${t}`:""}`),"Gateway request failed")}async function $g(e,t){return u(await c.get(`/projects/${e}/gateway/breakdown${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ug(e,t){return u(await c.get(`/projects/${e}/gateway/sessions${t?`?days=${t}`:""}`),"Gateway request failed")}async function Fg(e,t){return u(await c.get(`/projects/${e}/gateway/errors${t?`?days=${t}`:""}`),"Gateway request failed")}async function Ng(e){return u(await c.get(`/projects/${e}/gateway/budgets`),"Gateway request failed")}async function Bg(e,t){return u(await c.put(`/projects/${e}/gateway/budgets`,t),"Gateway request failed")}async function Kg(e,t){return u(await c.delete(`/projects/${e}/gateway/budgets/${t}`),"Gateway request failed")}async function qg(e){return u(await c.get(`/projects/${e}/gateway/keys`),"Gateway request failed")}async function Gg(e,t){return u(await c.post(`/projects/${e}/gateway/keys`,{name:t}),"Gateway request failed")}async function Wg(e,t){return u(await c.delete(`/projects/${e}/gateway/keys/${t}`),"Gateway request failed")}async function Hg(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 v$(e,t){return u(await c.post(`/projects/${e}/gateway/providers/${encodeURIComponent(t)}/verify`,{}),"Gateway provider verification failed")}async function C$(){throw N("getReferralCode")}async function T$(){throw N("refreshReferralCode")}async function I$(e){throw N("validateReferralCode")}async function E$(){throw N("getReferralStats")}async function M$(e={}){throw N("listReferrals")}async function O$(e){throw N("sendReferralEmails")}var Do="call:";function zg(e){return e.startsWith("cr:")&&e.length>3?{type:"change_request",changeRequestId:e.slice(3)}:e.startsWith(Do)&&e.length>Do.length?{type:"connector_call",executionId:e.slice(Do.length)}:{type:"review_item",reviewItemId:e}}function Yw(e){return e==="needs_you"?"needs_you":e==="waiting"?"waiting":"done"}function j$(e){let t={needs_you:0,waiting:0,done:0};for(let n of e)t[Yw(n.status)]+=1;return t}function L$(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 jo(e){return e.split(/[._-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Yg(e){let t=e.indexOf(".");return t<=0?jo(e):`(${jo(e.slice(0,t))}) ${jo(e.slice(t+1))}`}function Jw(e){let t=e.indexOf(".");return t>0?{connector:e.slice(0,t),action:e.slice(t+1)}:{connector:e,action:""}}var Lt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},$=e=>typeof e=="string"&&e?e:void 0,Ce=e=>Array.isArray(e)?e:void 0,Vg=e=>typeof e=="number"?e:0,Qw=e=>e.split(`
|
|
14
|
+
`).map(t=>t.trim()).filter(Boolean);function Xw(e,t){let n=Lt(e.advanced),r=$(e.description),s=Ce(e.whatChanged)??(r?Qw(r):t.summary?[t.summary]:[]);return{crId:$(e.cr_id),number:typeof e.number=="number"?e.number:void 0,whatChanged:s,impact:$(e.impact)??"",verification:Ce(e.verification)??[],previewUrl:$(e.previewUrl)??$(e.preview_url),conflicts:Ce(e.conflicts),requestedChanges:Ce(e.requested_changes)??[],advanced:{headRef:$(n.headRef)??$(e.head_ref)??"",baseRef:$(n.baseRef)??$(e.base_ref)??"",headSha:$(n.headSha)??$(e.head_sha)??$(e.head_commit_sha)??"",baseSha:$(n.baseSha)??$(e.base_sha)??"",additions:Vg(n.additions),deletions:Vg(n.deletions),files:Ce(n.files)??[],mergeMode:$(n.mergeMode)??"merge"}}}function Zw(e,t){let n=Ce(e.actions);if(n)return{actions:n.map((l,p)=>({id:$(l.id)??`${t.review_item_id}-${p}`,title:$(l.title)??"Action",connector:$(l.connector)??"",action:$(l.action)??"",consequence:$(l.consequence)??"",risk:$(l.risk)??t.risk,icon:$(l.icon)??"generic",argsPreview:Ce(l.argsPreview)??[],policySource:$(l.policySource)??"Requires approval",decided:l.decided==="approved"||l.decided==="denied"?l.decided:void 0}))};let r=$(e.action_path)??"",{connector:s,action:o}=Jw(r),i=Lt(e.args_preview),a=Object.keys(i).length>0;return{actions:[{id:$(e.execution_id)??t.review_item_id,title:r?Yg(r):t.title||"Run action",connector:s,connectorName:$(e.connector_name),action:o,consequence:"Runs against the real connector once you approve",risk:t.risk,icon:"generic",argsPreview:Object.entries(i).map(([l,p])=>({key:l,value:p==="[redacted]"?"Hidden credential":typeof p=="string"?p:JSON.stringify(p,null,2)})),actionPath:r,rawArgsPreview:a?i:void 0,reviewComplete:e.args_preview_complete===!0,previewAuthorized:e.args_preview_authorized!==!1,canResolve:typeof t.can_resolve=="boolean"?t.can_resolve:e.args_preview_authorized!==!1,...t.resolvers?{resolvers:t.resolvers}:{},approvalContext:$(e.approval_context),...Object.keys(Lt(e.resolved_preview)).length>0?{resolvedPreview:Lt(e.resolved_preview)}:{},...$(e.resolved_error)?{resolvedError:$(e.resolved_error)}:{},connectorRisk:$(e.risk)??null,policySource:"Requires approval",expiresAt:$(t.expires_at)}]}}function ek(e,t){return{artifactKind:$(e.artifactKind)??"document",artifactLabel:$(e.artifactLabel)??"Output",previewUrl:$(e.previewUrl)??$(e.preview_url),preview:$(e.preview),files:Ce(e.files),note:$(e.note)??t.summary??""}}function tk(e,t){return{question:$(e.question)??t.title??"",context:$(e.context),options:Ce(e.options)??[]}}function nk(e,t){return{note:$(e.note)??t.summary??"",children:Ce(e.children)??[]}}function rk(e){let t=Lt(e.detail);switch(e.kind){case"change":return Xw(t,e);case"approval":return Zw(t,e);case"output":return ek(t,e);case"decision":return tk(t,e);case"batch":return nk(t,e)}}function sk(e,t){let n=typeof e.number=="number"?e.number:void 0,r=$(e.base_ref);return n!=null&&r?`#${n} \u2192 ${r}`:t}function $$(e,t={}){let n=Lt(e.detail),r=e.origin_session_id??void 0,s=r?t.sessionLabels?.[r]:void 0,o=e.kind==="approval"?$(n.action_path):void 0,i=e.kind==="change"?sk(n,e.summary):e.kind==="approval"?s??(r?"From a running session":e.summary):e.summary;return{id:e.review_item_id,kind:e.kind,title:o?Yg(o):e.title,summary:i,risk:e.risk,status:e.status,source:e.source,agent:e.agent||"Agent",createdAt:e.created_at,sessionId:r,expiresAt:$(e.expires_at),detail:rk(e)}}var Z={PROJECT_READ:"project.read",PROJECT_WRITE:"project.write",PROJECT_DELETE:"project.delete",PROJECT_SESSION_READ:"project.session.read",PROJECT_SESSION_START:"project.session.start",PROJECT_SESSION_STOP:"project.session.stop",PROJECT_SESSION_BINDINGS_WRITE:"project.session.bindings.write",PROJECT_MEMBERS_READ:"project.members.read",PROJECT_MEMBERS_MANAGE:"project.members.manage",PROJECT_TRIGGER_READ:"project.trigger.read",PROJECT_TRIGGER_CREATE:"project.trigger.create",PROJECT_TRIGGER_UPDATE:"project.trigger.update",PROJECT_TRIGGER_DELETE:"project.trigger.delete",PROJECT_TRIGGER_FIRE:"project.trigger.fire",PROJECT_GATEWAY_LOGS_READ:"project.gateway.logs.read",PROJECT_GATEWAY_SPEND_READ:"project.gateway.spend.read",PROJECT_USAGE_READ:"project.usage.read",PROJECT_GATEWAY_BUDGET_SET:"project.gateway.budget.set",PROJECT_GATEWAY_KEYS_MANAGE:"project.gateway.keys.manage",PROJECT_AGENT_READ:"project.agent.read",PROJECT_AGENT_WRITE:"project.agent.write",PROJECT_SKILL_READ:"project.skill.read",PROJECT_SKILL_WRITE:"project.skill.write",PROJECT_COMMAND_READ:"project.command.read",PROJECT_COMMAND_WRITE:"project.command.write",PROJECT_FILE_READ:"project.file.read",PROJECT_FILE_WRITE:"project.file.write",PROJECT_SETTINGS_WRITE:"project.settings.write",PROJECT_SANDBOX_WRITE:"project.sandbox.write",PROJECT_MODEL_READ:"project.model.read",PROJECT_MODEL_WRITE:"project.model.write",PROJECT_GITOPS_READ:"project.gitops.read",PROJECT_GITOPS_PUSH:"project.gitops.push",PROJECT_GITOPS_MERGE:"project.gitops.merge",PROJECT_GITOPS_REF_ANY:"project.gitops.ref.any",PROJECT_GITOPS_REF_DELETE:"project.gitops.ref.delete",PROJECT_SECRET_READ:"project.secret.read",PROJECT_SECRET_WRITE:"project.secret.write",PROJECT_CONNECTOR_READ:"project.connector.read",PROJECT_CONNECTOR_CONNECTIONS_MANAGE:"project.connector.connections.manage",PROJECT_CONNECTOR_WRITE:"project.connector.write",PROJECT_APP_READ:"project.app.read",PROJECT_APP_WRITE:"project.app.write",PROJECT_APP_DEPLOY:"project.app.deploy",PROJECT_APP_ADMIN:"project.app.admin",PROJECT_REVIEW_READ:"project.review.read",PROJECT_REVIEW_SUBMIT:"project.review.submit",PROJECT_REVIEW_ACT:"project.review.act",PROJECT_ROOM_READ:"project.room.read",PROJECT_ROOM_WRITE:"project.room.write",PROJECT_CREDENTIALS_ISSUE:"project.credentials.issue"},N$=[Z.PROJECT_WRITE,Z.PROJECT_TRIGGER_CREATE,Z.PROJECT_TRIGGER_FIRE,Z.PROJECT_TRIGGER_UPDATE,Z.PROJECT_TRIGGER_DELETE];function B$(e){let t=r=>e[r]?.allowed===!0,n=t(Z.PROJECT_WRITE);return{canCreate:n&&t(Z.PROJECT_TRIGGER_CREATE),canFire:t(Z.PROJECT_TRIGGER_FIRE),canUpdate:n&&t(Z.PROJECT_TRIGGER_UPDATE),canDelete:n&&t(Z.PROJECT_TRIGGER_DELETE)}}var K$=[Z.PROJECT_WRITE,Z.PROJECT_GITOPS_PUSH,Z.PROJECT_GITOPS_MERGE,Z.PROJECT_REVIEW_ACT];function ok(e){let t=r=>e[r]?.allowed===!0,n=t(Z.PROJECT_WRITE);return{canOpen:n&&t(Z.PROJECT_GITOPS_PUSH),canMerge:n&&t(Z.PROJECT_GITOPS_MERGE),canClose:n}}function q$(e,t,n){let r=zg(e.id);if(r.type==="connector_call"){let s=e.kind==="approval"?e.detail.actions?.[0]:void 0;return(t==="approve"||t==="reject")&&s?.canResolve!==!1&&s?.previewAuthorized!==!1}if(r.type==="change_request"){if(t==="answer")return!1;if(t==="approve")return ok(n).canMerge}return n[Z.PROJECT_WRITE]?.allowed===!0&&n[Z.PROJECT_REVIEW_ACT]?.allowed===!0}function F(e){return c.get(e,{showErrors:!1})}function A(e){return u(e,"Unexpected empty response")}async function Jg(e){return A(await F(`/accounts/${e}/iam/groups`)).groups}async function Qg(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}`))}async function Xg(e,t){return A(await c.post(`/accounts/${e}/iam/groups`,t,{showErrors:!1}))}async function Zg(e,t,n){return A(await c.patch(`/accounts/${e}/iam/groups/${t}`,n))}async function em(e,t){return A(await c.delete(`/accounts/${e}/iam/groups/${t}`))}async function tm(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/members`)).members}async function nm(e,t,n){return A(await c.post(`/accounts/${e}/iam/groups/${t}/members`,{userIds:n}))}async function J$(e,t){return A(await F(`/accounts/${e}/iam/groups/${t}/project-grants`)).grants}async function rm(e,t,n){return A(await c.delete(`/accounts/${e}/iam/groups/${t}/members/${n}`))}async function Q$(e,t){return A(await F(`/accounts/${e}/iam/members/${t}/groups`)).groups}async function X$(e,t){let n=A(await F(`/accounts/${e}/iam/members/${t}/project-access`));return{projects:n.projects,account_wide_policies:n.account_wide_policies??[]}}function Ze(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function r0(e,t={}){let n=Ze({resourceType:t.resourceType,principalType:t.principalType,principalId:t.principalId,projectId:t.projectId});return A(await F(`/accounts/${e}/iam/resource-grants${n}`)).grants}async function c0(e,t={}){let n=Ze({principalType:t.principalType,principalId:t.principalId,scopeType:t.scopeType,scopeId:t.scopeId===null?"null":t.scopeId});return A(await F(`/accounts/${e}/iam/policies${n}`)).policies}async function l0(e,t){return A(await c.post(`/accounts/${e}/iam/policies`,t,{showErrors:!1}))}async function u0(e,t,n){return A(await c.patch(`/accounts/${e}/iam/policies/${t}`,n,{showErrors:!1}))}async function p0(e,t){return A(await c.delete(`/accounts/${e}/iam/policies/${t}`))}async function d0(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-delete`,{policy_ids:t},{showErrors:!1}))}async function g0(e,t){return A(await c.post(`/accounts/${e}/iam/policies:bulk-import`,{policies:t},{showErrors:!1}))}async function sm(e){return A(await F(`/accounts/${e}/iam/roles`)).roles}async function om(e){return A(await F(`/accounts/${e}/iam/agent-identities`)).agents}async function im(e){return A(await c.get(`/projects/${e}/agent-identities`,{showErrors:!1})).agents}async function am(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/permissions`))}async function h0(e){return A(await F(`/accounts/${e}/iam/actions`)).actions}async function cm(e,t){return A(await F(`/accounts/${e}/iam/roles/${t}/usage`))}async function lm(e,t){return A(await c.post(`/accounts/${e}/iam/roles`,t,{showErrors:!1}))}async function um(e,t,n){return A(await c.patch(`/accounts/${e}/iam/roles/${t}`,n,{showErrors:!1}))}async function pm(e,t,n){return A(await c.put(`/accounts/${e}/iam/roles/${t}/permissions`,{actions:n},{showErrors:!1}))}async function dm(e,t){return A(await c.delete(`/accounts/${e}/iam/roles/${t}`,{showErrors:!1}))}async function _0(e,t,n){return A(await c.patch(`/accounts/${e}/iam/members/${t}/super-admin`,{isSuperAdmin:n}))}async function P0(e){return A(await F(`/accounts/${e}/iam/scim/tokens`)).tokens}async function w0(e,t){return A(await c.post(`/accounts/${e}/iam/scim/tokens`,t,{showErrors:!1}))}async function k0(e,t){return A(await c.delete(`/accounts/${e}/iam/scim/tokens/${t}`))}async function C0(e){return A(await F(`/accounts/${e}/iam/mfa-required`))}async function T0(e){return A(await F(`/accounts/${e}/iam/mfa-required/preview`))}async function I0(e,t){return A(await c.patch(`/accounts/${e}/iam/mfa-required`,{enabled:t},{showErrors:!1}))}async function E0(e){return A(await F(`/accounts/${e}/iam/session-oversight`))}async function M0(e,t){return A(await c.patch(`/accounts/${e}/iam/session-oversight`,{enabled:t},{showErrors:!1}))}async function L0(e){return A(await F(`/accounts/${e}/iam/sso/provider`)).provider}async function $0(e,t){return A(await c.put(`/accounts/${e}/iam/sso/provider`,t,{showErrors:!1})).provider}async function U0(e,t){return A(await c.post(`/accounts/${e}/iam/sso/provider/from-metadata`,t,{showErrors:!1})).provider}async function F0(e){return A(await c.post(`/accounts/${e}/iam/sso/provider/verify-domain`,{},{showErrors:!1})).provider}async function N0(e){return A(await c.delete(`/accounts/${e}/iam/sso/provider`))}async function B0(e){return A(await F(`/accounts/${e}/iam/sso/mappings`)).mappings}async function K0(e,t){return A(await c.post(`/accounts/${e}/iam/sso/mappings`,t,{showErrors:!1}))}async function q0(e,t){return A(await c.delete(`/accounts/${e}/iam/sso/mappings/${t}`))}async function V0(e){return A(await F(`/accounts/${e}/iam/session-policy`))}async function z0(e,t){return A(await c.patch(`/accounts/${e}/iam/session-policy`,t,{showErrors:!1}))}async function Y0(e){return A(await F(`/accounts/${e}/iam/sessions`)).sessions}async function J0(e,t){return A(await c.post(`/accounts/${e}/iam/sessions/${t}/revoke`,{},{showErrors:!1}))}async function Q0(e){return A(await F(`/accounts/${e}/iam/pat-policy`))}async function X0(e,t){return A(await c.patch(`/accounts/${e}/iam/pat-policy`,t,{showErrors:!1}))}async function nU(e){return A(await F(`/accounts/${e}/iam/service-accounts`)).service_accounts}async function rU(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts`,t,{showErrors:!1}))}async function sU(e,t){return A(await c.post(`/accounts/${e}/iam/service-accounts/${t}/disable`,{},{showErrors:!1}))}async function oU(e,t){return A(await c.delete(`/accounts/${e}/iam/service-accounts/${t}`))}async function uU(e){return A(await F(`/accounts/${e}/audit/webhooks`)).webhooks}async function pU(e,t){return A(await c.post(`/accounts/${e}/audit/webhooks`,t,{showErrors:!1}))}async function dU(e,t,n){return A(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function gU(e,t){return A(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function mU(e,t={}){let n=Ze({action:t.action,actor:t.actor,project_id:t.project_id,session_id:t.session_id,actor_type:t.actor_type,source:t.source,credential_kind:t.credential_kind,phase:t.phase,outcome:t.outcome,request_id:t.request_id,correlation_id:t.correlation_id,resource_type:t.resource_type,since:t.since,until:t.until,q:t.q,cursor:t.cursor,limit:t.limit});return A(await F(`/accounts/${e}/audit${n}`))}async function gm(e,t,n){let r=new URLSearchParams;return r.set("action",n.action),n.resourceType&&r.set("resourceType",n.resourceType),n.resourceId&&r.set("resourceId",n.resourceId),A(await F(`/accounts/${e}/iam/members/${t}/effective?${r.toString()}`))}async function mm(e,t,n){return n.length===0?[]:A(await c.post(`/accounts/${e}/iam/members/${t}/effective:batch`,{probes:n})).results}async function xU(e){return A(await F(`/accounts/${e}/iam/enterprise-demo`)).enabled}async function PU(e,t){return A(await c.put(`/accounts/${e}/iam/enterprise-demo`,{enabled:t})).enabled}async function fm(e){return u(await c.get(`/accounts/${e}/iam/oauth-clients`,{showErrors:!1}))}async function ym(e,t){return u(await c.get(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}async function hm(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients`,t,{showErrors:!1}))}async function _m(e,t,n){return u(await c.patch(`/accounts/${e}/iam/oauth-clients/${t}`,n,{showErrors:!1}))}async function bm(e,t){return u(await c.post(`/accounts/${e}/iam/oauth-clients/${t}/rotate-secret`,{},{showErrors:!1}))}async function Sm(e,t){return u(await c.delete(`/accounts/${e}/iam/oauth-clients/${t}`,{showErrors:!1}))}function ik(e){return Ze({principal_type:e?.principalType,principal_id:e?.principalId,scope_type:e?.scopeType,scope_id:e?.scopeId,object_type:e?.objectType,object_id:e?.objectId,role_id:e?.roleId,include_expired:e?.includeExpired?"true":void 0})}async function xm(e,t){return u(await F(`/accounts/${e}/iam/assignments${ik(t)}`)).assignments}async function Pm(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 wm(e,t){return u(await c.delete(`/accounts/${e}/iam/assignments/${t}`)).assignment}async function km(e,t){let n=t?.scopeType?`?scope_type=${t.scopeType}`:"";return u(await F(`/accounts/${e}/iam/permissions${n}`)).permissions}async function DU(){let e=await c.get("/account/deletion-status",{showErrors:!1});return e.error?.status===404?null:u(e,"Failed to load account deletion status")}async function jU(e="User requested deletion"){return u(await c.post("/account/request-deletion",{reason:e},{showErrors:!1}),"Failed to request account deletion")}async function LU(){return u(await c.post("/account/cancel-deletion",void 0,{showErrors:!1}),"Failed to cancel account deletion")}async function $U(){return u(await c.delete("/account/delete-immediately",{showErrors:!1}),"Failed to delete account immediately")}async function UU(){return(await c.get("/user-roles",{showErrors:!1})).data??{isAdmin:!1,role:null}}function KU(){return c.get("/admin/api/provider-distribution").then(e=>u(e))}function qU(e=300){return c.get(`/admin/api/sandboxes?limit=${e}`).then(t=>u(t))}function GU(e){return c.put("/admin/api/provider-distribution",e).then(t=>u(t))}function WU(e){return c.get(`/admin/api/provider-analytics?days=${e}`).then(t=>u(t))}function HU(e,t){return c.post(`/admin/api/sandboxes/${encodeURIComponent(e)}/migrate`,{targetProvider:t}).then(n=>u(n))}function VU(){return c.get("/admin/api/provider-fallback").then(e=>u(e))}function zU(e){return c.put("/admin/api/provider-fallback",{enabled:e}).then(t=>u(t))}var vm="Export the deck as PDF or PPTX with convertRuntimePresentation().";async function QU(e){throw N("getGoogleAuthUrl",vm)}async function XU(e,t){throw N("convertPresentationToGoogleSlides",vm)}async function Am(e,t){let n=new URLSearchParams;t?.segment&&n.set("segment",t.segment),t?.kind&&n.set("kind",t.kind),t?.sessionId&&n.set("session_id",t.sessionId),t?.limit!=null&&n.set("limit",String(t.limit)),t?.cursor&&n.set("cursor",t.cursor);let r=n.toString();return u(await c.get(`/projects/${e}/review/items${r?`?${r}`:""}`,{showErrors:!1}))}async function Rm(e){return u(await c.get(`/projects/${e}/review/summary`,{showErrors:!1}))}async function Cm(e,t){return u(await c.get(`/projects/${e}/review/items/${t}`))}async function Tm(e,t){return u(await c.post(`/projects/${e}/review/items`,t))}async function Im(e,t,n){return u(await c.post(`/projects/${e}/review/items/${t}/act`,n))}async function Em(e,t){return u(await c.post(`/projects/${e}/review/bulk`,t))}async function Mm(e){return u(await c.get(`/p/share?sandbox_id=${encodeURIComponent(e)}`),"Failed to load public links").shares??[]}async function Om(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 Dm(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 Lo=class extends Error{constructor(n,r){super(n);this.status=r;this.name="PublicSessionShareError"}status};function jm(e,t=""){return`${dn()}/public/session-shares/${encodeURIComponent(e)}${t}`}async function Lm(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 Lo(s,t.status)}return r}async function aF(e){return Lm(jm(e))}async function cF(e){return Lm(jm(e,"/messages"))}async function $m(e,t){return u(await c.get(`/projects/${e}/sessions/${t}/reminders`))}async function Um(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders`,n))}async function $o(e,t,n,r){return u(await c.patch(`/projects/${e}/sessions/${t}/reminders/${n}`,r))}async function Uo(e,t,n){return u(await c.delete(`/projects/${e}/sessions/${t}/reminders/${n}`))}async function Fm(e,t,n){return u(await c.post(`/projects/${e}/sessions/${t}/reminders/${n}/run`,{}))}var ak=4;async function Nm(e,t){let n=new Array(e.length),r=0,s=async()=>{for(;r<e.length;){let i=r++;try{await t(e[i]),n[i]={ok:!0}}catch(a){n[i]={ok:!1,error:a}}}};await Promise.all(Array.from({length:Math.min(ak,e.length)},s));let o={done:[],failed:[]};return e.forEach((i,a)=>{let l=n[a];l.ok?o.done.push(i):o.failed.push({reminder:i,error:l.error})}),o}function Bm(e,t,n){return Nm(t,r=>$o(e,r.sessionId,r.reminderId,n))}function Km(e,t){return Nm(t,n=>Uo(e,n.sessionId,n.reminderId))}async function qm(e){return u(await c.get(`/projects/${e}/reminders`))}var xe=e=>`/projects/${e}/rooms`;function Fo(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&s!==!1&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}async function Gm(e,t={}){return u(await c.get(`${xe(e)}${Fo({name:t.name,archived:t.archived,mine:t.mine})}`))}async function Wm(e,t){return u(await c.post(xe(e),t))}async function Hm(e,t){return u(await c.get(`${xe(e)}/${t}`))}async function Vm(e,t,n){return u(await c.patch(`${xe(e)}/${t}`,n))}async function zm(e,t,n={}){return u(await c.get(`${xe(e)}/${t}/messages${Fo({after:n.after,before:n.before,limit:n.limit,top:n.top,thread:n.thread})}`))}async function Ym(e,t,n){return u(await c.post(`${xe(e)}/${t}/messages`,n))}async function Jm(e,t,n){return u(await c.post(`${xe(e)}/${t}/read`,n===void 0?{}:{seq:n}))}async function Qm(e,t,n,r={}){return u(await c.put(`${xe(e)}/${t}/members/sessions/${n}`,r))}async function Xm(e,t,n){return u(await c.delete(`${xe(e)}/${t}/members/sessions/${n}`))}async function Zm(e,t,n,r={}){return u(await c.put(`${xe(e)}/${t}/members/people/${n}`,r))}async function ef(e,t,n){return u(await c.delete(`${xe(e)}/${t}/members/people/${n}`))}async function tf(e,t){return u(await c.get(`${xe(e)}/people${Fo({q:t})}`))}async function nf(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 rf(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 sf(e,t,n){let r=new URLSearchParams;t&&r.set("account_id",t),n?.deleteRevoked&&r.set("delete_revoked","true");let s=r.size>0?`?${r.toString()}`:"";return u(await c.delete(`/accounts/tokens/${encodeURIComponent(e)}${s}`))}async function of(){return u(await c.get("/oauth/grants")).grants}async function af(e){return u(await c.delete(`/oauth/grants/${encodeURIComponent(e)}`))}async function _F(){return u(await c.get("/accounts/me/devices")).devices}async function bF(e){return u(await c.delete(`/accounts/me/devices/${encodeURIComponent(e)}`))}async function cf(e){return u(await c.get(`/projects/${e}/cli-token`))}async function lf(e,t){return u(await c.post(`/projects/${e}/cli-token`,t??{}))}async function uf(e,t){return u(await c.delete(`/projects/${e}/cli-token/${t}`))}function $t(e){let t=new URLSearchParams,n=" format action actor actor_type project_id session_id source credential_kind phase outcome resource_type request_id correlation_id since until q cursor limit ";for(let[r,s]of Object.entries(e))n.includes(` ${r} `)&&s!=null&&s!==""&&t.set(r,String(s));return t}function No(e={}){return{format:e.format,action:e.action,actor:e.actor,actor_type:e.actorType,project_id:e.projectId,session_id:e.sessionId,source:e.source,credential_kind:e.credentialKind,phase:e.phase,outcome:e.outcome,resource_type:e.resourceType,request_id:e.requestId,correlation_id:e.correlationId,since:e.since,until:e.until,q:e.q,cursor:e.cursor,limit:e.limit}}async function pf(e,t){let n=$t(No(t)).toString();return u(await c.get(`/accounts/${e}/audit${n?`?${n}`:""}`))}async function df(e,t){let n=$t(No({...t,projectId:void 0})).toString();return u(await c.get(`/projects/${e}/audit${n?`?${n}`:""}`))}async function gf(e,t){let n=$t(No(t)).toString();return u(await c.get(`/accounts/${e}/audit/export${n?`?${n}`:""}`))}async function mf(e){return u(await c.get(`/accounts/${e}/audit/webhooks`))}async function ff(e,t){return u(await c.post(`/accounts/${e}/audit/webhooks`,t))}async function yf(e,t,n){return u(await c.patch(`/accounts/${e}/audit/webhooks/${t}`,n))}async function hf(e,t){return u(await c.delete(`/accounts/${e}/audit/webhooks/${t}`))}async function _f(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 bf(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 CF(e){return u(await c.get(`/approval-links/${e}`),"Failed to load approval")}async function Sf(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 xf(){return u(await c.get("/marketplace/marketplaces"))}async function Pf(){return u(await c.get("/marketplace/marketplaces/featured"))}async function wf(e){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}`),"Item not found")}async function kf(e,t){return u(await c.get(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`),"File not found")}async function vf(){return u(await c.get("/marketplace/sources"))}async function Af(e){return u(await c.post("/marketplace/sources",e),"Failed to add marketplace source")}async function Rf(e){return u(await c.delete(`/marketplace/sources/${encodeURIComponent(e)}`),"Failed to remove marketplace source")}async function MF(e,t){return u(await c.post(`/projects/${encodeURIComponent(e)}/marketplace/install-session`,{id:t}),"Failed to start marketplace install session")}async function jF(e){throw N("getTemplate")}async function LF(e,t){throw N("installTemplate")}async function Cf(e){return u(await c.get(`/projects/${e}/apps`),"Failed to list Apps").apps}async function Tf(e,t){return u(await c.post(`/projects/${e}/apps`,t),"Failed to create App")}async function Bo(e,t){return u(await c.get(`/projects/${e}/apps/${t}`),"Failed to load App")}async function If(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}`,n),"Failed to update App")}async function Ef(e,t){return u(await c.delete(`/projects/${e}/apps/${t}`),"Failed to delete App")}async function Mf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/token`,{}),"Failed to mint an App token")}async function Of(e,t){let n=await Bo(e,t);if(!n.auth)throw new Error("This server does not report sign-in values for Apps.");let r=u(await c.get(`/projects/${e}/jwks.json`),"Failed to read the project key set"),s=new TextEncoder().encode(JSON.stringify(r)),o="";for(let i of s)o+=String.fromCharCode(i);return{KORTIX_AUTH_ISSUER:n.auth.issuer,KORTIX_AUTH_AUDIENCE:n.auth.audience,KORTIX_AUTH_JWKS:`data:application/json;base64,${btoa(o)}`}}async function Df(e,t){return u(await c.get(`/projects/${e}/apps/${t}/access`),"Failed to load App access policy")}async function jf(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 Lf(e,t,n){return u(await c.patch(`/projects/${e}/apps/${t}/access`,n),"Failed to update App access policy")}async function $f(e,t){return u(await c.post(`/projects/${e}/apps/${t}/access-session`,{}),"Failed to create App access session")}async function Ko(e,t){return u(await c.post(`/projects/${e}/apps/artifacts`,t),"Failed to register App artifact")}async function qo(e,t,n){return u(await c.post(`/projects/${e}/apps/artifacts/${t}/finalize`,n),"Failed to finalize App artifact")}async function ck(e){return e instanceof Uint8Array?e:new Uint8Array(await e.arrayBuffer())}async function lk(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 Uf(e,t,n={}){let r=await ck(t),s=n.mediaType??"application/gzip",o=await Ko(e,{kind:"archive",media_type:s});if(!o.upload)throw new Error("App artifact registration did not return an upload URL");if(r.byteLength>o.upload.max_bytes)throw new Error(`App artifact exceeds ${o.upload.max_bytes} bytes`);n.onProgress?.(0,r.byteLength);let i=await fetch(o.upload.url,{method:"PUT",body:new Blob([Uint8Array.from(r).buffer],{type:s}),signal:n.signal,headers:{"content-type":s,"x-upsert":"false"}});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`App artifact upload failed with HTTP ${i.status}${a?`: ${a}`:""}`)}return n.onProgress?.(r.byteLength,r.byteLength),qo(e,o.artifact.artifact_id,{sha256:await lk(r),size_bytes:r.byteLength})}async function Ff(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/deployments`,n),"Failed to create App deployment")}async function Nf(e,t){return u(await c.get(`/projects/${e}/apps/${t}/deployments`),"Failed to list App deployments").deployments}async function Bf(e,t,n){return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to load App deployment")}async function Kf(e,t,n,r={}){let s=new URLSearchParams;r.after!==void 0&&s.set("after",String(r.after)),r.limit!==void 0&&s.set("limit",String(r.limit));let o=s.size?`?${s.toString()}`:"";return u(await c.get(`/projects/${e}/apps/${t}/deployments/${n}/logs${o}`),"Failed to load App logs")}async function qf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/start`,{}),"Failed to start App")}async function Gf(e,t){return u(await c.post(`/projects/${e}/apps/${t}/stop`,{}),"Failed to stop App")}async function Wf(e,t,n){return u(await c.delete(`/projects/${e}/apps/${t}/deployments/${n}`),"Failed to delete App deployment")}async function Hf(e,t,n){return u(await c.post(`/projects/${e}/apps/${t}/rollback`,{deployment_id:n}),"Failed to roll back App")}var ye=(e,t)=>`/projects/${e}/apps/${t}`;async function Vf(e,t){return u(await c.get(`${ye(e,t)}/machines`),"Failed to list machines").machines}async function Go(e,t,n,r){return u(await c.post(`${ye(e,t)}/machines/${n}/${r}`,{}),`Failed to ${r} the machine`).machines}var zf=(e,t,n)=>Go(e,t,n,"start"),Yf=(e,t,n)=>Go(e,t,n,"stop"),Jf=(e,t,n)=>Go(e,t,n,"restart");async function Qf(e,t,n){return u(await c.delete(`${ye(e,t)}/machines/${n}`),"Failed to destroy the machine").machines}async function Xf(e,t,n,r={}){return u(await c.put(`${ye(e,t)}/scale`,{count:n,...r.newVolumes?{new_volumes:!0}:{}}),"Failed to scale the App")}async function Zf(e,t,n){return u(await c.post(`${ye(e,t)}/exec`,n),"Failed to run the command")}async function ey(e,t){return u(await c.get(`${ye(e,t)}/volumes`),"Failed to list volumes").volumes}async function ty(e,t,n){return u(await c.post(`${ye(e,t)}/volumes`,n),"Failed to create the volume")}async function ny(e,t,n,r){return u(await c.patch(`${ye(e,t)}/volumes/${n}`,r),"Failed to update the volume")}async function ry(e,t,n,r){u(await c.delete(`${ye(e,t)}/volumes/${n}?confirm=${encodeURIComponent(r)}`),"Failed to destroy the volume")}async function sy(e,t,n){return u(await c.get(`${ye(e,t)}/volumes/${n}/snapshots`),"Failed to list snapshots").snapshots}async function oy(e,t,n){return u(await c.post(`${ye(e,t)}/volumes/${n}/snapshots`,{}),"Failed to take the snapshot")}async function iy(e,t,n,r){return u(await c.post(`${ye(e,t)}/volumes/${n}/restore`,{snapshot_id:r}),"Failed to restore the volume")}async function ay(e,t,n,r){return u(await c.post(`${ye(e,t)}/volumes/${n}/fork`,r),"Failed to fork the volume")}function pe(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return t===e.length?e:e.slice(0,t)}var ge=e=>`/drives/${encodeURIComponent(e)}`;async function QF(e){let t=u(await c.get(`/drives?${new URLSearchParams({projectId:e})}`),"Failed to load files").drives;if(!t[0])throw new P("Files not found",{status:404});return t[0]}async function XF(e,t){return u(await c.get(`${ge(e)}/access?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load sharing")}async function ZF(e,t){return u(await c.put(`${ge(e)}/access`,t),"Failed to share folder")}async function eN(e,t){let n=u(await c.delete(`${ge(e)}/access/${encodeURIComponent(t)}`),"Failed to stop sharing");return{pendingSessions:typeof n?.pendingSessions=="number"?n.pendingSessions:0}}async function tN(e){return u(await c.get(`${ge(e)}/principals`),"Failed to load people")}async function nN(e){return u(await c.get(`${ge(e)}/conflicts`),"Failed to load conflicts").conflicts}async function rN(e,t){u(await c.post(`${ge(e)}/conflicts/${encodeURIComponent(t)}/dismiss`,{}),"Failed to dismiss conflict")}async function sN(e,t="/"){return(await uk(e,t)).entries}async function uk(e,t="/"){return u(await c.get(`${ge(e)}/files?${new URLSearchParams({path:t})}`,{showErrors:!1}),"Failed to load files")}function cy(e,t,n){let r=pe(I().backendUrl),s={path:t};return n?.download&&(s.download="1"),`${r}${ge(e)}/files/content?${new URLSearchParams(s)}`}async function oN(e,t,n){let r=await U(cy(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new P(s?.message||"Could not download file",{status:r.status})}return r.blob()}async function iN(e,t,n){let r=await U(cy(e,t),{signal:n});if(!r.ok){let s=await r.json().catch(()=>null);throw new P(s?.message||"Could not download file",{status:r.status})}return{blob:await r.blob(),version:r.headers.get("etag")}}async function aN(e,t,n,r){let s=`${ge(e)}/files/content?${new URLSearchParams({path:t})}`,o=r?.ifMatch?{"If-Match":r.ifMatch}:{},i=r?.onProgress,a=globalThis.XMLHttpRequest;if(i&&a){let d=n instanceof Blob?n:new Blob([n]);return pk(a,s,d,o,i,r?.signal)}let l=u(await c.putRaw(s,n,{signal:r?.signal,headers:o}),"Failed to upload file"),p=n instanceof Blob?n.size:n.byteLength;return i?.(p,p),l}async function pk(e,t,n,r,s,o){let i=`${pe(I().backendUrl)}${t}`,{headers:a,rejected:l}=await vt(i,{"Content-Type":"application/octet-stream",...r});return new Promise((p,d)=>{let g=new e,m=()=>new P("Request aborted",{name:"AbortError",code:"ABORTED"});if(o?.aborted)return d(m());let f=()=>g.abort();o?.addEventListener("abort",f,{once:!0});let h=()=>o?.removeEventListener("abort",f);g.open("PUT",i),a.forEach((S,v)=>g.setRequestHeader(v,S)),g.upload.onprogress=S=>s(S.loaded,n.size),g.onload=()=>{h();let S=null;try{S=g.responseText?JSON.parse(g.responseText):null}catch{S=null}if(g.status>=200&&g.status<300)return p(S);g.status===401&&l(),d(new P(S?.message||"Failed to upload file",{status:g.status,code:S?.code,url:i}))},g.onerror=()=>{h(),d(new P("Network error while uploading",{name:"TypeError",url:i}))},g.onabort=()=>{h(),d(m())},g.send(n)})}async function cN(e,t){return u(await c.post(`${ge(e)}/files/mkdir`,{path:t},{showErrors:!1}),"Failed to create folder")}async function lN(e,t,n){return u(await c.post(`${ge(e)}/files/move`,{from:t,to:n},{showErrors:!1}),"Failed to move")}async function uN(e,t,n){let r={path:t};n?.recursive&&(r.recursive="true"),u(await c.delete(`${ge(e)}/files?${new URLSearchParams(r)}`,{showErrors:!1}),"Failed to delete")}async function pN(e){return u(await c.get(`${ge(e)}/versions`),"Failed to load versions").versions}async function dN(e,t){u(await c.post(`${ge(e)}/restore`,{versionId:t}),"Failed to restore version")}var dk=(e,t)=>`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/drives`;async function gN(e,t){return(await gk(e,t)).drives}async function gk(e,t){return u(await c.get(dk(e,t)),"Failed to load session files")}function et(e){try{return typeof process<"u"?process.env?.[e]:void 0}catch{return}}var tt={DESKTOP:"6080",DESKTOP_HTTPS:"6081",PRESENTATION_VIEWER:"3210",STATIC_FILE_SERVER:"3211",KORTIX_MASTER:"8000",BROWSER_STREAM:"9223",BROWSER_VIEWER:"9224",SSH:"22"};function nt(){let e=et("BACKEND_URL")||I().backendUrl;return e||"http://localhost:8008/v1"}function Ne(e){let t=pe(e);return t.endsWith("/v1")?t:`${t}/v1`}function gn(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}if(Array.isArray(e)){for(let t of e){let n=gn(t);if(n)return n}return}if(e&&typeof e=="object"){let t=e;return gn(t.sandboxId??t.id??t.slug??Object.values(t)[0])}}function mk(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 Vr(e,t,n){let r=n?.external_id||t.sandbox_url?.match(/\/p\/([^/]+)\//)?.[1]||t.sandbox_id||"";return{sandbox_id:n?.sandbox_id||t.sandbox_id||t.session_id,external_id:r,name:t.name||`${e.name} session`,provider:n?.provider||t.sandbox_provider||"platinum",base_url:n?.base_url||t.sandbox_url||(n?.external_id?`${nt()}/p/${n.external_id}/${tt.KORTIX_MASTER}`:""),status:mk(n?.status||t.status),metadata:{...t.metadata??{},project_id:e.project_id,session_id:t.session_id,project_name:e.name,runtime_status:n?.status,error:t.error},created_at:n?.created_at||t.created_at,updated_at:n?.updated_at||t.updated_at}}async function Wo(){let e=await Rt(),t=[];for(let n of e){let r=await Dt(n.project_id).catch(()=>[]);for(let s of r)t.push({project:n,session:s,runtime:null,sandbox:Vr(n,s,null)})}return t.sort((n,r)=>{let s={active:0,provisioning:1,stopped:2,error:3},o=(s[n.sandbox.status]??99)-(s[r.sandbox.status]??99);return o!==0?o:Date.parse(r.sandbox.updated_at)-Date.parse(n.sandbox.updated_at)})}async function Ho(e){let t=await c.get(`/sessions/${encodeURIComponent(e)}`,{showErrors:!1});if(t.success&&t.data)return t.data;if(t.error?.status===400||t.error?.status===404)return null;throw t.error??new Error("Session request failed")}async function zr(e){let t=await Ho(e);if(t)return{projectId:t.project_id,sessionId:t.session_id};let n=await mn(e);return n?{projectId:n.project.project_id,sessionId:n.session.session_id}:null}async function mn(e){let t=await Wo();return e?t.find(n=>n.sandbox.sandbox_id===e||n.sandbox.external_id===e||n.session.session_id===e||n.runtime?.external_id===e)??null:t[0]??null}async function ly(e){return u(await c.post("/notifications/device-token",e))}async function uy(e,t){return u(await c.delete(`/notifications/device-token/${encodeURIComponent(e)}`,{signal:t?.signal}))}async function py(e,t){let n=I().fetch??((o,i)=>fetch(o,i)),r=Ne(t?.backendUrl??I().backendUrl),s=await n(`${r}/notifications/device-token/release`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({device_token:e}),credentials:"omit",...t?.signal?{signal:t.signal}:{}});if(!s.ok)throw new P(`Device token release failed (HTTP ${s.status})`,{status:s.status,response:s});return{ok:!0}}var TN=["turn_done","turn_error","question","permission","shared","automation_failed","automation_recovered","capture_device_down","capture_device_recovered","message"];async function dy(e={},t){let n=new URLSearchParams;e.limit!==void 0&&n.set("limit",String(e.limit)),e.before&&n.set("before",e.before);let r=n.toString();return u(await c.get(`/notifications${r?`?${r}`:""}`,{showErrors:!1,signal:t?.signal}))}async function gy(e){let t="ids"in e?{ids:e.ids}:"all"in e?{all:!0}:{session_id:e.sessionId};return u(await c.post("/notifications/read",t))}var IN={turn_done:{push:!0,email:!1},turn_error:{push:!0,email:!0},question:{push:!0,email:!0},permission:{push:!0,email:!1},shared:{push:!0,email:!0},automation_failed:{push:!0,email:!0},automation_recovered:{push:!0,email:!1},capture_device_down:{push:!0,email:!0},capture_device_recovered:{push:!0,email:!1},message:{push:!0,email:!0}};async function my(){return u(await c.get("/notifications/preferences",{showErrors:!1}))}async function fy(e){return u(await c.put("/notifications/preferences",e))}async function yy(){return u(await c.get("/notifications/web-push/key",{showErrors:!1}))}async function hy(e){let t={endpoint:e.endpoint,keys:{p256dh:e.keys.p256dh,auth:e.keys.auth}};return u(await c.post("/notifications/web-push/subscriptions",t,{showErrors:!1}))}async function _y(e,t){return u(await c.delete(`/notifications/web-push/subscriptions?endpoint=${encodeURIComponent(e)}`,{signal:t?.signal,showErrors:!1}))}async function Yr(e){return u(await c.get(`/projects/${e}/model-access`))}async function Jr(e,t){return u(await c.put(`/projects/${e}/model-access`,t))}async function Qr(e){return u(await c.get(`/projects/${encodeURIComponent(e)}/custom-providers`)).providers}async function Xr(e,t,n){return u(await c.put(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,n))}var by=e=>e?.status===404;async function Zr(e,t){let n=await c.delete(`/projects/${encodeURIComponent(e)}/custom-providers/${encodeURIComponent(t)}`,{showErrors:!1});if(!n.success&&!by(n.error))throw n.error??new Error("Failed to delete the custom provider");let r=`CUSTOM_${t.toUpperCase().replace(/-/g,"_")}_API_KEY`;await wr(e,r).catch(s=>{if(!by(s))throw s})}function FN(e){let{running:t,isCarousel:n,contentStatus:r,isWebsitePreview:s,previewHasError:o,previewIsLinkOnly:i}=e;return t||n?!1:s?o&&!i:r==="error"}function Vo(e){return typeof e=="string"&&e.trim().length>0}function Sy(e){if(!e||typeof e!="object")return!1;let{path:t,url:n,content:r}=e;return Vo(t)||Vo(n)||Vo(r)}function fk(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 es(e){if(!e)return!0;let t=fk(e.items);return t?!t.some(Sy):!Sy(e)}var Te="kortix.transcript.v1",yk=["auth","rate_limit","credits","context_length","output_length","aborted","unknown"];function xy(e){return typeof e=="string"&&yk.includes(e)}var BN=["once","always","reject"],KN=["read","edit","glob","grep","list","bash","task","external_directory","todowrite","question","webfetch","websearch","lsp","doom_loop","skill"];var ky="kortix-v1-import",hk={harness:ky,harness_version:Te,adapter_version:"1"},zo={schema:ue,v:1},_k={opencode:"[Tool execution was interrupted]",pi:"No result provided"},bk="[Old tool result content cleared]",Sk="The following tool was executed by the user",xk=new Map(Object.entries({bash:"shell",powershell:"shell",read:"read",write:"write",edit:"edit",multiedit:"edit",patch:"patch",apply_patch:"patch",list:"list",ls:"list",glob:"glob",find:"glob",grep:"grep",webfetch:"web_fetch",websearch:"web_search",codesearch:"web_search",todowrite:"todo",todoread:"todo",task:"task",question:"question",plan_enter:"plan",plan_exit:"plan"})),Pk=e=>xk.get(e)??(e.includes("_")?"mcp":"other"),wk=new Map([["stop","stop"],["tool-calls","tool_calls"],["length","length"],["error","error"]]),kk=new Map([["stop","stop"],["tool_calls","tool-calls"],["length","length"],["error","error"]]),B=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Q=e=>typeof e=="string"?e:void 0,Be=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ss=(e,t)=>Object.hasOwn(e,t)?e[t]:void 0,vy=(e,t,n)=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0}),Ut=e=>Be(e)!==void 0&&Math.abs(e)<=864e13?new Date(e).toISOString():null,Ft=e=>{let t=e?Date.parse(e):NaN;return Number.isNaN(t)?void 0:t};function Yo(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,s)=>Yo(r,t[s]));if(!B(e)||!B(t))return!1;let n=Object.keys(e).filter(r=>e[r]!==void 0);return n.length===Object.keys(t).filter(r=>t[r]!==void 0).length&&n.every(r=>Yo(e[r],ss(t,r)))}function ns(e,t){if(Yo(e,t))return;if(e===void 0)return{del:!0};if(!B(e)||!B(t))return{set:e};let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let s=ns(ss(e,r),ss(t,r));s&&vy(n,r,s)}return{sub:n}}function rs(e,t){if(!t)return e;if("set"in t)return t.set;if("del"in t)return;let n=B(e)?{...e}:{};for(let[r,s]of Object.entries(t.sub)){let o=rs(ss(n,r),s);o===void 0?delete n[r]:vy(n,r,o)}return n}var fn=e=>Object.values(e??{}).find(t=>t.version===Te),os=(e,t)=>({[e]:{version:Te,...t}}),Ay=(e,t)=>e.url!==void 0?{url:e.url}:e.ref!==void 0&&!t.fromV1?{url:e.ref}:{},Py=e=>(e??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join(""),vk=(e,t)=>({id:e.id,...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID}),Ak=e=>{if(B(e.result?.details))return e.result.details;let t=Object.values(e.ext??{}).find(n=>n.version!==Te&&B(n.data?.details));return t?t.data.details:{}};function Rk(e,t,n){let r=e.result,s=e.input===null||e.input===void 0?{}:{input:e.input},o=Ft(e.started_at)??t.created,i=Ft(e.ended_at)??o,a=r?.exit_code!==void 0?{exit:r.exit_code}:{};if(e.status==="pending")return{status:"pending",input:e.input??{},raw:""};if(e.status==="running")return{status:"running",input:e.input??{},...e.title&&{title:e.title},time:{start:o}};if(e.status==="error")return{status:"error",...s,error:Py(r?.content),...r?.exit_code!==void 0&&{metadata:a},time:{start:o,end:i}};let l=(r?.content??[]).flatMap((d,g)=>d.type==="attachment"?[{...n,id:`${e.id}-a${g}`,type:"file",mime:d.mime,...Ay(d,t)}]:[]),p=Ft(r?.cleared_at);return{status:"completed",...s,output:Py(r?.content),title:e.title??"",metadata:{...Ak(e),...a},time:{start:o,end:i,...p!==void 0&&{compacted:p}},...l.length&&{attachments:l}}}function Ry(e,t){let n=vk(e,t);switch(e.type){case"text":return{...n,type:"text",text:e.text,...e.synthetic!==void 0&&{synthetic:e.synthetic}};case"reasoning":return{...n,type:"reasoning",text:e.text,time:{start:t.created}};case"attachment":return{...n,type:"file",mime:e.mime,...e.name!==void 0&&{filename:e.name},...Ay(e,t)};case"tool_call":return{...n,type:"tool",callID:e.call_id,tool:e.name,state:Rk(e,t,{...t.sessionID!==null&&{sessionID:t.sessionID},messageID:t.messageID})};case"step":return e.phase==="start"?{...n,type:"step-start"}:{...n,type:"step-finish",reason:"stop",cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}}};case"compaction":return{...n,type:"compaction",auto:e.trigger==="auto"||e.trigger==="overflow",...e.trigger==="overflow"&&{overflow:!0},...e.first_kept_message_id!==null&&{tail_start_id:e.first_kept_message_id}};case"harness":return t.fromV1&&(e.harness==="opencode"||e.harness==="pi")?e.data:e.model_visible&&e.fallback_text!==void 0?{...n,type:"text",text:e.fallback_text,synthetic:!0}:void 0;case"subtask":return}}function Ck(e){return xy(e.code)?{name:e.code==="aborted"?"MessageAbortedError":"UnknownError",code:e.code,data:{message:e.message}}:{name:e.code,data:{message:e.message}}}function Cy(e,t,n={}){let r=e.usage,s=e.finish===null?void 0:kk.get(e.finish);return{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"assistant",time:{created:t.created,...e.completed_at!==null&&{completed:Ft(e.completed_at)}},...e.reply_to&&{parentID:e.reply_to},modelID:e.model?.model??"",providerID:e.model?.provider??"",...e.model?.variant!==void 0&&{variant:e.model.variant},mode:e.agent??"",agent:e.agent??"",path:{cwd:"",root:""},cost:r?.cost??0,tokens:{input:r?.input??0,output:r?.output??0,reasoning:r?.reasoning??0,cache:{read:r?.cache_read??0,write:r?.cache_write??0}},...s&&{finish:s},...e.error&&{error:Ck(e.error)},...n}}function Ty(e,t){return e.role==="assistant"?Cy(e,t):{id:e.message_id,...t.sessionID!==null&&{sessionID:t.sessionID},role:"user",time:{created:t.created},agent:e.agent??"",model:{providerID:e.model?.provider??"",modelID:e.model?.model??"",...e.model?.variant!==void 0&&{variant:e.model.variant}}}}function Iy(e,t,n){let r=`${e.message_id}-summary`;return{info:Cy({...e,reply_to:e.message_id,agent:"compaction",finish:e.status==="complete"?"stop":null},n,{id:r,summary:!0}),parts:[{id:`${r}-p0`,...n.sessionID!==null&&{sessionID:n.sessionID},messageID:r,type:"text",text:t.summary}]}}function Tk(e,t,n){let r=n||e.producer.harness===ky;if(!r&&(e.role==="system"||e.kind==="context"))return[];let s=fn(e.ext)?.data,o=s&&"runtime_session_id"in s?s.runtime_session_id??null:t,i={sessionID:o,messageID:e.message_id,created:Ft(e.created_at),fromV1:r},a=s&&"parts"in s?s.parts:e.blocks.flatMap(d=>{let g=Ry(d,i);return g===void 0?[]:[rs(g,fn(d.ext)?.data)]}),l=[{runtime_session_id:o,info:rs(Ty(e,i),s?.info),parts:a}],p=e.blocks.find(d=>d.type==="compaction");if(e.kind==="compaction"&&p&&p.summary!==null){let d=rs(Iy(e,p,i),s?.summary);l.push({runtime_session_id:o,info:d.info,parts:d.parts})}return l}var Jo=e=>Be(B(e.info)&&B(e.info.time)?e.info.time.created:void 0)??-1/0,ts=e=>String(B(e.info)?e.info.id:""),Ey=(e,t)=>Jo(e)-Jo(t)||(ts(e)<ts(t)?-1:ts(e)>ts(t)?1:0),wy=e=>{let t=fn(e.ext);return t?t.native_id??null:e.thread_id};function is(e){let t=structuredClone(e),n=t.threads.find(i=>i.parent_thread_id===null)??t.threads[0],r=t.threads.flatMap(i=>i.messages.flatMap(a=>Tk(a,wy(i),fn(i.ext)!==void 0))),s=fn(t.ext)?.data,o=s&&"root_id"in s?s.root_id??null:n?wy(n):null;return{session_id:t.session_id,root_id:o,rows:r.sort(Ey)}}function Ik(e){let t=e.role==="assistant"?{p:e.providerID,m:e.modelID,v:e.variant}:B(e.model)?{p:e.model.providerID,m:e.model.modelID,v:e.model.variant}:{},n=Q(t.p),r=Q(t.m);return n===void 0||r===void 0?null:{provider:n,model:r,...Q(t.v)!==void 0&&{variant:t.v}}}function Ek(e){if(!B(e.tokens))return null;let t=e.tokens,n=B(t.cache)?t.cache:{};return{input:Be(t.input)??0,output:Be(t.output)??0,cache_read:Be(n.read)??0,cache_write:Be(n.write)??0,...Be(t.reasoning)!==void 0&&{reasoning:t.reasoning},...Be(e.cost)!==void 0&&{cost:e.cost}}}var Mk=e=>({code:Q(e.code)||Q(e.name)||"UnknownError",message:Q(B(e.data)?e.data.message:void 0)??""});function My(e,t,n){let r=t.resolve(e);return r||n.attachment++,{mime:Q(e.mime)??"application/octet-stream",...r&&{ref:r.ref,bytes:r.bytes,...r.sha256!==void 0&&{sha256:r.sha256}},...Q(e.url)!==void 0&&{url:e.url}}}function Ok(e,t,n,r){let s=e.state,o=B(s.time)?s.time:{};B(s.input)||r.tool_input++;let i=B(s.metadata)&&Be(s.metadata.exit)!==void 0?{exit_code:s.metadata.exit}:{},a,l,p=s.input??null;if(s.status==="completed"){let m=(Array.isArray(s.attachments)?s.attachments:[]).filter(B).map(h=>{let{bytes:S,...v}=My(h,n,r);return{type:"attachment",...v}}),f=Ut(o.compacted);a="complete",l={content:[...Q(s.output)!==void 0?[{type:"text",text:s.output}]:[],...m],is_error:!1,...i,...f&&{model_content:[{type:"text",text:bk}],cleared_at:f}}}else if(s.status==="error"){let m=Q(s.error);a="error",l={content:m!==void 0?[{type:"text",text:m}]:[],is_error:!0,...m!==void 0&&{error:{message:m}},...i}}else if(n.live)a=s.status==="pending"?"pending":"running",a==="pending"&&Q(s.raw)&&!(B(s.input)&&Object.keys(s.input).length)&&(p=s.raw);else{let m=_k[n.h];a="error",l={content:[{type:"text",text:m}],is_error:!0,synthetic:!0,error:{code:"interrupted",message:m}}}let d=Ut(o.start),g=Ut(o.end);return{type:"tool_call",id:t,call_id:e.callID,name:e.tool,kind:Pk(e.tool),input:p,status:a,...l&&{result:l},...Q(s.title)&&{title:s.title},...d&&{started_at:d},...g&&{ended_at:g}}}function Dk(e,t,n,r,s,o){let i=(a,l=!1)=>({type:"harness",id:t,harness:s.h,kind:a,data:e,model_visible:l,...l&&{fallback_text:Sk}});if(!B(e))return i("unknown");switch(e.type){case"text":return typeof e.text!="string"||e.ignored===!0?i("text"):{type:"text",id:t,text:e.text,...typeof e.synthetic=="boolean"&&{synthetic:e.synthetic}};case"reasoning":return typeof e.text!="string"?i("reasoning"):{type:"reasoning",id:t,text:e.text};case"file":return e.mime==="text/plain"||e.mime==="application/x-directory"?i("file"):{type:"attachment",id:t,...My(e,s,o),...Q(e.filename)!==void 0&&{name:e.filename}};case"tool":return typeof e.callID=="string"&&typeof e.tool=="string"&&B(e.state)?Ok(e,t,s,o):i("tool");case"step-start":case"step-finish":return{type:"step",id:t,phase:e.type==="step-start"?"start":"finish"};case"compaction":{if(e!==n)return i("compaction");let a=e.overflow===!0?"overflow":e.auto===!0?"auto":"manual";return{type:"compaction",id:t,summary:r,first_kept_message_id:Q(e.tail_start_id)??null,trigger:a}}case"subtask":return i("subtask",!0);default:return i(Q(e.type)||"unknown")}}function jk(e){let t=e.map((s,o)=>B(s)&&typeof s.id=="string"&&s.id?s.id:`#${o}`),n=new Set(t),r=new Set;return t.map(s=>{if(!r.has(s))return r.add(s),s;let o=2;for(;n.has(`${s}#${o}`);)o++;return n.add(`${s}#${o}`),`${s}#${o}`})}function Lk(e,t,n,r,s,o){let i=B(e.info)?e.info:{},a=Array.isArray(e.parts)?e.parts:[],l=i.role==="user"?a.find(R=>B(R)&&R.type==="compaction"):void 0,p=t&&B(t.info)?t.info:void 0,d=i.role==="assistant"||i.role==="user"?i.role:"system",g=l?p:d==="assistant"?i:void 0,m=g&&B(g.error)?g.error:void 0,f=m?.name==="MessageAbortedError",h=g&&B(g.time)?Ut(g.time.completed):null,S=o.live?"streaming":"interrupted",v=g?m?f?"aborted":"error":h?"complete":S:l?S:"complete",T=Ut(B(i.time)?i.time.created:void 0)??"",_=t?(Array.isArray(t.parts)?t.parts:[]).flatMap(R=>B(R)&&R.type==="text"&&typeof R.text=="string"?[R.text]:[]).join(""):null,b={tool_input:0,cut_point:0,attachment:0},O=jk(a),y=a.map((R,L)=>Dk(R,O[L],l,_,o,b)),w=y.some(R=>R.type==="text"||R.type==="attachment"||R.type==="tool_call"||R.type==="harness"&&R.model_visible),x=!s&&d!=="system"&&(l?v==="complete":!m||f&&w),k=o.live&&x&&v!=="streaming"&&y.some(R=>R.type==="tool_call"&&(R.status==="pending"||R.status==="running"))?"streaming":v,C=s?"superseded":x||!m?void 0:f?"aborted":"failed_attempt";return l&&B(l)&&Q(l.tail_start_id)===void 0&&b.cut_point++,{m:{...zo,message_id:Q(i.id)??"",thread_id:n,seq:r,role:d,kind:l?"compaction":"turn",status:k,in_context:x,...C&&{hidden_reason:C},agent:Q(i.agent)??null,...d==="assistant"&&{reply_to:Q(i.parentID)??null},model:Ik(i),usage:g?Ek(g):null,finish:!g||l?null:f?"aborted":m?"error":wk.get(i.finish)??null,error:m?Mk(m):null,created_at:T,completed_at:g||l?h:T||null,producer:hk,blocks:y},lost:b}}function $k(e,t,n,r,s){let o={};t.runtime_session_id!==r&&(o.runtime_session_id=t.runtime_session_id);let i={sessionID:t.runtime_session_id,messageID:e.message_id,created:Ft(e.created_at),fromV1:!0};Array.isArray(t.parts)?e.blocks.forEach((p,d)=>{if(p.type==="harness"||p.type==="subtask")return;let g=ns(t.parts[d],Ry(p,i));g&&(p.ext=os(s,{data:g}))}):o.parts=t.parts;let a=ns(t.info,Ty(e,i));a&&(o.info=a);let l=e.blocks.find(p=>p.type==="compaction");if(n&&l){let p=ns({info:n.info,parts:n.parts},Iy(e,l,i));p&&(o.summary=p)}Object.keys(o).length&&(e.ext=os(s,{data:o}))}function Uk(e,t,n){if(t){for(let r of[!0,!1])for(let s of e)if(!(s.runtime_session_id===t||!Array.isArray(s.parts))){for(let o of s.parts)if(!(!B(o)||o.type!=="tool"||!B(o.state))&&(r?B(o.state.metadata)&&o.state.metadata.sessionId===t:n(o.state).includes(t)))return{row:s,part:o}}}}function as(e,t={}){let n={h:t.harness??"opencode",resolve:t.resolveAttachment??(()=>null),counts:{tool_input:0,cut_point:0,attachment:0},live:t.live===!0},r=structuredClone(e.rows).sort(Ey),s=new Map;for(let b of r){let O=s.get(b.runtime_session_id);O?O.push(b):s.set(b.runtime_session_id,[b])}let o=e.root_id,i=s.has(o),a=new Map,l=b=>a.get(b)??(a.set(b,JSON.stringify(b)),a.get(b)),p=new Map;for(let b of s.keys()){let O=i&&b===o?void 0:Uk(r,b,l);O&&p.set(b,O)}let d=[...r].reverse().find(b=>b.runtime_session_id===null||!p.has(b.runtime_session_id)),g=i||!d?o:d.runtime_session_id;s.has(g)||s.set(g,[]);let m=g||e.session_id,f=b=>b!==null&&p.has(b)?b:m,h=Ut(r.map(Jo).find(Number.isFinite))??"",S=[];for(let[b,O]of s){if(b!==g&&(b===null||!p.has(b)))continue;let y=b===g,w=y?r.filter(D=>D.runtime_session_id!==g&&f(D.runtime_session_id)===m):[],x=[...w,...O],k=new Set(w),C=new Map,j=new Set;for(let D of x){let q=B(D.info)?D.info:{};if(q.role!=="user"||!Array.isArray(D.parts)||!D.parts.some(K=>B(K)&&K.type==="compaction"))continue;let W=x.find(K=>!j.has(K)&&K.runtime_session_id===D.runtime_session_id&&B(K.info)&&K.info.role==="assistant"&&K.info.summary===!0&&K.info.parentID===q.id);W&&(C.set(D,W),j.add(W))}let R=[];for(let D of x){if(j.has(D))continue;let q=C.get(D),{m:W,lost:K}=Lk(D,q,y?m:b,R.length+1,k.has(D),n);if($k(W,D,q,b,n.h),W.in_context)for(let Me of["tool_input","cut_point","attachment"])n.counts[Me]+=K[Me];R.push(W)}let L=b===null?void 0:p.get(b),le=R.find(D=>D.role==="user"&&D.kind==="turn");S.push({...zo,thread_id:y?m:b,parent_thread_id:L?f(L.row.runtime_session_id):null,spawned_by:L&&typeof L.part.callID=="string"?{message_id:Q(L.row.info?.id)??"",call_id:L.part.callID}:null,agent:le?.agent??null,title:null,created_at:R[0]?.created_at||h,messages:R,ext:os(n.h,b===null?{}:{native_id:b})})}S.sort((b,O)=>b.parent_thread_id===null?-1:O.parent_thread_id===null?1:_(b)-_(O));let v=S[0]?.messages.filter(b=>b.role==="user"&&b.kind==="turn").at(-1),T=n.counts.tool_input+n.counts.cut_point+n.counts.attachment>0;return{...zo,session_id:e.session_id,title:null,created_at:h,restore_grade:T?"partial":"converted",grade_counts:n.counts,harness:{current:n.h,history:[]},selection:{agent:v?.agent??null,model:v?.model??null},todos:[],pending:{questions:[],permissions:[]},threads:S,...g!==o&&{ext:os(n.h,{data:{root_id:o}})}};function _(b){return r.findIndex(O=>O.runtime_session_id===b.thread_id)}}var Qo={schema:ue,v:1},Fk=Object.freeze({}),Oy=new WeakMap;function cs(e){let t=Oy.get(e);if(t&&t.state===e.state)return t.block;let n=e.sessionID??null,r={id:e.messageID,sessionID:e.sessionID,role:"assistant"},o=as({session_id:"",root_id:n,rows:[{runtime_session_id:n,info:r,parts:[e]}]},{live:!0}).threads[0].messages[0].blocks[0];return Oy.set(e,{state:e.state,block:o}),o}var Xo=new WeakMap;function Zo(e){if(Xo.has(e))return Xo.get(e);let t={...Qo,thread_id:"",parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:"",ext:{opencode:{version:Te}},messages:[{...Qo,message_id:"",thread_id:"",seq:1,role:"assistant",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:"",completed_at:null,producer:{harness:"",harness_version:"",adapter_version:""},blocks:[e]}]},{rows:n}=is({...Qo,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]},threads:[t]}),r=n[0].parts[0];return Xo.set(e,r),r}function se(e){return Zo(e)}var me=e=>typeof e=="object"&&e!==null&&e.type==="tool_call",Ke=e=>me(e)?se(e):e;function Nk(e){let t=se(e).state.metadata;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length?t:Fk}var jy=e=>(e.result?.content??[]).flatMap(t=>t.type==="text"?[t.text]:[]).join("");function Bk(e){return e.status==="complete"?"completed":e.status}var Dy=new WeakMap;function Kk(e){if(e.status!=="complete")return"";let t=Dy.get(e);return t===void 0&&Dy.set(e,t=jy(e)),t}function qk(e){return e.status==="error"?e.result?.error?.message||jy(e):void 0}function he(e){return(e??"").replace(/^oc-/,"").replace(/-/g,"_")}function ZN(e){return he(e)==="bash"}function Ly(e){let t=he(e);return t==="question"||t==="ask"}function eB(e,t){let n=Math.max(0,e);return`${t?"Running":"Ran"} ${n} command${n===1?"":"s"}`}var Gk=new Set(["show","show_user"]);function $y(e){return Gk.has(he(e))}function tB(e,t){let n=Math.max(0,e);return`${t?"Writing":"Wrote"} ${n} file${n===1?"":"s"}`}function Uy(e){return!!(e.type==="snapshot"||e.type==="patch"||e.type==="step-start"||e.type==="step-finish"||e.type==="text"&&!e.text?.trim()||ei(e))}function ei(e){let t=me(e)?se(e):e,n=he(t.tool);return n!=="show"&&n!=="show_user"||t.state?.status!=="completed"?!1:es(t.state?.input)}var Wk=new Set(["show","show_user","agent_spawn","agent_status","agent_message","agent_task_update","agent_stop"]);function Fy(e){return Wk.has(he(e))}var Hk=50*1024*1024,ti="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Vk=new RegExp(`^kortix-attachment://(${ti})/(${ti})/(${ti})$`);function ri(e){if(typeof e!="string")return null;let t=Vk.exec(e);return t?{projectId:t[1],sessionId:t[2],attachmentId:t[3]}:null}function cB(e){return ri(e)!==null}var ni=new WeakMap;async function Ny(e,t,n,r={}){if(n.size>Hk)throw new Error("Attachments must be 50 MiB or smaller.");let s=`${e}/${t}`,o=r.attachmentId?void 0:ni.get(n)?.get(s);if(o?.promise)return o.promise;let i=o??{id:r.attachmentId??crypto.randomUUID(),promise:void 0};if(!r.attachmentId){let l=ni.get(n)??new Map;l.set(s,i),ni.set(n,l)}let a=new FormData;return a.append("attachment_id",i.id),a.append("file",n,n.name),i.promise=c.upload(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/attachments`,a,{signal:r.signal,timeout:12e4,showErrors:!1}).then(u).catch(l=>{throw i.promise=void 0,l}),i.promise}async function By(e,t){let n=ri(e);if(!n)throw new Error("Invalid attachment reference");let r=I().backendUrl.replace(/\/$/,""),s=await U(`${r}/projects/${n.projectId}/sessions/${n.sessionId}/attachments/${n.attachmentId}`,{signal:t});if(!s.ok)throw new P("Could not load attachment",{status:s.status});return s.blob()}var zk=new Set(["show","show_user"]);function Yk(e){let t=[],n=0;for(;;){let r=e.indexOf("<file",n);if(r===-1)return t;let s=r+5;if(s>=e.length||!/\s/.test(e[s])){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return t;let i=e.indexOf("</file>",o+1);if(i===-1)return t;t.push(e.slice(s,o).trimStart()),n=i+7}}var qe=e=>!!e&&typeof e=="object"&&!Array.isArray(e),yn=e=>typeof e=="string"&&e.length>0?e:null,Ky=e=>typeof e=="string"?yn(e.split("/").pop()):null;function ls(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 Jk(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 Qk(e){let t=e.blocks.filter(qe).map(n=>n.type==="attachment"?{type:"file",url:n.ref??n.url,filename:n.name,mime:n.mime}:n.type==="tool_call"?{type:"tool",tool:n.name,state:{input:n.input}}:n.type==="harness"&&qe(n.data)?n.data:n);return{info:{id:e.message_id,role:e.role},parts:t}}function Xk(e,t){for(let n of Yk(e))t(ls(n,"attachment"),ls(n,"filename")??Ky(ls(n,"path")),ls(n,"mime"))}function Zk(e,t){for(let n of[e,...Jk(e.items)])qe(n)&&t(n.attachment,Ky(n.path),null)}function lB(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){let s=qe(r)&&Array.isArray(r.blocks)?Qk(r):r;if(!qe(s)||!qe(s.info)||!Array.isArray(s.parts))continue;let o=yn(s.info.id);if(!o)continue;let i=yn(s.info.role)??"unknown",a=(l,p,d)=>{let g=ri(l);!g||n.has(l)||(n.add(l),t.push({url:l,attachment_id:g.attachmentId,filename:p,mime:d,message_id:o,role:i}))};for(let l of s.parts)qe(l)&&(l.type==="file"?a(l.url,yn(l.filename),yn(l.mime)):l.type==="text"&&typeof l.text=="string"?Xk(l.text,a):l.type==="tool"&&typeof l.tool=="string"&&zk.has(he(l.tool))&&qe(l.state)&&qe(l.state.input)&&Zk(l.state.input,a))}return t}function ev(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 gB(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 si(e,t,n){return e!==void 0?e:ev(et(t),n)}var qy={get disableMobileAdvertising(){return si(I().featureFlags?.disableMobileAdvertising,"NEXT_PUBLIC_DISABLE_MOBILE_ADVERTISING",!1)},get enableDinoGame(){return si(I().featureFlags?.enableDinoGame,"NEXT_PUBLIC_ENABLE_DINO_GAME",!1)},get enableProjects(){return si(I().featureFlags?.enableProjects,"NEXT_PUBLIC_ENABLE_PROJECTS",!1)},get enableAutoModel(){return!1}};var tv=new Set(["project-manager"]);function oi(e){return e.native===!0||e.mode==="subagent"||e.hidden||e.enabled===!1?!1:qy.enableProjects||!tv.has(e.name)}function yB(e){let t=e.agents.filter(oi),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function Gy(){return{projects:{list:Rt,listForAccount:Ic,get:Ct,detail:_r,create:Dc,createRepo:jc,provision:Lc,update:xr,archive:Pr,llmCatalog:br,modelPicker:Sr,modelAccess:Yr,setModelAccess:Jr,customLlmProviders:Qr,setCustomLlmProvider:Xr,deleteCustomLlmProvider:Zr,sandboxHealth:Ar,sandboxTemplates:Tu,sessions:Dt,createSession:jt},github:{linkRepository:qc,replaceProjectRepository:Gc,getInstallation:Wc,listInstallations:Hc,listLinkableInstallations:Vc,listRepositories:zc,listRepositoryBranches:Yc,linkInstallation:Qc,saveInstallation:Jc,deleteInstallation:Zc,storeUserToken:Xc},gitBackend:{get:el,repositories:tl},connectStatus:xu,marketplace:{items:o=>Sf(o),item:o=>wf(o),itemFile:(o,i)=>kf(o,i),marketplaces:()=>xf(),featured:()=>Pf(),sources:{list:()=>vf(),add:o=>Af(o),remove:o=>Rf(o)}}}}function Wy(){return{billing:{accountState:Bd,accountStateMinimal:Kd,transactions:qd,transactionsSummary:Gd,creditBreakdown:Wd,usageHistory:Hd,usageRollup:lg,sessionCosts:{list:pg,get:Hr},tierConfigurations:Vd,setPlan:ig,previewPlan:og,acceptEnterpriseOffer:ag,contactSales:cg,checkout:{createSession:n=>zd(n),confirmSession:(n,r)=>Yd(n,r)},subscription:{createPortalSession:(n,r)=>Jd(n,r),cancel:(n,r)=>Qd(n,r),reactivate:n=>Xd(n),scheduleDowngrade:(n,r,s)=>Zd(n,r,s),cancelScheduledChange:n=>eg(n),prorationPreview:(n,r)=>tg(n,r)},credits:{purchase:n=>ng(n),autoTopupSettings:n=>rg(n),configureAutoTopup:n=>sg(n)}},sandboxShares:{list:Mm,create:Om,revoke:Dm}}}var hn=class extends Error{constructor(n,r,s){super(r);this.code=n;this.status=s;this.name="HeadlessAuthError"}code;status};async function oe(e,t,n){let r=n?.fetch??I().fetch??((p,d)=>fetch(p,d)),s=pe(n?.backendUrl??I().backendUrl??"");if(!s)throw new hn("not_configured","backendUrl is not configured (configureKortix / createKortix first)",0);let o={accept:"application/json"};t.body!==void 0&&(o["content-type"]="application/json"),t.bearer&&(o.authorization=`Bearer ${t.bearer}`);let i=await r(`${Ne(s)}${e}`,{method:t.method??(t.body!==void 0?"POST":"GET"),headers:o,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...n?.signal?{signal:n.signal}:{}}),a=await i.text().catch(()=>""),l=null;try{l=a?JSON.parse(a):null}catch{l=a}if(!i.ok){let p=l&&typeof l=="object"?l:{};throw new hn(typeof p.error=="string"?p.error:"auth_error",typeof p.error_description=="string"&&p.error_description?p.error_description:typeof p.error=="string"?p.error:i.statusText||`HTTP ${i.status}`,i.status)}return l}function ii(e,t){return oe("/auth/signup",{body:e},t)}function ai(e,t){return oe("/auth/sign-in/password",{body:e},t)}function ci(e,t){return oe("/auth/sign-in/magic-link",{body:e},t)}function li(e,t){return oe("/auth/verify-otp",{body:e},t)}function ui(e,t){return oe("/auth/sign-in/oauth",{body:e},t)}function pi(e,t){return oe("/auth/oauth/exchange",{body:e},t)}function _n(e,t){return oe("/auth/refresh",{body:e},t)}function di(e,t){return oe("/auth/password/reset",{body:e},t)}function gi(e,t,n){return oe("/auth/password/update",{body:e,bearer:t},n)}function mi(e,t){return oe("/auth/user",{bearer:e},t)}function fi(e,t,n){return oe("/auth/user",{method:"PATCH",body:e,bearer:t},n)}function yi(e,t){return oe("/auth/sign-in/sso",{body:e},t)}var hi={enroll:(e,t,n)=>oe("/auth/mfa/factors",{body:e,bearer:t},n),challenge:(e,t={},n,r)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}/challenge`,{body:t,bearer:n},r),verify:(e,t,n,r)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}/verify`,{body:t,bearer:n},r),unenroll:(e,t,n)=>oe(`/auth/mfa/factors/${encodeURIComponent(e)}`,{method:"DELETE",bearer:t},n)};function _i(e,t={},n){return oe("/auth/sign-out",{body:t,bearer:e},n)}function bi(e={}){let t=e.refreshSkewSeconds??60,n=e.now??(()=>Date.now()),r=null,s=null,o=!e.storage,i=null,a=null,l=0,p=new Set,d=S=>(S.expires_at??0)*1e3,g=S=>d(S)-t*1e3<=n();async function m(){e.storage&&(r?await e.storage.set(JSON.stringify({session:r,user:s})):await e.storage.remove());for(let S of[...p])try{S(r)}catch{}try{e.onChange?.(r)}catch{}}async function f(){if(o)return r;if(!i){let S=l,v=(async()=>{let T=await e.storage.get();if(S===l&&T)try{let _=JSON.parse(T);_.session?.access_token&&_.session?.refresh_token&&(r=_.session,s=_.user??null)}catch{r=null}return o=!0,r})();i=v,v.then(()=>{i===v&&(i=null)},()=>{i===v&&(i=null)})}return i}async function h(){if(await f(),!r)return null;if(!a){let S=r.refresh_token,v=l,T=_n({refresh_token:S},e.request).then(async _=>(v!==l||(r=_.session,_.user&&(s=_.user),await m()),r)).catch(async _=>{if(v!==l)return r;let b=_&&typeof _=="object"&&"status"in _?_.status:0;if(b>=400&&b<500)return r=null,s=null,await m(),null;throw _}).finally(()=>{a===T&&(a=null)});a=T}return a}return{subscribe(S){return p.add(S),()=>{p.delete(S)}},current:()=>r,user:()=>s,load:f,async set(S,v){await f(),l+=1,a=null,r=S,v!==void 0&&(s=v),S||(s=null),await m()},async getToken(){return await f(),r?g(r)?(await h().catch(()=>r))?.access_token??null:r.access_token:null},refresh:h,async clear(){l+=1,a=null,r=null,s=null,o=!0,await m()}}}function Hy(){return{list:ac,get:lc,create:cc,secretResources:{list:Ml,create:Ol,rotate:Dl,retry:jl,remove:Ll,grant:$l,revoke:Ul,setAccess:Fl},updateName:uc,branding:{get:pc,update:dc,uploadAsset:gc,removeAsset:mc,reset:fc},leave:Rc,members:yc,invite:hc,removeMember:vc,updateMemberRole:Ac,invites:_c,cancelInvite:bc,resendInvite:Sc,tokens:{list:nf,create:rf,revoke:sf},connectedApps:{list:of,revoke:af},audit:{log:pf,export:gf,webhooks:{list:mf,create:ff,update:yf,remove:hf}}}}function Vy(){return{assignments:{list:xm,create:Pm,revoke:wm},permissions:{list:km,forRole:am},roles:{list:sm,create:lm,update:um,setPermissions:pm,remove:dm,usage:cm},groups:{list:Jg,get:Qg,create:Xg,update:Zg,remove:em,members:{list:tm,add:nm,remove:rm}},agentIdentities:om,oauthClients:{list:fm,get:ym,create:hm,update:_m,rotateSecret:bm,remove:Sm},can:gm,canBatch:mm}}function zy(){let e={signUp:ii,signInWithPassword:ai,sendMagicLink:ci,verifyOtp:li,signInWithProvider:ui,exchangeCode:pi,refresh:_n,resetPassword:di,updatePassword:gi,updateUserMetadata:fi,signInWithSso:yi,mfa:hi,user:mi,signOut:_i,session:bi},t=Hy(),n=Vy();return{auth:e,accounts:t,iam:n,accountInvites:{listMine:xc,describe:Pc,accept:co,acceptAndLand:wc,decline:kc}}}var bn=new Map,Si=new Map;function xi(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Yy(e){return bn.get(xi(e))??null}function Jy(){return[...bn.values()].filter(e=>typeof e=="string")}function Qy(e){return bn.has(xi(e))}async function ft(e){let t=xi(e),n=bn.get(t);if(n!==void 0)return n;let r=Si.get(t);if(r)return r;let s=(async()=>{try{let o=await c.get("/p/config",{showErrors:!1,errorContext:{operation:"load preview config",silent:!0}});if(!o.success)return null;let i=typeof o.data?.preview_url_template=="string"?o.data.preview_url_template:null;return bn.set(t,i),i}catch{return null}finally{Si.delete(t)}})();return Si.set(t,s),s}function Xy(e){let{apiBaseUrl:t}=e;return Qy(t)||ft(t).catch(()=>{}),{sandboxId:e.sandboxId,backendPort:e.backendPort,apiBaseUrl:t,previewUrlTemplate:Yy(t)}}function Zy(e){function t(n){try{return new URL(n)}catch{if(typeof window<"u"&&window.location?.origin)try{return new URL(n,window.location.origin)}catch{return null}throw new P(`Kortix SDK: backendUrl must be an absolute URL outside the browser (got ${JSON.stringify(n)}). Relative paths like "/api/kortix" only resolve against a page origin \u2014 configure an absolute backendUrl for server-side hosts.`,{code:"INVALID_BACKEND_URL"})}}return function(r){let s=I().backendUrl??e.backendUrl,o=80,i=t(s);return i&&(o=i.port?Number(i.port):i.protocol==="https:"?443:80),Xy({sandboxId:r,apiBaseUrl:s,backendPort:o})}}function eh(e,t){let n=null;async function r(){n||(n=Dr(e,t,{showErrors:!1}).then(s=>{let o=Nr(s)??"",i=o.indexOf("/"),a=i>0&&i<o.length-1?{providerID:o.slice(0,i),modelID:o.slice(i+1)}:void 0,l=s.agent_name?.trim()||void 0;return{model:a,agent:l}}));try{return await n}catch(s){throw n=null,s}}return{persistedPromptDefaults:r,clearPersistedDefaults:()=>{n=null}}}var Nt={url:null,sandboxId:null,dbSandboxId:null,version:0},rv=new Set;function us(e,t=null,n=null){if(!(Nt.url===e&&Nt.sandboxId===t&&Nt.dbSandboxId===n)){Nt={url:e,sandboxId:t,dbSandboxId:n,version:Nt.version+1};for(let r of rv)r()}}function th(){return Nt.url}var Sn=new Map;function nh(e){let t=`Session runtime not ready (stage: ${e?.stage??"unknown"})`,n=e?.failure,r=[];n?.category&&r.push(n.category),n?.message&&r.push(n.message);let s=n?.evidence?.error;return s&&s!==n?.message&&r.push(s),r.length===0&&e?.reason&&r.push(e.reason),r.length>0?`${t}: ${r.join(" \u2014 ")}`:t}var Bt=class extends Error{constructor(t){super(`Session runtime not ready \u2014 call \`await session.ensureReady()\` (it drives \`start()\` to completion and resolves this session's own sandbox runtime) before calling \`${t}\`.`),this.name="SessionNotReadyError"}};function rh(e,t){async function n(r){let s=Date.now()+r,o=()=>Math.max(0,s-Date.now()),i=await mt(e,t,Math.min(3e4,o()));for(;Date.now()<s&&(i==null||(i.stage==="provisioning"||i.stage==="starting")&&i.retriable);)await new Promise(d=>setTimeout(d,Math.min(1e3,o()))),i=await mt(e,t,Math.min(3e4,o()));let a=i?.runtime_session_id??i?.opencode_session_id;if(!i||i.stage!=="ready"||!i.sandbox||!a)throw new P(nh(i),{code:"RUNTIME_UNAVAILABLE"});let l=i.sandbox.external_id;if(!l)throw new P("Session sandbox has no external_id \u2014 cannot resolve its runtime URL",{code:"RUNTIME_UNAVAILABLE"});let p=Fe(l);return us(p,l),{runtimeSessionId:a,opencodeSessionId:a,runtimeUrl:p,sandboxId:l}}return n}function sh(e,t,n){let r=null;function s(){if(r)return r;let p=kd(e,t);return p&&(r=p),r}let o=rh(e,t);async function i(p){let d=s();if(d)return d;let g=p?.readyTimeoutMs??18e4,m=ft(I().backendUrl??n.backendUrl).catch(()=>null),f=p?.session?.session_id===t?Rd(p.session):null,h=f?.sandbox?.external_id,S=f?.runtime_session_id;if(h&&S){let b=Fe(h);return us(b,h),r={runtimeSessionId:S,opencodeSessionId:S,runtimeUrl:b,sandboxId:h},Br(e,t,r),await m,r}let v=`${e}
|
|
15
|
+
${t}`,T=Sn.get(v);if(T)return r=await T,await m,r;let _=o(g);Sn.set(v,_);try{return r=await _,await m,r}finally{Sn.get(v)===_&&Sn.delete(v)}}function a(p){let d=s();if(!d)throw new Bt(p);return d}function l(){r=null,vd(e,t)}return{ensureReady:i,tryResolveReady:s,requireReady:a,forgetReady:l}}var G=["directory","workspace"],oh=["messageID","model","agent","noReply","tools","format","system","variant","parts"],E=(e,t,n=G,r=[],s)=>({method:e,path:t,query:n,body:r,bodyParam:s}),sv={"session.list":E("GET","/session",[...G,"scope","path","roots","start","search","limit"]),"session.get":E("GET","/session/{sessionID}"),"session.create":E("POST","/session",G,["parentID","title","agent","model","metadata","permission","workspaceID"]),"session.delete":E("DELETE","/session/{sessionID}"),"session.update":E("PATCH","/session/{sessionID}",G,["title","metadata","permission","time"]),"session.status":E("GET","/session/status"),"session.messages":E("GET","/session/{sessionID}/message",[...G,"limit","before"]),"session.prompt":E("POST","/session/{sessionID}/message",G,oh),"session.promptAsync":E("POST","/session/{sessionID}/prompt_async",G,oh),"session.abort":E("POST","/session/{sessionID}/abort"),"session.revert":E("POST","/session/{sessionID}/revert",G,["messageID","partID"]),"session.unrevert":E("POST","/session/{sessionID}/unrevert"),"session.summarize":E("POST","/session/{sessionID}/summarize",G,["providerID","modelID","auto"]),"session.command":E("POST","/session/{sessionID}/command",G,["messageID","agent","model","arguments","command","variant","parts"]),"session.share":E("POST","/session/{sessionID}/share"),"session.unshare":E("DELETE","/session/{sessionID}/share"),"session.fork":E("POST","/session/{sessionID}/fork",G,["messageID"]),"session.diff":E("GET","/session/{sessionID}/diff",[...G,"messageID"]),"session.todo":E("GET","/session/{sessionID}/todo"),"permission.list":E("GET","/permission"),"permission.reply":E("POST","/permission/{requestID}/reply",G,["reply","message"]),"question.list":E("GET","/question"),"question.reply":E("POST","/question/{requestID}/reply",G,["answers"]),"question.reject":E("POST","/question/{requestID}/reject"),"part.update":E("PATCH","/session/{sessionID}/message/{messageID}/part/{partID}",G,[],"part"),"part.delete":E("DELETE","/session/{sessionID}/message/{messageID}/part/{partID}"),"file.list":E("GET","/file",[...G,"path"]),"file.read":E("GET","/file/content",[...G,"path"]),"find.files":E("GET","/find/file",[...G,"query","dirs","type","limit"]),"vcs.diff":E("GET","/vcs/diff",[...G,"mode","context"]),"global.health":E("GET","/global/health",[]),"global.dispose":E("POST","/global/dispose",[]),"global.config.get":E("GET","/global/config",[]),"global.config.update":E("PATCH","/global/config",[],[],"config"),"provider.list":E("GET","/provider"),"provider.auth":E("GET","/provider/auth"),"provider.oauth.authorize":E("POST","/provider/{providerID}/oauth/authorize",G,["method","inputs"]),"provider.oauth.callback":E("POST","/provider/{providerID}/oauth/callback",G,["method","code"]),"auth.set":E("PUT","/auth/{providerID}",[],[],"auth"),"app.agents":E("GET","/agent"),"app.skills":E("GET","/skill"),"app.log":E("POST","/log",G,["service","level","message","extra"]),"command.list":E("GET","/command"),"tool.ids":E("GET","/experimental/tool/ids"),"tool.list":E("GET","/experimental/tool",[...G,"provider","model"]),"mcp.status":E("GET","/mcp"),"mcp.add":E("POST","/mcp",G,["name","config"]),"mcp.connect":E("POST","/mcp/{name}/connect"),"mcp.disconnect":E("POST","/mcp/{name}/disconnect"),"mcp.auth.start":E("POST","/mcp/{name}/auth"),"mcp.auth.callback":E("POST","/mcp/{name}/auth/callback",G,["code"]),"mcp.auth.remove":E("DELETE","/mcp/{name}/auth"),"project.list":E("GET","/project"),"project.current":E("GET","/project/current"),"path.get":E("GET","/path")};function ov(e,t){let n=[];for(let r of e.query){let s=t[r];s!=null&&n.push(`${r}=${encodeURIComponent(String(s))}`)}return n.length?`?${n.join("&")}`:""}function iv(e,t,n={},r={}){let s=sv[t],o=s.path.replace(/\{(\w+)\}/g,(p,d)=>encodeURIComponent(String(n[d]))),i,a=!1;if(s.bodyParam)i=n[s.bodyParam],a=i!==void 0;else for(let p of s.body)p in n&&(i={...i,[p]:n[p]},a=!0);let l=new Headers(r.headers);return a&&l.set("Content-Type","application/json"),new Request(`${e.replace(/\/$/,"")}${o}${ov(s,n)}`,{method:s.method,headers:l,redirect:"follow",...a?{body:JSON.stringify(i)}:{},...r.signal?{signal:r.signal}:{}})}function av(e){if(!e)return"stream";let t=e.split(";")[0]?.trim()??"";return t.startsWith("application/json")||t.endsWith("+json")?"json":t==="multipart/form-data"?"formData":["application/","audio/","image/","video/"].some(n=>t.startsWith(n))?"blob":t.startsWith("text/")?"text":"json"}async function cv(e,t){let n=e.fetch??globalThis.fetch,r;try{r=await n(t)}catch(i){return{error:i||{},request:t,response:void 0}}if(r.headers.get("content-type")==="text/html")throw new Error("The session runtime does not serve this request (it answered text/html)");if(r.ok){let i=av(r.headers.get("Content-Type"));if(r.status===204||r.headers.get("Content-Length")==="0")return{data:i==="json"?{}:i==="formData"?new FormData:i==="stream"?r.body:await r[i](),request:t,response:r};if(i==="stream")return{data:r.body,request:t,response:r};if(i==="json"){let a=await r.text();return{data:a?JSON.parse(a):{},request:t,response:r}}return{data:await r[i](),request:t,response:r}}let s=await r.text(),o=s;try{o=JSON.parse(s)}catch{}return{error:o||{},request:t,response:r}}function Pi(e=globalThis.fetch){return async function*({url:t,headers:n,signal:r}){let s=await e(new Request(t,{method:"GET",headers:n,signal:r,redirect:"follow"}));if(!s.ok)throw Object.assign(new Error(`SSE failed: ${s.status} ${s.statusText}`),{status:s.status});if(!s.body)throw new Error("No body in SSE response");let o=s.body.pipeThrough(new TextDecoderStream).getReader(),i=()=>{try{o.cancel().catch(()=>{})}catch{}};r.addEventListener("abort",i);try{let a="";for(;;){let{done:l,value:p}=await o.read();if(l)break;a=(a+p).replace(/\r\n/g,`
|
|
16
16
|
`).replace(/\r/g,`
|
|
17
17
|
`);let d=a.split(`
|
|
18
18
|
|
|
19
|
-
`);a=d.pop()??"";for(let g of d){let m={},f=[];for(let
|
|
20
|
-
`))if(
|
|
21
|
-
`)),yield m}}}finally{r.removeEventListener("abort",i),s.releaseLock()}}}async function*sv(e,t,n){let r=e.eventTransport??xi(e.fetch??globalThis.fetch),o=n.signal??new AbortController().signal,s=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!o.aborted;a++)try{let l=new Headers(n.headers);i!==void 0&&l.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:l,signal:o}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(s=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(l){if(n.onSseError?.(l),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(s*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function Sn(e){let t=o=>(s,i)=>ov(e,nv(e.baseUrl,o,s,i)),n=o=>s=>t(o)(void 0,s);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(o={})=>({stream:sv(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,o)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var ih=200;async function iv(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function rt(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new S(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function ah(e){let t=e.runtimeUrl.replace(/\/$/,""),n=Sn({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let o=encodeURIComponent(r.conversationId??e.rootId),s=async(l,p)=>{let d=new URLSearchParams;l!==void 0&&d.set("limit",String(l)),p&&d.set("before",p);let g=`/messages/${o}${d.size?`?${d}`:""}`,m=y=>e.fetch(new Request(`${t}${y}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new S(`Reading the session transcript failed: ${await iv(f)}`,{status:f.status,response:f});let _=await f.json();return{messages:_.messages??[],hasMore:_.has_more===!0}},i=await s(r.limit===void 0?void 0:Math.min(r.limit,ih),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await s(Math.min(r.limit-a.length,ih),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,o,s]=await Promise.all([n.session.status().then(i=>rt(i,"Reading the session status failed")),n.permission.list().then(i=>rt(i,"Reading permission requests failed")),n.question.list().then(i=>rt(i,"Reading questions failed"))]);return{statuses:r??{},permissions:o??[],questions:s??[]}},answerPermission:async(r,o,s)=>{rt(await n.permission.reply({requestID:r,reply:o,...s!==void 0?{message:s}:{}}),"Answering the permission request failed")},answerQuestion:async(r,o)=>{if(o===null){rt(await n.question.reject({requestID:r}),"Dismissing the question failed");return}rt(await n.question.reply({requestID:r,answers:o}),"Answering the question failed")},compact:async r=>{let o=r;if(!o){let a=await n.global.config.get().then(d=>d.error===void 0?d.data:null),l=typeof a?.model=="string"?a.model:"",p=l.indexOf("/");p>0&&p<l.length-1&&(o={providerID:l.slice(0,p),modelID:l.slice(p+1)})}if(!o)throw new S("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});let i=rt(await n.session.status(),"Reading the session status failed")?.[e.rootId];if(i&&i.type!=="idle")throw new S("This session is busy. Wait for the current turn to finish, then run compact again.",{code:"SESSION_BUSY",status:409});return rt(await n.session.summarize({sessionID:e.rootId,providerID:o.providerID,modelID:o.modelID}),"Compacting the session failed"),o}}}function ch(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return ah({runtimeUrl:r,rootId:n,fetch:$})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,o)=>(await t()).answerPermission(n,r,o),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function lh(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await ld(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var xn=BigInt(4096),ot=BigInt(0xffffffffffff),uh=ot+BigInt(1),av=uh/BigInt(2),yt=BigInt(3600*1e3)*xn,wi=120*1e3,cv=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,lv=/^msg_([0-9a-f]{12})/,ph="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Kt(e){let t=lv.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function wn(e){return BigInt(Math.trunc(e))*xn&ot}function qt(e,t){let n=e-t&ot;return n>=av&&(n-=uh),n}function dh(e){let t=null;for(let n of e)n!=null&&(t===null||qt(n,t)>BigInt(0))&&(t=n);return t}function uv(e,t){let n=Kt(e);return n===null?!1:qt(n,wn(t))>yt}function pv(e,t){let n=t===void 0?null:wn(t);return gh(e,r=>n===null||qt(r,n)<=yt)}function gh(e,t){let n=[];for(let r of e){let o=Kt(r);o!==null&&t(o)&&n.push(o)}return dh(n)}function dv(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=ph[n%62])}return e}function mh(e){let t=e.random,n=wn(e.nowMs-(e.backdateMs??wi)),r=e.newestKnownTime??null;if(r!==null){let s=qt(r,n);s>=BigInt(0)&&s<=yt&&(n=r+BigInt(1)&ot)}let o="";if(t)for(let s=0;s<14;s++)o+=ph[Math.min(61,Math.floor(t()*62))];else o=dv();return{id:`msg_${n.toString(16).padStart(12,"0")}${o}`,time:n}}function ki(e={}){let t=e.nowMs??Date.now(),n=wn(t-wi),r=gh(e.after??[],o=>{let s=qt(o,n);return s>=BigInt(0)&&s<=yt});return mh({nowMs:t,newestKnownTime:r}).id}function fh(e){return{scope:()=>ad(e.projectId,e.sessionId),providerSecretPool:{list:()=>Kl(e.projectId,e.sessionId),get:t=>Bl(e.projectId,e.sessionId,t),set:(t,n)=>ql(e.projectId,e.sessionId,t,n)},rescope:t=>cd(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,o=n?.agent??e.agent,s=r&&o?{}:await e.persistedPromptDefaults(),i=r??s.model,a=o??s.agent,l=ki(),p=await jr(e.projectId,e.sessionId,{clientMessageId:l,messageId:l,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new S("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var yh=async function*(e){let t=C().eventStreamTransport;if(!t){yield*xi(((o,s)=>$(o,s,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await vt(e.url,e.headers);try{yield*t({...e,headers:n})}catch(o){throw o?.status===401&&r(),o}};function Ge(){let e=th();return e||(C().billingEnabled??!1?"":Rd())}async function vi(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Ai(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function hh(e){let t=Ai(e),n=await $(`${t}/env`);if(!n.ok)throw new Error(await vi(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function _h(e,t,n){let r=Ai(e),o=await $(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!o.ok)throw new Error(await vi(o,"Failed to save secret"))}async function bh(e,t){let n=Ai(e),r=await $(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await vi(r,"Failed to delete secret"))}var gv={list:hh,set:_h,delete:bh};async function mv(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let o=await $(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),s=await o.json();if(!o.ok)throw new Error(s?.error||s?.message||`Request failed with ${o.status}`);return s}async function uo(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function kn(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return ue(e)}async function Ph(e){let t=kn(e),n=await $(`${t}/kortix/pty`);if(!n.ok)throw new Error(await uo(n,"Failed to list terminals"));return n.json()}async function Sh(e,t){let n=kn(e),r=await $(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await uo(r,"Failed to create terminal"));return r.json()}async function xh(e,t,n){let r=kn(e),o=await $(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(await uo(o,"Failed to update terminal"));return o.json()}async function wh(e,t){let n=kn(e),r=await $(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await uo(r,"Failed to remove terminal"))}async function kh(e,t,n){let r=kn(t),s=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),ue(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await on();a&&i.set("token",a),n?.wake&&i.set("wake","1");let l=i.toString();return l?`${s}${s.includes("?")?"&":"?"}${l}`:s}function fv(e){let t=e.reason.trim().toLowerCase();return t.includes("pty not found")?"replace":t.includes("pty exited")?"ended":e.hadError||t.includes("idle timeout")||t.includes("upstream error")||e.code!==1e3?"reconnect":"ended"}var st="\x1B",vh="\x07",yv="\0",Ri=`(?:${vh}|${st}\\\\)`,hv=[new RegExp(`${st}\\]697;[^${vh}${st}]*${Ri}`,"g"),new RegExp(`${yv}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${st}\\][0-9]+;rgb:[0-9a-fA-F/]+${Ri}`,"g"),new RegExp(`${st}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Ri}`,"g"),new RegExp(`${st}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${st}\\[\\d+;\\d+R`,"g"),new RegExp(`${st}\\[\\?[0-9;]*c`,"g")];function _v(e){let t=e;for(let n of hv)t=t.replace(n,"");return t}var bv={list:Ph,create:Sh,update:xh,remove:wh,webSocketUrl:kh};async function O(e,t,n,r){let o=e;for(;o.endsWith("/");)o=o.slice(0,-1);let s=await $(`${o}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await s.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!s.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${s.status}`);return a}async function RK(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return O(e,`/kortix/tasks${r}`)}async function CK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function TK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function IK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function EK(e,t){return O(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function MK(e,t,n){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function OK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function DK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function LK(e,t){return O(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function jK(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return O(e,`/kortix/tickets${n}`)}async function $K(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function UK(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function FK(e,t){return O(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function NK(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function BK(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function KK(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function qK(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function GK(e,t,n){return O(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function WK(e,t){return O(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function HK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function VK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function zK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function YK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function JK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function QK(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function XK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function ZK(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function eq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function tq(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function nq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function rq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function oq(e,t,n=200){return O(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function sq(e){return O(e,"/kortix/projects")}async function iq(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function aq(e,t){return O(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function cq(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function lq(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function uq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function pq(e,t,n="all"){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function dq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function gq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function mq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function fq(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function yq(e,t,n,r){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function hq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function _q(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function bq(e,t){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function Pq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function Sq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function xq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function wq(e,t,n){return O(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var Pv=1e4,Sv={retryOnAuthError:!1};function Gt(e,t,n){return O(e,t,{signal:AbortSignal.timeout(Pv),...n},Sv)}async function kq(e,t=!1){return(await Gt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function vq(e){return(await Gt(e,"/kortix/services/templates")).templates??[]}async function Aq(e,t){return(await Gt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function Rq(e,t,n){let r=n==="delete",o=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return Gt(e,o,{method:r?"DELETE":"POST"})}async function Cq(e,t){return Gt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function Tq(e,t){return Gt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var We=new Map,xv=256,vn=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function ht(){let e=Ge();if(!e)throw new vn;return He(e)}function He(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=We.get(e);if(t)return We.delete(e),We.set(e,t),t;if(!es())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=Sn({baseUrl:e,fetch:$,eventTransport:yh});return We.set(e,n),We.size>xv&&We.delete(We.keys().next().value),n}function $q(e){We.delete(e)}function Uq(){We.clear()}var po=new Map;function Fq(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=po.get(e);if(t)return t;let n=Sn({baseUrl:e,fetch});return po.set(e,n),n}function Nq(e){po.delete(e)}function Bq(){po.clear()}async function wv(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n?.error||n?.message||t||e.statusText||`HTTP ${e.status}`}catch{return t||e.statusText||`HTTP ${e.status}`}}async function Kq(e){let t=Ge();if(!t)throw new S("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await $(`${t}${n}`,{method:"POST"}),o=r.headers.get("content-type")??"",s=/^application\/([\w.+-]+\+)?json\b/i.test(o.trim());if(!r.ok)throw new S(`System reload failed (${r.status}): ${await wv(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!s)throw new S(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(l){throw new S(`System reload returned malformed JSON from ${n}: ${l instanceof Error?l.message:String(l)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var Ah="frontend";function go(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Ah}] ${t}`,...n?[n]:[]);try{ht().app.log({service:Ah,level:e,message:t,extra:n})}catch{}}var Ve={debug:(e,t)=>go("debug",e,t),info:(e,t)=>go("info",e,t),warn:(e,t)=>go("warn",e,t),error:(e,t)=>go("error",e,t)};var kv=16,vv=8,Rh=6e4,Av=250,Rv=1e3,Cv=3e4,Tv=5,Iv=.5,Ev=3e3,Mv=3e4,Ch=2e4,Ov=2e3,Th=8;function Dv(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function Lv(e,t){if(!e||e.type!==t.type)return;if(t.type==="message.part.delta"){let s=e.properties,i=t.properties;if(s.partID!==i.partID||s.field!==i.field||s.messageID!==i.messageID||s.sessionID!==i.sessionID)return}else if(t.type==="log.block.delta"){let s=e.properties,i=t.properties;if(typeof s.delta!="string"||typeof i.delta!="string"||s.thread_id!==i.thread_id||s.message_id!==i.message_id||s.block_id!==i.block_id)return}else return;let n=e.properties,r=t.properties,o=e.coalesced??[e];return o.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:o}}function Ih(e,t){let n=[],r,o=0,s=new Map,i=()=>{if(r&&e.clearTimeout(r),r=void 0,n.length===0)return;let l=n;n=[],s.clear(),o=e.now();for(let p of l)p&&t(p.event)},a=()=>{if(r)return;let l=e.now()-o;r=e.setTimeout(i,Math.max(0,kv-l))};return{push(l){let p=Lv(n[n.length-1]?.event,l);if(p)n[n.length-1]={type:p.type,event:p};else{let d=Dv(l);if(d){let g=s.get(d);g!==void 0&&(n[g]=void 0),s.set(d,n.length)}n.push({type:l.type,event:l})}a()},flush:i,clearTimer:()=>{r&&e.clearTimeout(r)}}}function Eh(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}function Ci(e,t,...n){for(let r of e){let o=t(r);if(o)try{o(...n)}catch(s){console.warn("[opencode-events] subscriber handler threw, skipping",s)}}}async function jv(e,t,n,r){return new Promise((o,s)=>{let i=!1,a=t.setTimeout(()=>{i||(i=!0,Ve.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:n}),r.abort(),s(new Error(`SSE connect timed out after ${n}ms`)))},n);e.global.event({signal:r.signal,sseDefaultRetryDelay:Ev,sseMaxRetryDelay:Mv,sseMaxRetryAttempts:1}).then(l=>{i||(i=!0,t.clearTimeout(a),o(l))},l=>{i||(i=!0,t.clearTimeout(a),s(l))})})}async function $v(e,t,n,r,o){let s=!1,i=t.now(),a=e[Symbol.asyncIterator]();for(;!n.aborted;){let l=a.next().then(f=>({kind:"next",result:f}),f=>({kind:"error",error:f})),p=Eh(n),d=await Promise.race([l,p.promise.then(()=>({kind:"aborted"}))]);if(p.cleanup(),d.kind==="aborted")break;if(d.kind==="error")throw d.error;if(d.result.done)break;o();let g=d.result.value,m=g&&typeof g=="object"&&"payload"in g?g.payload:g;m?.type&&(m.type!=="server.connected"&&(s=!0),r.push(m),!(t.now()-i<vv)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return s}function Mh(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<Ov)}function Oh(e,t,n){Ve.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),Ci(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function Dh(e,t,n){let r=t?Av:Math.min(Rv*2**Math.min(e-1,Tv),Cv);return Math.round(r*(1+Iv*(n.random?.()??0)))}function Lh(e,t,n){return new Promise(r=>{let o=e.setTimeout(r,n),s=()=>{e.clearTimeout(o),r()};t.addEventListener("abort",s,{once:!0})})}async function jh(e){let{client:t,t:n,connectTimeoutMs:r,heartbeatTimeoutMs:o,outerSignal:s,retryCount:i,setConnectionState:a,onConnected:l,coalescer:p}=e,d=!1,g=!1,m,f=null,_=new AbortController;a("connecting");let y=Eh(s);y.promise.then(()=>_.abort());try{let{stream:k}=await jv(t,n,r,_);l();let R=()=>{n.clearTimeout(m),m=n.setTimeout(()=>{Ve.warn("SSE heartbeat timeout, forcing reconnect"),_.abort()},o)};R(),d=await $v(k,n,_.signal,p,()=>{a("open"),R()}),g=d}catch(k){if(f=k,s.aborted)return{streamHadWork:d,stableConnection:g,error:f};let R=String(k),I=tn(k)||tn(k?.cause);if(Ve.error("SSE event stream error",{error:R,retryCount:i,isAuthError:I}),I)try{ms(),await gs(),Ve.info("SSE: refreshed auth token after auth error")}catch(b){Ve.error("SSE: failed to refresh auth token",{error:String(b)})}}finally{n.clearTimeout(m),_.abort(),y.cleanup(),p.flush()}return{streamHadWork:d,stableConnection:g,error:f}}function Uv(e){return{type:"heartbeat-gap",gapMs:e}}function Fv(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 Nv={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},Bv=5e3,Kv=1e4,qv=4,An=new WeakMap;function Gv(e,t,n){let r=t.timers??Nv,o=t.connectTimeoutMs??Ch,s=t.heartbeatTimeoutMs??Rh,i=t.maxConsecutiveHardFailures??Th,a=new AbortController,l=(k,...R)=>Ci(n,k,...R),p=null,d=!1,g=k=>{p!==k&&(p=k,k&&l(R=>R.onConnectionChange,k))},m=r.now(),f=null,_=Ih(r,k=>{m=r.now(),l(R=>R.onEvent,k)}),y={client:e,t:r,connectTimeoutMs:o,heartbeatTimeoutMs:s,outerSignal:a.signal,setConnectionState:g,onConnected:()=>{if(f){let k=r.now()-f.lastActivityAt,R=f.eventful;f=null,(R||k>Bv)&&l(I=>I.onGapRehydrate,k)}m=r.now()},coalescer:_};return(async()=>{let k=0,R=0,I=0;for(;!a.signal.aborted;){let b=r.now(),M=await jh({...y,retryCount:k});if(a.signal.aborted)break;let h=M.error,{streamHadWork:x,stableConnection:P}=M,v=r.now()-b;if(R=Mh(x,h,v)?R+1:0,R>=i){Oh(n,R,h),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||x},I=P&&v<Kv?I+1:0;let w=P&&I<=qv;w?k=0:(k++,k>1&&Ve.warn("SSE event stream reconnecting",{retryCount:k})),await Lh(r,a.signal,Dh(k,w,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),_.clearTimer()}}}function Ti(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o,signal:s}=e,i=e.client??(e.url?He(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:o},l=An.get(i);if(l?.isParked()&&(An.delete(i),l=void 0),!l)l=Gv(i,e,new Set([a])),An.set(i,l);else{l.subscribers.add(a);let f=l.connectionState();f&&o?.(f)}let p=l,d=!1,g=()=>{d||(d=!0,s&&s.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),An.get(i)===p&&An.delete(i)))},m=()=>g();return s&&(s.aborted?g():s.addEventListener("abort",m,{once:!0})),{close:g}}function $h(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return He(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return He(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return He(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return Ti({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Fh(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new S(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Mi(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function ae(e){let t=(e??Ge()).trim();if(!t)throw new vn;return t}async function En(e,t){let n=await $(`${ae(t)}${e}`);if(!n.ok)throw new S(await Mi(n),{status:n.status,response:n});return n.json()}async function Oi(e,t,n,r,o){let s=await $(`${ae(o)}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new S(`${r} failed (${s.status}): ${await Mi(s)}`,{status:s.status,response:s});return s.json()}var Di=["/workspace","/tmp","/home","/opt"],Wv=Di.filter(e=>e!=="/workspace");function Nh(e){return Di.some(t=>e===t||e.startsWith(`${t}/`))}function Mn(e){return Nh(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function _t(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(Wv.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Bh=_t;async function On(e,t){let n=ae(t),r=_t(e)||".";return(await En(`/file?path=${encodeURIComponent(r)}`,n)).map(s=>({...s,path:s.absolute||`/workspace/${s.path}`}))}async function Dn(e,t){let n=_t(e);return En(`/file/content?path=${encodeURIComponent(n)}`,t)}async function Hv(e,t,n){let r=ae(n),o=_t(e),s=await $(`${r}/file/raw?path=${encodeURIComponent(o)}`);if(!s.ok)throw new S(await Mi(s),{status:s.status,response:s});if((s.headers.get("content-type")||"").includes("text/html"))throw new S("File could not be loaded (raw byte route unavailable)",{status:s.status,response:s,code:"INVALID_CONTENT_TYPE"});let i=await s.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var Vv=8,mo=0,Kh=[];async function zv(){if(mo<Vv){mo++;return}await new Promise(e=>Kh.push(e)),mo++}function Yv(){mo--,Kh.shift()?.()}function Jv(e,t){let n=ae(t);return Ar(`${n}/file/raw?path=${encodeURIComponent(_t(e))}`)}async function Ln(e,t){await zv();try{let n=ae(t);try{return await Hv(e,void 0,n)}catch{}let r=await Dn(e,n);if(r.encoding==="base64"&&r.content){let o=Uint8Array.from(atob(r.content),s=>s.charCodeAt(0));return new Blob([o],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{Yv()}}async function fo(e){return En("/file/status",ae(e))}async function yo(e,t,n){let r=ae(n),o=new URLSearchParams({query:e});return t?.type&&o.set("type",t.type),t?.limit&&o.set("limit",String(t.limit)),En(`/find/file?${o.toString()}`,r)}async function ho(e,t){let n=ae(t);return(await En(`/find?pattern=${encodeURIComponent(e)}`,n)).map(o=>({path:typeof o.path=="string"?o.path:o.path?.text??"",lines:typeof o.lines=="string"?o.lines:o.lines?.text??"",line_number:o.line_number,absolute_offset:o.absolute_offset,submatches:(o.submatches??[]).map(s=>({start:s.start,end:s.end}))}))}var Rn=[400,1200],Qv=e=>e===408||e===429||e===502||e===503||e===504,Uh=e=>new Promise(t=>setTimeout(t,e));function Xv(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Ii=3e4,qh=15*6e4,Zv=256;function Cn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Ii;let t=Ii+e/Zv;return Math.min(qh,Math.max(Ii,Math.round(t)))}async function eA(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function Tn(e,t){let n;for(let o=0;o<=Rn.length;o++){let s;try{s=await t(e())}catch(a){if(n=a,Xv(a)||o===Rn.length)break;await Uh(Rn[o]);continue}if(s.ok)return s.json();let i=await eA(s);if(n=new S(`Upload failed (${s.status}): ${i}`,{status:s.status,response:s}),!Qv(s.status)||o===Rn.length)throw n;await Uh(Rn[o])}if(n instanceof S)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new S(`Upload failed: ${r}`)}var Ei=8*1024*1024;function tA(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new S(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Gh(e,t){try{e?.onProgress?.(t)}catch{}}function Wh(e,t,n){let r=new FormData,o=(t??"").trim();return o&&r.append("path",o.startsWith("/")?o:`/${o}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function nA(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function jn(e,t,n,r,o){let s=typeof r=="string"?r:void 0,i=typeof r=="string"?o:r,a=ae(s),l=Cn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Ei){let d=await Tn(()=>Wh(e,t,p),g=>$(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:l}));return tA(d[0],e.size),Gh(i,{loadedBytes:e.size,totalBytes:e.size}),d}return rA(e,t,p,a,i)}async function rA(e,t,n,r,o){let i=(await Tn(()=>Wh(new Blob([],{type:e.type}),t,n),l=>$(`${r}/file/upload`,{method:"POST",body:l},{timeoutMs:Cn(0)})))[0]?.path;if(!i)throw new S("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=nA(i);if(!a.name)throw new S(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let l=0;l<e.size;l+=Ei){let p=Math.min(e.size,l+Ei),d=e.slice(l,p,e.type),g=await Tn(()=>{let m=new FormData;return a.parent&&m.append("path",a.parent),m.append("filename",a.name),m.append("first",l===0?"true":"false"),m.append("offset",String(l)),m.append("file",d,a.name),m},m=>$(`${r}/file/append`,{method:"POST",body:m},{timeoutMs:Cn(d.size)}));if(g.path!==i||g.size!==p)throw new S(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Gh(o,{loadedBytes:p,totalBytes:e.size})}}catch(l){throw await Wt(i,r).catch(()=>{}),l}return[{path:i,size:e.size}]}function oA(e,t,n){let r=ae(n);return Tn(()=>{let o=new FormData;return t&&o.append("path",t),o.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),o},o=>$(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:sA}))}var sA=qh;function iA(e,t,n){let r=ae(n),o=Cn(t.size);return Tn(()=>{let s=new FormData;return s.append(e,t,e.split("/").pop()||"file"),s},s=>$(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:o}))}var In=class extends S{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function _o(e,t){let n=ae(t),r=e.trim(),s=(r.startsWith("/")?r:`/${r}`).split("/"),i=s.pop()||"untitled",a=s.join("/")||"/workspace",l=Mn(`${a}/${i}`),p=[];try{p=await On(Hh(l),n)}catch(g){if(!(g instanceof S&&g.status===404))throw g}if(p.some(g=>g.name===Vh(l)))throw new In(l);let d=await zh(l,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function bo(e,t,n){let r=ae(n);return iA(t,await Ln(e,r),r)}function aA(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Hh(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Vh(e){return e.slice(e.lastIndexOf("/")+1)}function cA(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function Po(e,t,n){let r=ae(n),o=Mn(aA(e.trim()));return zh(o,t,r,{overwrite:!0})}async function zh(e,t,n,r){let o=Vh(e);if(!o)throw new S(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let s=Hh(e);await $n(s,n).catch(()=>{});let i=cA(),a=await jn(t,s,`.${o}.kortix-write-${i}`,n),l=a[0]?.path;if(!l)throw new S(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=Mn(l);try{await Yh(p,e,n,r.overwrite)}catch(g){throw await Wt(p,n).catch(()=>{}),!r.overwrite&&g instanceof S&&g.status===409?new In(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Wt(e,t){return Oi("/file","DELETE",{path:e},"Delete",t)}async function $n(e,t){return Oi("/file/mkdir","POST",{path:e},"Mkdir",t)}async function So(e,t,n){return Yh(e,t,ae(n),!0)}async function Yh(e,t,n,r){return Oi("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function Jh(){return Fh(await ht().project.current())}async function Li(){return Fh(await ht().global.health())}async function Qh(){try{return(await Li()).healthy===!0}catch{return!1}}var lA={list:On,read:Dn,readBlob:Ln,status:fo,findFiles:yo,findText:ho,upload:jn,write:Po,create:_o,copy:bo,remove:Wt,mkdir:$n,rename:So,currentProject:Jh,health:Li,isReachable:Qh,toDaemonPath:_t,toSandboxAbsolutePath:Mn,toWorkspaceRelative:Bh};function Xh(e){return{list:async t=>On(t,(await e()).runtimeUrl),read:async t=>Dn(t,(await e()).runtimeUrl),readBlob:async t=>Ln(t,(await e()).runtimeUrl),status:async()=>fo((await e()).runtimeUrl),findFiles:async(t,n)=>yo(t,n,(await e()).runtimeUrl),findText:async t=>ho(t,(await e()).runtimeUrl),upload:async(t,n,r,o)=>jn(t,n,r,(await e()).runtimeUrl,o),write:async(t,n)=>Po(t,n,(await e()).runtimeUrl),create:async t=>_o(t,(await e()).runtimeUrl),copy:async(t,n)=>bo(t,n,(await e()).runtimeUrl),remove:async t=>Wt(t,(await e()).runtimeUrl),mkdir:async t=>$n(t,(await e()).runtimeUrl),rename:async(t,n)=>So(t,n,(await e()).runtimeUrl)}}function Zh(e){return{get:t=>Or(e.projectId,e.sessionId,t),presence:(t,n)=>c.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>Wr(e.sessionId,{projectId:e.projectId}),update:t=>ed(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),td(e.projectId,e.sessionId)),restore:()=>rd(e.projectId,e.sessionId),recover:()=>nd(e.projectId,e.sessionId),start:(...t)=>mt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Id(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),$r(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Ur(e.projectId,e.sessionId)),configState:()=>od(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),sd(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),id(e.projectId,e.sessionId,...t)),setSharing:t=>Op(e.projectId,e.sessionId,t),previews:()=>Fp(e.projectId,e.sessionId),participants:()=>Dp(e.projectId,e.sessionId),watch:()=>Lp(e.projectId,e.sessionId),setWatch:t=>jp(e.projectId,e.sessionId,t),setPinned:t=>$p(e.projectId,e.sessionId,t),setArchived:t=>Up(e.projectId,e.sessionId,t),commit:t=>dp(e.projectId,e.sessionId,t),publicShares:{list:()=>Np(e.projectId,e.sessionId),create:(...t)=>Bp(e.projectId,e.sessionId,...t),revoke:(...t)=>Kp(e.projectId,e.sessionId,...t)}}}function e_(e){return{reminders:{list:()=>Um(e.projectId,e.sessionId),create:t=>Fm(e.projectId,e.sessionId,t),update:(t,n)=>$s(e.projectId,e.sessionId,t,n),remove:t=>Us(e.projectId,e.sessionId,t)},audit:(t,n)=>Wp(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Ny(e.projectId,e.sessionId,t,n),read:(t,n)=>By(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Hp(e.projectId,e.sessionId,t),messageAuthors:()=>ud(e.projectId,e.sessionId),modelUsage:()=>pd(e.projectId,e.sessionId),transcriptSync:t=>Dr(e.projectId,e.sessionId,t),log:t=>Vp(e.projectId,e.sessionId,t),turn:()=>Lr(e.projectId,e.sessionId),prompts:{create:t=>jr(e.projectId,e.sessionId,t),list:()=>zp(e.projectId,e.sessionId),remove:t=>Yp(e.projectId,e.sessionId,t),retry:t=>Xp(e.projectId,e.sessionId,t),edit:(t,n)=>Jp(e.projectId,e.sessionId,t,n),interrupt:t=>Qp(e.projectId,e.sessionId,t),hold:t=>Zp(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function pA(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var dA=["control_plane","provider_ingress","daemon","upstream_port"];function t_(e){return typeof e=="string"&&dA.includes(e)?e:null}function n_(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.harness?e.harness.ready===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function r_(e,t){let n=(e===void 0?Ge():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await $(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),o=await r.text().catch(()=>""),s=null;try{s=o?JSON.parse(o):null}catch{s=null}let i=s,a=t_(r.headers.get("X-Kortix-Proxy-Hop"))??t_(s?.hop),l=Number(r.headers.get("X-Kortix-Upstream-Status")),p=s?.upstream_status,d=Number.isFinite(l)&&l>0?l:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:o,hop:a,upstreamStatus:d}}var o_=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,s_=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,i_=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,a_=new Set([22,4096,parseInt(tt.KORTIX_MASTER,10)]);function gA(e){return s_.test(e)}function xo(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 mA(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var fA=new Set(["'",'"',"`","<","(","["]),yA=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function hA(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&&fA.has(e[t]);)t++;for(;n>t&&yA.has(e[n-1]);)n--;return e.slice(t,n)}function _A(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var bA=/^\/proxy\/(\d{1,5})(\/.*)?$/,PA=/^\/(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 SA(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:PA.test(t.pathname)}catch{return!1}}function wo(e){if(!e)return null;let t=hA(mA(e.trim())),n=d_(t);if(n){let r=xo(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let o=parseInt(r.port,10);if(!Number.isInteger(o)||o<1||o>65535)return null;let s=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(tt.KORTIX_MASTER,10);if(o===i){let l=r.pathname.match(bA);if(l){let p=parseInt(l[1],10);if(p>=1&&p<=65535)return o=p,s=xo(`${l[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${o}${s}`,port:o,path:s}}}let a=xo(s);return{originalUrl:`${r.protocol}//${r.hostname}:${o}${a}`,port:o,path:a}}catch{let r=_A(e);return r&&r!==e?wo(r):null}}function xA(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let o=/`[^`\n]+`/g;for(;(r=o.exec(e))!==null;){let s=r.index,i=s+r[0].length;t.some(([l,p])=>s>=l&&i<=p)||t.push([s,i])}return t}function wA(e,t){return t.some(([n,r])=>e>=n&&e<r)}function kA(e){let t=[],n=new Set,r=xA(e);o_.lastIndex=0;let o;for(;(o=o_.exec(e))!==null;){let s=wo(o[0]);if(!s)continue;let{originalUrl:i,port:a,path:l}=s;a<1||a>65535||a_.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:l,startIndex:o.index,endIndex:o.index+i.length,inCodeBlock:wA(o.index,r)}))}return t}function xG(e){return kA(e).length>0}function vA(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function c_(e){return e.trim().toLowerCase().split("_").join("-")}function l_(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function AA(e,t,n){let r=n.previewUrlTemplate;if(!r||!r.includes("{port}")||!r.includes("{sandbox}"))return null;let o=r.split("{port}").join(String(e)).split("{sandbox}").join(c_(n.sandboxId));return`${l_(o)}${t}`}function RA(e){return e.sandboxId.trim().length>0}function bt(e,t,n){let r=xo(t);if(!RA(n))return EA(e,r);let o=AA(e,r,n);return o||(vA(n.apiBaseUrl)?`http://p${e}-${c_(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${l_(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function wG(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(o=>encodeURIComponent(o)).join("/");return bt(3211,`/open?path=/workspace/${r}`,t)}function CA(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function kG(e){return`http://localhost:3211${CA(e)}`}function TA(){return"/health"}function vG(e){return bt(3211,TA(),e)}function AG(e,t){return bt(e,"/",t)}function IA(e){let t=wo(e);return!(!t||a_.has(t.port)||SA(e))}function u_(e,t){if(!e)return e;let n=wo(e);return n?IA(n.originalUrl)?bt(n.port,n.path,t):n.originalUrl:e}function EA(e,t="/"){return`http://localhost:${e}${t}`}var p_=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function d_(e){let t=e.match(s_);if(t)return{port:parseInt(t[1],10),sandboxId:t[2],backendPort:t[3]?parseInt(t[3],10):80,path:t[4]||"/"};let n=e.match(i_);if(n){let o=443;try{let s=new URL(e);o=s.port?parseInt(s.port,10):s.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:o,path:n[4]||"/"}}let r=e.match(p_);if(r)try{let o=new URL(e);return{port:parseInt(r[2],10),sandboxId:r[1],backendPort:parseInt(o.port,10)||(o.protocol==="https:"?443:80),path:r[3]||"/"}}catch{return null}return null}function RG(e){try{let t=d_(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function CG(e){return gA(e)||i_.test(e)||p_.test(e)}function TG(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Un="/web-proxy/";function IG(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),o=`${Un}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,s=parseInt(tt.KORTIX_MASTER,10);return`${bt(s,"/",t).replace(/\/$/,"")}${o}`}catch{return null}}function EG(e){try{let t=new URL(e),n=t.pathname.indexOf(Un);if(n===-1)return null;let o=t.pathname.slice(n+Un.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!o)return null;let s=o[1],i=o[2],a=o[3]||"/";return`${s}://${i}${a}${t.search}${t.hash}`}catch{return null}}function MG(e){try{return new URL(e).pathname.includes(Un)}catch{return e.includes(Un)}}function OG(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 DG(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t)?`https://${t}`:null:null}function g_(e){return{health:t=>r_(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>bt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>u_(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Fe(e.requireReady("sandboxPortUrl").sandboxId,t)}}function ji(e,t,n,r){let o,s,{persistedPromptDefaults:i,clearPersistedDefaults:a}=eh(e,t),{ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g}=oh(e,t,n),m={projectId:e,sessionId:t,ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return o},set model(f){o=f},get agent(){return s},set agent(f){s=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...Zh(m),...e_(m),...g_(m),...lh(m),...fh(m),...$h(m),files:Xh(l),...ch(m),get runtime(){return He(d("runtime").runtimeUrl)}}}function m_(e){return{apps:{list:()=>Cf(e),create:t=>Tf(e,t),get:t=>Bs(e,t),update:(...t)=>If(e,...t),access:{get:(...t)=>Df(e,...t),update:(...t)=>jf(e,...t),session:(...t)=>$f(e,...t),agents:t=>Lf(e,t)},remove:t=>Ef(e,t),token:t=>Mf(e,t),authEnv:t=>Of(e,t),artifacts:{register:t=>Ks(e,t),uploadArchive:(...t)=>Uf(e,...t),finalize:(...t)=>qs(e,...t)},deployments:{create:(...t)=>Ff(e,...t),list:t=>Nf(e,t),get:(...t)=>Bf(e,...t),logs:(...t)=>Kf(e,...t),remove:(...t)=>Wf(e,...t)},start:t=>qf(e,t),stop:t=>Gf(e,t),rollback:(...t)=>Hf(e,...t),machines:{list:t=>Vf(e,t),start:(t,n)=>zf(e,t,n),stop:(t,n)=>Yf(e,t,n),restart:(t,n)=>Jf(e,t,n),destroy:(t,n)=>Qf(e,t,n)},scale:(...t)=>Xf(e,...t),exec:(...t)=>Zf(e,...t),volumes:{list:t=>ey(e,t),create:(...t)=>ty(e,...t),update:(...t)=>ny(e,...t),destroy:(...t)=>ry(e,...t),snapshots:(...t)=>oy(e,...t),snapshot:(...t)=>sy(e,...t),restore:(...t)=>iy(e,...t),fork:(...t)=>ay(e,...t)}}}}function f_(e){return{list:()=>il(e),invite:(...t)=>ll(e,...t),update:(...t)=>al(e,...t),revoke:t=>cl(e,t),pendingInvites:()=>ul(e),resendInvite:(...t)=>dl(e,...t),revokeInvite:(...t)=>pl(e,...t),requests:()=>rl(e),approveRequest:(...t)=>ol(e,...t),rejectRequest:(...t)=>sl(e,...t),groupGrants:()=>gl(e),attachGroupGrant:(...t)=>ml(e,...t),updateGroupGrant:(...t)=>fl(e,...t),detachGroupGrant:t=>yl(e,t),resourceGrants:{list:()=>hl(e),create:t=>_l(e,t),remove:t=>bl(e,t)}}}function y_(e){return{tokens:{list:()=>cf(e),create:t=>lf(e,t),revoke:t=>uf(e,t)},setupLinks:{requestSecret:t=>_f(e,t),requestConnector:t=>bf(e,t)},validateManifest:t=>Oc(e,t),gitToken:()=>Dc(e),agentIdentities:()=>am(e),secrets:{list:()=>wl(e),upsert:t=>kl(e,t),setStrategy:(...t)=>vl(e,...t),broker:(...t)=>Al(e,...t),remove:t=>xr(e,t),setPersonal:(...t)=>Il(e,...t),removePersonal:t=>El(e,t),setGitCredential:t=>Tl(e,t),listProviderOAuth:()=>Rl(e),startProviderOAuth:(...t)=>us(e,...t),pollProviderOAuth:(...t)=>ps(e,...t),removeProviderOAuth:t=>Cl(e,t)},access:f_(e)}}function h_(e){return{list:()=>Wl(e),listAll:()=>Hl(e),reconcile:(...t)=>Vl(e,...t),reconcileMember:(...t)=>zl(e,...t),updateCredential:(...t)=>Yl(e,...t),revoke:(...t)=>Jl(e,...t),activate:(...t)=>Ql(e,...t),setDefault:(...t)=>Xl(e,...t),rename:(...t)=>Zl(e,...t),share:(...t)=>tu(e,...t),addComputer:(...t)=>eu(e,...t),pipedreamConnect:(...t)=>nu(e,...t),pipedreamFinalize:(...t)=>ru(e,...t)}}function ko(e){return{catalog:t=>sn(e,t),tools:()=>fs(e),search:(...t)=>Gl(e,...t),describe:(...t)=>ys(e,...t),call:(...t)=>It(e,...t),callAction:(t,n,r,o)=>It(e,`${t}.${n}`,r,o),accounts:(...t)=>hs(e,...t),uploadAttachment:(...t)=>_s(e,...t)}}function $i(e,t){return{slug:t,run:(r,o,s)=>ws(e,t,r,o,s),call:(r,o,s)=>It(e,`${t}.${r}`,o,s),describe:async r=>r!==void 0?ys(e,`${t}.${r}`):(await sn(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(s=>s.slug===t)??null,accounts:()=>hs(e,t),paginate:(r,o,s)=>Ru(e,t,r,o,s),uploadAttachment:(r,o)=>_s(e,r,{...o,connector:t})}}var MA=100,__=0,OA=new Set(["attachment_size_mismatch","attachment_failed"]),b_=()=>new S("Attachment expired. Attach the file again.",{code:"attachment_expired"});function Ui(e){if(!e||typeof e.attachment_id!="string"||!e.attachment_id||typeof e.filename!="string"||!e.filename||typeof e.mime!="string"||!e.mime||!Number.isSafeInteger(e.size)||e.size<=0||e.size>52428800||!Number.isFinite(Date.parse(e.expires_at))||Date.parse(e.expires_at)<=Date.now())throw new Error("Attachment metadata is invalid or expired. Attach the file again.");return{attachment_id:e.attachment_id,filename:e.filename,mime:e.mime,size:e.size,expires_at:e.expires_at}}function DA(e,t,n){let r,o=0,s,i=()=>{s=void 0,!(!t()||e.item.status!=="uploading"||r===void 0)&&(e.item={...e.item,receivedBytes:r},r=void 0,o=Date.now(),n())},a=p=>Math.floor(p*100/e.item.size),l=()=>{s&&clearTimeout(s),s=void 0};return{onProgress:p=>{if(!t()||a(p)===a(e.item.receivedBytes)||(r=p,s))return;let d=o+MA-Date.now();if(d<=0)return i();s=setTimeout(i,d),typeof s=="object"&&"unref"in s&&s.unref()},onProcessing:()=>{l(),r=void 0,t()&&(e.item={...e.item,status:"processing",receivedBytes:e.item.size},n())},clear:l}}function P_(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,o=new Set,s=new Set,i=0,a=!1,l,p={attachments:[]},d=()=>[...r.values()].filter(h=>!h.handedOff);function g(h,x){h.removalDeleted||(h.removalDeleted=!0,ln(e,x).catch(()=>{}))}function m(){l&&clearTimeout(l);let h=d().map(({item:P})=>P);(h.length!==p.attachments.length||h.some((P,v)=>P!==p.attachments[v]))&&(p={attachments:h});let x=Math.min(...h.filter(P=>P.status==="ready").map(P=>Date.parse(P.attachment.expires_at)));Number.isFinite(x)&&!a&&(l=setTimeout(()=>{for(let P of d())P.item.status==="ready"&&Date.parse(P.item.attachment.expires_at)<=Date.now()&&(P.item={...P.item,status:"error",error:b_()});m()},Math.min(2147483647,Math.max(0,x-Date.now()))),typeof l=="object"&&"unref"in l&&l.unref());for(let P of o)P();for(let P of[...s])P()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function _(h){f();let x=d();if(x.length+h.length>20)throw new Error("A message can contain up to 20 attachments");if(h.some(v=>!Number.isSafeInteger(v)||v<=0||v>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(x.reduce((v,T)=>v+T.item.size,0)+h.reduce((v,T)=>v+T,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function y(h,x,P){let v=++h.generation,T=new AbortController;h.abort=T,h.item={...h.item,status:"uploading",error:void 0};let L=()=>(!a||h.handedOff===!0)&&r.get(h.item.id)===h&&h.generation===v,w=DA(h,L,m);Ir(e,x,{resume:h.upload,signal:T.signal,onUpload:D=>{h.upload=D,h.removed&&(T.abort(),g(h,D.attachment_id))},...w}).then(D=>{L()&&(h.item={...h.item,status:"ready",attachment:Ui(D),receivedBytes:D.size})}).catch(D=>{D instanceof S&&OA.has(D.code??"")&&(h.upload=void 0),L()&&(h.item={...h.item,status:D instanceof S&&D.code==="ABORTED"?"aborted":"error",error:D instanceof Error?D:new Error(String(D))})}).finally(()=>{w.clear(),h.abort===T&&(h.abort=void 0),P()})}function k(){for(let h of r.values()){if(i>=n)break;if(h.item.status!=="pending"||!h.item.file||a&&!h.handedOff)continue;let x=h.item.file;i++,y(h,x,()=>{i--,m(),k()})}m()}function R(h){_(h.map(P=>P.size));let x=h.map(P=>{let v=`attachment-${++__}`;return r.set(v,{generation:0,item:{id:v,file:P,filename:P.name,mime:P.type||"application/octet-stream",size:P.size,status:"pending",receivedBytes:0}}),v});return m(),k(),x}function I(h){let x=h.map(({attachment:v,file:T})=>{try{return{attachment:Ui(v),file:T}}catch{return}});_(x.flatMap(v=>v?[v.attachment.size]:[]));let P=x.map(v=>{if(!v)return;let T=`attachment-${++__}`,{attachment:L,file:w}=v;return r.set(T,{generation:0,item:{id:T,...w?{file:w}:{},filename:L.filename,mime:L.mime,size:L.size,status:"ready",receivedBytes:L.size,attachment:L}}),T});return m(),P}function b(h){let x=r.get(h);!x||x.item.status==="ready"||(x.generation++,x.abort?.abort(),x.item={...x.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function M(h,{signal:x}={}){let P=[...h];return new Promise((v,T)=>{let L=()=>{s.delete(be),x?.removeEventListener("abort",D)},w=N=>{L(),T(N)},D=()=>w(ke()),be=()=>{let N=!1;for(let G of P){let K=r.get(G);if(!K)return w(new Error("Attachment was removed before it was sent"));if(a&&!K.handedOff)return w(new Error("Attachment controller is disposed"));if(K.item.status==="error"||K.item.status==="aborted")return w(K.item.error??new Error("Attachment upload failed"));K.item.status!=="ready"&&(N=!0)}if(N)return;let z;try{z=P.map(G=>{let K=Ui(r.get(G).item.attachment);return{type:"file",attachment_id:K.attachment_id,filename:K.filename,mime:K.mime}})}catch(G){return w(G instanceof Error?G:new Error(String(G)))}L(),v(z)};if(x?.aborted)return D();s.add(be),x?.addEventListener("abort",D,{once:!0}),be()})}return{add:h=>R([h])[0],addMany:R,restore:I,retry(h){let x=r.get(h);if(x?.handedOff||f(),!(!x||x.item.status==="ready"||x.item.status==="uploading"||x.item.status==="processing"||x.item.status==="pending")){if(!x.item.file||x.upload&&Date.parse(x.upload.expires_at)<=Date.now())throw b_();x.item={...x.item,status:"pending",error:void 0},k()}},async remove(h){let x=r.get(h);if(!x)return;x.removed=!0,x.generation++,r.delete(h);let P=x.upload?.attachment_id??x.item.attachment?.attachment_id;P&&x.abort?.abort(),m(),k(),P&&g(x,P)},abort:b,submit(h){if(!a){for(let x of h){let P=r.get(x);P&&(P.handedOff=!0)}m()}},reclaim(h){if(!a){for(let x of h){let P=r.get(x);P&&(P.handedOff=!1)}m()}},whenReady:M,forget(h=d().map(x=>x.item.id)){for(let x of h){let P=r.get(x);P&&(P.generation++,P.abort?.abort(),r.delete(x))}m(),k()},dispose(){if(!a){a=!0,l&&clearTimeout(l);for(let h of r.values()){if(h.handedOff)continue;h.generation++,h.abort?.abort();let x=h.upload?.attachment_id??h.item.attachment?.attachment_id;x&&e&&ln(e,x).catch(()=>{})}o.clear(),m()}},getSnapshot:()=>p,subscribe(h){return o.add(h),()=>{o.delete(h)}}}}function S_(e){return{attachments:{upload:(...t)=>Ir(e,...t),delete:(...t)=>ln(e,...t),createController:t=>P_(e,t)},get:t=>Ct(e,t),detail:()=>hr(e),skills:{remove:(...t)=>qc(e,...t),create:(...t)=>Kc(e,...t)},audit:t=>df(e,t),update:t=>Pr(e,t),archive:()=>Sr(e),llmCatalog:()=>_r(e),modelPicker:()=>br(e),modelAccess:()=>zr(e),setModelAccess:t=>Yr(e,t),customLlmProviders:()=>Jr(e),setCustomLlmProvider:(t,n)=>Qr(e,t,n),deleteCustomLlmProvider:t=>Xr(e,t),sandboxHealth:()=>vr(e),onboardingComplete:(...t)=>Bc(e,...t)}}function x_(e){return{sessions:{list:t=>Dt(e,t),listPage:t=>Mp(e,t),create:t=>Lt(e,t),ensureWarm:()=>qp(e),claimWarm:t=>Gp(e,t)},review:{list:t=>Rm(e,t),summary:()=>Cm(e),get:t=>Tm(e,t),submit:t=>Im(e,t),act:(...t)=>Em(e,...t),bulkAct:t=>Mm(e,t)},approvals:{list:t=>Pl(e,t),resolve:(...t)=>xl(e,...t),sessionsNeedingInput:t=>Sl(e,t)}}}function w_(e){return{files:{list:t=>Fu(e,t),listDirectory:t=>Nu(e,t),read:(t,n)=>Ku(e,t,n),search:(...t)=>Bu(e,...t),archive:(...t)=>qu(e,...t),archiveRequest:(...t)=>Gu(e,...t),history:(...t)=>tp(e,...t)},git:{commits:()=>Xu(e),commit:t=>Zu(e,t),commitDiff:t=>ep(e,t),branches:()=>Qu(e),versionDiff:(...t)=>np(e,...t),inviteCollaborator:(...t)=>Mc(e,...t)},changeRequests:{list:(...t)=>rp(e,...t),get:t=>op(e,t),update:(...t)=>gp(e,...t),diff:t=>sp(e,t),mergePreview:t=>ip(e,t),open:(...t)=>ap(e,...t),merge:(...t)=>cp(e,...t),close:(...t)=>lp(e,...t),reopen:(...t)=>up(e,...t),requestChanges:(...t)=>pp(e,...t)},...x_(e)}}function k_(e){return{policies:{list:()=>Cu(e),set:(...t)=>Tu(e,...t)},reminders:{list:()=>qm(e),updateMany:(...t)=>Bm(e,...t),removeMany:(...t)=>Km(e,...t)},rooms:{list:(...t)=>Gm(e,...t),create:(...t)=>Wm(e,...t),get:(...t)=>Hm(e,...t),update:(...t)=>Vm(e,...t),messages:(...t)=>zm(e,...t),post:(...t)=>Ym(e,...t),markRead:(...t)=>Jm(e,...t),addSession:(...t)=>Qm(e,...t),removeSession:(...t)=>Xm(e,...t),addPerson:(...t)=>Zm(e,...t),removePerson:(...t)=>ef(e,...t),people:(...t)=>tf(e,...t)},triggers:{list:()=>dd(e),eventApps:()=>wd(e),eventTypes:(...t)=>xd(e,...t),create:(...t)=>gd(e,...t),update:(...t)=>md(e,...t),remove:(...t)=>fd(e,...t),fire:((t,n)=>_d(e,t,n)),runs:(...t)=>bd(e,...t),projectRuns:(...t)=>Pd(e,...t),replay:(...t)=>Sd(e,...t),setActivation:(...t)=>yd(e,...t)},...w_(e)}}function v_(e,t){return{connectors:{...ko(e),list:()=>ou(e),config:(...n)=>pu(e,...n),create:(...n)=>mu(e,...n),remove:(...n)=>_u(e,...n),sync:()=>su(e),auth:{discover:(...n)=>fu(e,...n)},setName:(...n)=>du(e,...n),setCredentialMode:(...n)=>iu(e,...n),setAuthorizationStrategy:(...n)=>au(e,...n),setCredential:(...n)=>wu(e,...n),deleteCredential:(...n)=>ku(e,...n),setSensitive:(...n)=>cu(e,...n),connections:t,policies:{get:(...n)=>lu(e,...n),set:(...n)=>uu(e,...n)},listMoves:()=>yu(e),move:(...n)=>hu(e,...n),pipedream:{listApps:(...n)=>bu(e,...n),listSections:(...n)=>Pu(e,...n),connect:(...n)=>gu(e,...n),finalize:(...n)=>vu(e,...n)},discover:{list:(...n)=>bs(e,...n),sections:(...n)=>Su(e,...n),detail:(...n)=>Ps(e,...n)}},...k_(e)}}function A_(e){return{gateway:{logs:t=>Dg(e,t),log:t=>Lg(e,t),overview:t=>jg(e,t),series:t=>$g(e,t),breakdown:t=>Ug(e,t),sessions:t=>Fg(e,t),errors:t=>Ng(e,t),budgets:()=>Bg(e),setBudget:t=>Kg(e,t),deleteBudget:t=>qg(e,t),keys:()=>Gg(e),createKey:t=>Wg(e,t),revokeKey:t=>Hg(e,t),routing:{get:()=>Ig(e),set:t=>Eg(e,t),reset:()=>Mg(e),preview:t=>Og(e,t)},playground:(t,n,r)=>Vg(e,t,n,r)}}}function R_(e){return{modelDefaults:{get:()=>Md(e),set:t=>Od(e,t),clear:t=>Dd(e,t)},setDefaultAgent:t=>$d(e,t),sandbox:{list:()=>Uu(e),snapshots:()=>Eu(e),rebuildSnapshot:t=>Mu(e,t),fixWithAgent:()=>Ou(e),createTemplate:t=>Du(e,t),updateTemplate:(...t)=>Lu(e,...t),removeTemplate:t=>ju(e,t),buildTemplate:t=>$u(e,t),setProvider:t=>Nc(e,t)},setAgentScope:(...t)=>jd(e,...t)}}function C_(e){return{channels:{slack:{installation:()=>fg(e),connect:t=>yg(e,t),mode:()=>hg(e),completeInstall:t=>bg(e,t),manifest:()=>Sg(e),disconnect:()=>xg(e),getFile:t=>wg(e,t),uploadFile:t=>kg(e,t)},teams:{completeInstall:t=>Pg(e,t)},email:{installation:t=>vg(e,t),mode:()=>Ag(e),connect:t=>Rg(e,t),disconnect:t=>Cg(e,t),updatePolicy:(...t)=>Tg(e,...t)}},updateFeatureFlag:(...t)=>Uc(e,...t),updateExperimentalFeature:(...t)=>Fc(e,...t),...R_(e)}}var x1=["screen","actions","audio"],w1=["password_managers","messaging","banking"],k1={localHours:8760,remoteDays:3650},v1=[500,1e3,2e3,5e3,1e4],A1=[720,1080,1440,2160],R1={intervalMs:2e3,maxHeight:1440},LA=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function C1(e){let t=e.trim().toLowerCase();if(!t)return null;let n;try{n=new URL(t.includes("://")?t:`https://${t}`).hostname}catch{return null}return n=n.replace(/^www\./,"").replace(/\.$/,""),LA.test(n)?n:null}function T1(e){let t=e.trim();return!t||t.length>255||t.startsWith("-")||/[\u0000-\u001f\u007f]/.test(t)||t.endsWith("*")&&t.slice(0,-1).trim().length<3?null:t}function O1(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var Q=e=>`/accounts/${e}/capture`;function ze(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))o!==void 0&&o!==""&&t.set(r,String(o));let n=t.toString();return n?`?${n}`:""}var T_=e=>ze({q:e.q,kinds:e.kinds?.join(","),app:e.app,limit:e.limit,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,scope:e.scope}),Fi=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function I_(e,t={}){return u(await c.get(`${Q(e)}/devices${ze({user_id:t.userId,scope:t.scope})}`))}async function E_(e,t){return u(await c.delete(`${Q(e)}/devices/${t}`))}async function M_(e,t,n){return u(await c.put(`${Q(e)}/devices/${t}/link`,{user_id:n}))}async function O_(e){return u(await c.get(`${Q(e)}/enrollment-tokens`))}async function D_(e,t){return u(await c.post(`${Q(e)}/enrollment-tokens`,t))}async function L_(e,t){return u(await c.delete(`${Q(e)}/enrollment-tokens/${t}`))}async function j_(e,t={}){return u(await c.get(`${Q(e)}/enrollments${ze({status:t.status})}`))}async function $_(e,t,n){return u(await c.post(`${Q(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function U_(e,t){return u(await c.post(`${Q(e)}/enrollments/${t}/deny`,{}))}async function F_(e){return u(await c.get(`${Q(e)}/policy`))}async function N_(e,t){return u(await c.put(`${Q(e)}/policy`,{policy:t}))}async function B_(e,t={}){return u(await c.get(`${Q(e)}/timeline${ze(Fi(t))}`))}async function K_(e,t={}){return u(await c.get(`${Q(e)}/timeline/items${ze(Fi(t))}`))}async function q_(e,t={}){return u(await c.get(`${Q(e)}/days${ze({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function G_(e,t){return u(await c.get(`${Q(e)}/search${T_(t)}`))}async function W_(e,t,n={}){return u(await c.get(`${Q(e)}/frames/${t}${ze({user_id:n.userId,device_id:n.deviceId})}`))}async function H_(e,t,n={}){return u(await c.get(`${Q(e)}/chunks/${t}/media${ze({user_id:n.userId,device_id:n.deviceId})}`))}async function V_(e,t,n){return u(await c.get(`${Q(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function z_(e){return u(await c.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function Y_(e,t){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function J_(e){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function Q_(e){return u(await c.get(Q(e)))}async function X_(e,t){return u(await c.patch(Q(e),{enabled:t}))}async function Z_(e){return u(await c.get(`/capture/me/search${T_(e)}`))}async function eb(e={}){return u(await c.get(`/capture/me/timeline${ze(Fi(e))}`))}async function tb(e){return u(await c.get(`/capture/me/frames/${e}`))}function $A(e){return{workspace:{get:()=>Q_(e),setEnabled:t=>X_(e,t)},devices:{list:t=>I_(e,t),revoke:t=>E_(e,t),link:(t,n)=>M_(e,t,n),assetUrl:(t,n)=>V_(e,t,n)},enrollment:{tokens:{list:()=>O_(e),create:t=>D_(e,t),revoke:t=>L_(e,t)},list:t=>j_(e,t),approve:(t,n)=>$_(e,t,n),deny:t=>U_(e,t)},policy:{get:()=>F_(e),set:t=>N_(e,t)},timeline:{get:t=>B_(e,t),items:t=>K_(e,t),days:t=>q_(e,t)},search:t=>G_(e,t),frame:(t,n)=>W_(e,t,n),media:(t,n)=>H_(e,t,n)}}var nb={account:e=>$A(e),deviceGrant:z_,approveDevice:Y_,denyDevice:J_,me:{search:Z_,timeline:eb,frame:tb}};async function rb(e){let t=e?.fetch??C().fetch??((o,s)=>fetch(o,s)),n=e?.backendUrl??C().backendUrl,r=await t(`${Ne(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new S(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var UA=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function F1(e,t){let n=s=>{let i=UA.exec(s.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),o=n(t);if(!r||!o)return null;for(let s=0;s<3;s++)if(r[s]!==o[s])return r[s]<o[s]?-1:1;return 0}function FA(){return ht()}var ob=null,sb=!1;function NA(e){let t=ob;ob=e,!(sb||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(sb=!0,console.warn("[kortix] createKortix() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedKortix() from @kortix/sdk/server.")))}function BA(e,t){t?.global!==!1&&NA(e),Zo(e,t);let n=Zy(e),{auth:r,accounts:o,iam:s,accountInvites:i}=zy(),{billing:a,sandboxShares:l}=Wy(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=Gy();function _(y){let k=h_(y);return{...S_(y),...m_(y),...y_(y),...v_(y,k),...A_(y),...C_(y),connector:R=>$i(y,R),session:R=>ji(y,R,e,n)}}return{config:e,auth:r,accounts:o,iam:s,accountInvites:i,projects:p,connectors:ko(),connector:y=>$i(void 0,y),project:_,session:(y,k)=>ji(y,k,e,n),github:d,gitBackend:g,billing:a,sandboxShares:l,connectStatus:m,marketplace:f,capture:nb,notifications:{registerDeviceToken:ly,unregisterDeviceToken:uy,releaseDeviceToken:py,list:dy,markRead:gy,preferences:my,updatePreferences:fy,webPushPublicKey:yy,registerWebPushSubscription:hy,unregisterWebPushSubscription:_y},mobileClientPolicy:rb,validateToken:Tc,runtime:FA}}function KA(){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 qA(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Ht(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function GA(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function WA(e){if(Ht(e).length>0)return{state:e};let t=e.pending[0];if(!t)return{state:e};let n={...t,attempts:t.attempts+1};return{state:{...e,pending:[n,...e.pending.slice(1)],inFlightId:n.id,inFlightIds:[n.id]},claimed:n}}function HA(e){let t=Ht(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function VA(e,t){let n=Ht(e);if(n.length===0)return e;let r=e.pending.filter(o=>n.includes(o.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(o=>!n.includes(o.id)),failed:[...e.failed,...r.map(o=>({...o,lastError:t}))],inFlightId:null,inFlightIds:[]}}function zA(e,t){let n=e.failed.find(s=>s.id===t);if(!n)return e;let{lastError:r,...o}=n;return{...e,pending:[...e.pending,o],failed:e.failed.filter(s=>s.id!==t)}}function YA(e,t){return Ht(e).includes(t)?e:e.pending.some(n=>n.id===t)?{...e,pending:e.pending.filter(n=>n.id!==t)}:e.failed.some(n=>n.id===t)?{...e,failed:e.failed.filter(n=>n.id!==t)}:e}function JA(e,t,n){return Ht(e).includes(t)||!e.pending.some(r=>r.id===t)?e:{...e,pending:e.pending.map(r=>r.id===t?{...r,text:n}:r)}}function QA(e,t,n){let r=Ht(e);if(r.includes(t))return e;let o=e.pending.findIndex(p=>p.id===t);if(o===-1)return e;let s=r.length,i=Math.min(Math.max(n,s),e.pending.length-1);if(i===o)return e;let a=[...e.pending],[l]=a.splice(o,1);return a.splice(i,0,l),{...e,pending:a}}var ib={thinking:!1,toolDetails:!0,assistantMetadata:!0};function XA(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function ZA(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 eR(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
19
|
+
`);a=d.pop()??"";for(let g of d){let m={},f=[];for(let h of g.split(`
|
|
20
|
+
`))if(h.startsWith("data:"))f.push(h.replace(/^data:\s*/,""));else if(h.startsWith("id:"))m.id=h.replace(/^id:\s*/,"");else if(h.startsWith("retry:")){let S=Number.parseInt(h.replace(/^retry:\s*/,""),10);Number.isNaN(S)||(m.retry=S)}f.length&&(m.data=f.join(`
|
|
21
|
+
`)),yield m}}}finally{r.removeEventListener("abort",i),o.releaseLock()}}}async function*lv(e,t,n){let r=e.eventTransport??Pi(e.fetch??globalThis.fetch),s=n.signal??new AbortController().signal,o=n.sseDefaultRetryDelay??3e3,i;for(let a=1;!s.aborted;a++)try{let l=new Headers(n.headers);i!==void 0&&l.set("Last-Event-ID",i);for await(let p of r({url:new URL(t).href,headers:l,signal:s}))if(p.id!==void 0&&(i=p.id),p.retry!==void 0&&(o=p.retry),p.data!==void 0)try{yield JSON.parse(p.data)}catch{yield p.data}return}catch(l){if(n.onSseError?.(l),n.sseMaxRetryAttempts!==void 0&&a>=n.sseMaxRetryAttempts)return;let p=Math.min(o*2**(a-1),n.sseMaxRetryDelay??3e4);await new Promise(d=>setTimeout(d,p))}}function xn(e){let t=s=>(o,i)=>cv(e,iv(e.baseUrl,s,o,i)),n=s=>o=>t(s)(void 0,o);return{session:{list:t("session.list"),get:t("session.get"),create:t("session.create"),delete:t("session.delete"),update:t("session.update"),status:t("session.status"),messages:t("session.messages"),prompt:t("session.prompt"),promptAsync:t("session.promptAsync"),abort:t("session.abort"),revert:t("session.revert"),unrevert:t("session.unrevert"),summarize:t("session.summarize"),command:t("session.command"),share:t("session.share"),unshare:t("session.unshare"),fork:t("session.fork"),diff:t("session.diff"),todo:t("session.todo")},permission:{list:t("permission.list"),reply:t("permission.reply")},question:{list:t("question.list"),reply:t("question.reply"),reject:t("question.reject")},part:{update:t("part.update"),delete:t("part.delete")},file:{list:t("file.list"),read:t("file.read")},find:{files:t("find.files")},vcs:{diff:t("vcs.diff")},global:{event:async(s={})=>({stream:lv(e,`${e.baseUrl.replace(/\/$/,"")}/global/event`,s)}),health:n("global.health"),dispose:n("global.dispose"),config:{get:n("global.config.get"),update:t("global.config.update")}},provider:{list:t("provider.list"),auth:t("provider.auth"),oauth:{authorize:t("provider.oauth.authorize"),callback:t("provider.oauth.callback")}},auth:{set:t("auth.set")},app:{agents:t("app.agents"),skills:t("app.skills"),log:t("app.log")},command:{list:t("command.list")},tool:{ids:t("tool.ids"),list:t("tool.list")},mcp:{status:t("mcp.status"),add:t("mcp.add"),connect:t("mcp.connect"),disconnect:t("mcp.disconnect"),auth:{start:t("mcp.auth.start"),callback:t("mcp.auth.callback"),remove:t("mcp.auth.remove")}},project:{list:t("project.list"),current:t("project.current")},path:{get:t("path.get")}}}var ih=200;async function uv(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n.data?.message||n.error||n.message||t||`HTTP ${e.status}`}catch{return t||`HTTP ${e.status}`}}function rt(e,t){if(e.error===void 0)return e.data;let n=e.error,r=typeof n=="string"?n:n?.data?.message||n?.message||n?.error||"request failed";throw new P(`${t}: ${r}`,{...e.response?{status:e.response.status,response:e.response}:{}})}function ah(e){let t=e.runtimeUrl.replace(/\/$/,""),n=xn({baseUrl:t,fetch:e.fetch});return{messages:async(r={})=>{let s=encodeURIComponent(r.conversationId??e.rootId),o=async(l,p)=>{let d=new URLSearchParams;l!==void 0&&d.set("limit",String(l)),p&&d.set("before",p);let g=`/messages/${s}${d.size?`?${d}`:""}`,m=S=>e.fetch(new Request(`${t}${S}${g}`,{method:"GET",...r.signal?{signal:r.signal}:{}})),f=await m("/kortix/runtime");if((f.status===404||(f.headers.get("content-type")??"").startsWith("text/html"))&&(f=await m("/kortix/opencode")),!f.ok)throw new P(`Reading the session transcript failed: ${await uv(f)}`,{status:f.status,response:f});let h=await f.json();return{messages:h.messages??[],hasMore:h.has_more===!0}},i=await o(r.limit===void 0?void 0:Math.min(r.limit,ih),r.before),a=[...i.messages];for(;r.limit!==void 0&&a.length<r.limit&&i.hasMore&&a.length>0&&(i=await o(Math.min(r.limit-a.length,ih),a[0].info.id),!!i.messages.length);)a.unshift(...i.messages);return{messages:a,hasMore:i.hasMore}},pending:async()=>{let[r,s,o]=await Promise.all([n.session.status().then(i=>rt(i,"Reading the session status failed")),n.permission.list().then(i=>rt(i,"Reading permission requests failed")),n.question.list().then(i=>rt(i,"Reading questions failed"))]);return{statuses:r??{},permissions:s??[],questions:o??[]}},answerPermission:async(r,s,o)=>{rt(await n.permission.reply({requestID:r,reply:s,...o!==void 0?{message:o}:{}}),"Answering the permission request failed")},answerQuestion:async(r,s)=>{if(s===null){rt(await n.question.reject({requestID:r}),"Dismissing the question failed");return}rt(await n.question.reply({requestID:r,answers:s}),"Answering the question failed")},compact:async r=>{let s=r;if(!s){let a=await n.global.config.get().then(d=>d.error===void 0?d.data:null),l=typeof a?.model=="string"?a.model:"",p=l.indexOf("/");p>0&&p<l.length-1&&(s={providerID:l.slice(0,p),modelID:l.slice(p+1)})}if(!s)throw new P("Cannot compact: no model is set for this session",{code:"MODEL_REQUIRED"});let i=rt(await n.session.status(),"Reading the session status failed")?.[e.rootId];if(i&&i.type!=="idle")throw new P("This session is busy. Wait for the current turn to finish, then run compact again.",{code:"SESSION_BUSY",status:409});return rt(await n.session.summarize({sessionID:e.rootId,providerID:s.providerID,modelID:s.modelID}),"Compacting the session failed"),s}}}function ch(e){async function t(){let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return ah({runtimeUrl:r,rootId:n,fetch:U})}return{messages:async n=>(await t()).messages(n),pending:async()=>(await t()).pending(),answerPermission:async(n,r,s)=>(await t()).answerPermission(n,r,s),answerQuestion:async(n,r)=>(await t()).answerQuestion(n,r),compact:async n=>(await t()).compact(n)}}function lh(e){return{setModel:t=>{e.model=t},changeModel:async t=>{let n=await cd(e.projectId,e.sessionId,t);return e.clearPersistedDefaults(),n}}}var Pn=BigInt(4096),st=BigInt(0xffffffffffff),uh=st+BigInt(1),pv=uh/BigInt(2),yt=BigInt(3600*1e3)*Pn,wi=120*1e3,dv=/^msg_[0-9a-f]{12}[A-Za-z0-9]{14}$/,gv=/^msg_([0-9a-f]{12})/,ph="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function Kt(e){let t=gv.exec(e??"");return t?BigInt(`0x${t[1]}`):null}function wn(e){return BigInt(Math.trunc(e))*Pn&st}function qt(e,t){let n=e-t&st;return n>=pv&&(n-=uh),n}function dh(e){let t=null;for(let n of e)n!=null&&(t===null||qt(n,t)>BigInt(0))&&(t=n);return t}function mv(e,t){let n=Kt(e);return n===null?!1:qt(n,wn(t))>yt}function fv(e,t){let n=t===void 0?null:wn(t);return gh(e,r=>n===null||qt(r,n)<=yt)}function gh(e,t){let n=[];for(let r of e){let s=Kt(r);s!==null&&t(s)&&n.push(s)}return dh(n)}function yv(){let e="",t=new Uint8Array(32);for(;e.length<14;){crypto.getRandomValues(t);for(let n of t)n<248&&e.length<14&&(e+=ph[n%62])}return e}function mh(e){let t=e.random,n=wn(e.nowMs-(e.backdateMs??wi)),r=e.newestKnownTime??null;if(r!==null){let o=qt(r,n);o>=BigInt(0)&&o<=yt&&(n=r+BigInt(1)&st)}let s="";if(t)for(let o=0;o<14;o++)s+=ph[Math.min(61,Math.floor(t()*62))];else s=yv();return{id:`msg_${n.toString(16).padStart(12,"0")}${s}`,time:n}}function ki(e={}){let t=e.nowMs??Date.now(),n=wn(t-wi),r=gh(e.after??[],s=>{let o=qt(s,n);return o>=BigInt(0)&&o<=yt});return mh({nowMs:t,newestKnownTime:r}).id}function fh(e){return{scope:()=>id(e.projectId,e.sessionId),providerSecretPool:{list:()=>Bl(e.projectId,e.sessionId),get:t=>Nl(e.projectId,e.sessionId,t),set:(t,n)=>Kl(e.projectId,e.sessionId,t,n)},rescope:t=>ad(e.projectId,e.sessionId,t),setAgent:t=>{e.agent=t},send:async(t,n)=>{await e.ensureReady();let r=n?.model??e.model,s=n?.agent??e.agent,o=r&&s?{}:await e.persistedPromptDefaults(),i=r??o.model,a=s??o.agent,l=ki(),p=await $r(e.projectId,e.sessionId,{clientMessageId:l,messageId:l,remintOnDelivery:!0,parts:[{type:"text",text:t}],clientSentAtMs:Date.now(),...i||a?{overrides:{...i?{model:i}:{},...a?{agent:a}:{}}}:{}});if(p.state==="failed")throw new P("This prompt was refused: its earlier delivery already failed.",{code:"PROMPT_FAILED"});return p}}}var yh=async function*(e){let t=I().eventStreamTransport;if(!t){yield*Pi(((s,o)=>U(s,o,{timeoutMs:null})))(e);return}let{headers:n,rejected:r}=await vt(e.url,e.headers);try{yield*t({...e,headers:n})}catch(s){throw s?.status===401&&r(),s}};function Ge(){let e=th();return e||(I().billingEnabled??!1?"":Ad())}async function vi(e,t){return(await e.json().catch(()=>({})))?.error||e.statusText||t}function Ai(e){if(!e)throw new Error("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading");return e}async function hh(e){let t=Ai(e),n=await U(`${t}/env`);if(!n.ok)throw new Error(await vi(n,"Failed to load secrets"));return(await n.json()).secrets??{}}async function _h(e,t,n){let r=Ai(e),s=await U(`${r}/env/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})});if(!s.ok)throw new Error(await vi(s,"Failed to save secret"))}async function bh(e,t){let n=Ai(e),r=await U(`${n}/env/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await vi(r,"Failed to delete secret"))}var hv={list:hh,set:_h,delete:bh};async function _v(e,t,n){let r=e;for(;r.endsWith("/");)r=r.slice(0,-1);let s=await U(`${r}/kortix/triggers${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}}),o=await s.json();if(!s.ok)throw new Error(o?.error||o?.message||`Request failed with ${s.status}`);return o}async function ps(e,t){let n=await e.json().catch(()=>({}));return n?.error||n?.message||e.statusText||t}function kn(e){if(!e)throw new Error("[kortix-pty] Server URL not ready \u2014 sandbox is still loading");return pe(e)}async function Sh(e){let t=kn(e),n=await U(`${t}/kortix/pty`);if(!n.ok)throw new Error(await ps(n,"Failed to list terminals"));return n.json()}async function xh(e,t){let n=kn(e),r=await U(`${n}/kortix/pty`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})});if(!r.ok)throw new Error(await ps(r,"Failed to create terminal"));return r.json()}async function Ph(e,t,n){let r=kn(e),s=await U(`${r}/kortix/pty/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!s.ok)throw new Error(await ps(s,"Failed to update terminal"));return s.json()}async function wh(e,t){let n=kn(e),r=await U(`${n}/kortix/pty/${encodeURIComponent(t)}`,{method:"DELETE"});if(!r.ok)throw new Error(await ps(r,"Failed to remove terminal"))}async function kh(e,t,n){let r=kn(t),o=`${(()=>{try{let p=new URL(r);return p.protocol==="https:"?p.protocol="wss:":p.protocol==="http:"&&(p.protocol="ws:"),typeof window<"u"&&window.location.protocol==="https:"&&p.protocol==="ws:"&&(p.protocol="wss:"),pe(p.toString())}catch{return r.replace("https://","wss://").replace("http://","ws://")}})()}/kortix/pty/${encodeURIComponent(e)}/connect`,i=new URLSearchParams,a=await sn();a&&i.set("token",a),n?.wake&&i.set("wake","1");let l=i.toString();return l?`${o}${o.includes("?")?"&":"?"}${l}`:o}function bv(e){let t=e.reason.trim().toLowerCase();return t.includes("pty not found")?"replace":t.includes("pty exited")?"ended":e.hadError||t.includes("idle timeout")||t.includes("upstream error")||e.code!==1e3?"reconnect":"ended"}var ot="\x1B",vh="\x07",Sv="\0",Ri=`(?:${vh}|${ot}\\\\)`,xv=[new RegExp(`${ot}\\]697;[^${vh}${ot}]*${Ri}`,"g"),new RegExp(`${Sv}?\\{"cursor":\\d+\\}`,"g"),new RegExp(`${ot}\\][0-9]+;rgb:[0-9a-fA-F/]+${Ri}`,"g"),new RegExp(`${ot}\\]4;[0-9]+;rgb:[0-9a-fA-F/]+${Ri}`,"g"),new RegExp(`${ot}\\[\\??[0-9;]*\\$y`,"g"),new RegExp(`${ot}\\[\\d+;\\d+R`,"g"),new RegExp(`${ot}\\[\\?[0-9;]*c`,"g")];function Pv(e){let t=e;for(let n of xv)t=t.replace(n,"");return t}var wv={list:Sh,create:xh,update:Ph,remove:wh,webSocketUrl:kh};async function M(e,t,n,r){let s=e;for(;s.endsWith("/");)s=s.slice(0,-1);let o=await U(`${s}${t}`,{...n,headers:{"Content-Type":"application/json",...n?.headers}},r),i=await o.text(),a={};try{a=i?JSON.parse(i):{}}catch{a={}}if(!o.ok)throw new Error(a?.error||a?.message||a?.details||i.slice(0,200)||`Request failed with ${o.status}`);return a}async function OK(e,t={}){let n=new URLSearchParams;t.projectId&&n.set("project_id",t.projectId),t.status&&n.set("status",t.status);let r=n.toString()?`?${n}`:"";return M(e,`/kortix/tasks${r}`)}async function DK(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`)}async function jK(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/events`)}async function LK(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/status`)}async function $K(e,t){return M(e,"/kortix/tasks",{method:"POST",body:JSON.stringify(t)})}async function UK(e,t,n){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function FK(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/start`,{method:"POST"})}async function NK(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}/approve`,{method:"POST"})}async function BK(e,t){return M(e,`/kortix/tasks/${encodeURIComponent(t)}`,{method:"DELETE"})}async function KK(e,t){let n=t?`?project_id=${encodeURIComponent(t)}`:"";return M(e,`/kortix/tickets${n}`)}async function qK(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`)}async function GK(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/events`)}async function WK(e,t){return M(e,"/kortix/tickets",{method:"POST",body:JSON.stringify(t)})}async function HK(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function VK(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/status`,{method:"POST",body:JSON.stringify(n)})}async function zK(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/assign`,{method:"POST",body:JSON.stringify(n)})}async function YK(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/unassign`,{method:"POST",body:JSON.stringify(n)})}async function JK(e,t,n){return M(e,`/kortix/tickets/${encodeURIComponent(t)}/comments`,{method:"POST",body:JSON.stringify(n)})}async function QK(e,t){return M(e,`/kortix/tickets/${encodeURIComponent(t)}`,{method:"DELETE"})}async function XK(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`)}async function ZK(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/columns`,{method:"PUT",body:JSON.stringify({columns:n})})}async function eq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`)}async function tq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/fields`,{method:"PUT",body:JSON.stringify({fields:n})})}async function nq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`)}async function rq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/templates`,{method:"PUT",body:JSON.stringify({templates:n})})}async function sq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/pm-session`,{method:"POST"})}async function oq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`)}async function iq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents`,{method:"POST",body:JSON.stringify(n)})}async function aq(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function cq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}`,{method:"DELETE"})}async function lq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/agents/${encodeURIComponent(n)}/persona`)}async function uq(e,t,n=200){return M(e,`/kortix/projects/${encodeURIComponent(t)}/activity?limit=${n}`)}async function pq(e){return M(e,"/kortix/projects")}async function dq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`)}async function gq(e,t){return M(e,`/kortix/projects/by-session/${encodeURIComponent(t)}`)}async function mq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/sessions`)}async function fq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}async function yq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}async function hq(e,t,n="all"){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones?status=${n}`)}async function _q(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`)}async function bq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/events`)}async function Sq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones`,{method:"POST",body:JSON.stringify(n)})}async function xq(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(r)})}async function Pq(e,t,n,r){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/close`,{method:"POST",body:JSON.stringify(r)})}async function wq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}/reopen`,{method:"POST"})}async function kq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/milestones/${encodeURIComponent(n)}`,{method:"DELETE"})}async function vq(e,t){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`)}async function Aq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}/events`)}async function Rq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials`,{method:"POST",body:JSON.stringify(n)})}async function Cq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`)}async function Tq(e,t,n){return M(e,`/kortix/projects/${encodeURIComponent(t)}/credentials/${encodeURIComponent(n)}`,{method:"DELETE"})}var kv=1e4,vv={retryOnAuthError:!1};function Gt(e,t,n){return M(e,t,{signal:AbortSignal.timeout(kv),...n},vv)}async function Iq(e,t=!1){return(await Gt(e,`/kortix/services${t?"?all=true":""}`)).services??[]}async function Eq(e){return(await Gt(e,"/kortix/services/templates")).templates??[]}async function Mq(e,t){return(await Gt(e,`/kortix/services/${encodeURIComponent(t)}/logs`)).logs??[]}async function Oq(e,t,n){let r=n==="delete",s=r?`/kortix/services/${encodeURIComponent(t)}`:`/kortix/services/${encodeURIComponent(t)}/${n}`;return Gt(e,s,{method:r?"DELETE":"POST"})}async function Dq(e,t){return Gt(e,`/kortix/services/reconcile${t?"?reload=true":""}`,{method:"POST"})}async function jq(e,t){return Gt(e,"/kortix/services/register",{method:"POST",body:JSON.stringify(t)})}var We=new Map,Av=256,vn=class extends Error{constructor(t="[kortix-runtime] Server URL not ready \u2014 sandbox is still loading"){super(t),this.name="RuntimeNotReadyError"}};function ht(){let e=Ge();if(!e)throw new vn;return He(e)}function He(e){if(!e)throw new Error("[kortix-runtime] getClientForUrl called without a url");let t=We.get(e);if(t)return We.delete(e),We.set(e,t),t;if(!Zs())throw new Error("[kortix-runtime] No auth token provider configured \u2014 call configureKortix()/createKortix() before talking to a sandbox runtime.");let n=xn({baseUrl:e,fetch:U,eventTransport:yh});return We.set(e,n),We.size>Av&&We.delete(We.keys().next().value),n}function qq(e){We.delete(e)}function Gq(){We.clear()}var ds=new Map;function Wq(e){if(!e)throw new Error("[kortix-runtime] getPublicClientForUrl called without a url");let t=ds.get(e);if(t)return t;let n=xn({baseUrl:e,fetch});return ds.set(e,n),n}function Hq(e){ds.delete(e)}function Vq(){ds.clear()}async function Rv(e){let t=await e.text().catch(()=>"");try{let n=JSON.parse(t);return n?.error||n?.message||t||e.statusText||`HTTP ${e.status}`}catch{return t||e.statusText||`HTTP ${e.status}`}}async function zq(e){let t=Ge();if(!t)throw new P("[kortix-runtime] Server URL not ready \u2014 sandbox is still loading",{code:"RUNTIME_UNAVAILABLE"});let n=e==="full"?"/kortix/refresh":"/global/dispose",r=await U(`${t}${n}`,{method:"POST"}),s=r.headers.get("content-type")??"",o=/^application\/([\w.+-]+\+)?json\b/i.test(s.trim());if(!r.ok)throw new P(`System reload failed (${r.status}): ${await Rv(r)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});if(!o)throw new P(`System reload endpoint is unavailable on this sandbox (${n})`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"});let i;try{i=await r.json()}catch(l){throw new P(`System reload returned malformed JSON from ${n}: ${l instanceof Error?l.message:String(l)}`,{status:r.status,response:r,code:"RUNTIME_UNAVAILABLE"})}let a=i===!0||typeof i=="object"&&i!==null&&i.ok===!0;return{success:a,mode:e,steps:a?[e==="full"?"refreshed workspace and restarted runtime":"reloaded config in place"]:[],errors:a?[]:[`the sandbox did not confirm the reload (${n})`]}}var Ah="frontend";function gs(e,t,n){(e==="error"?console.error:e==="warn"?console.warn:e==="debug"?console.debug:console.log)(`[${Ah}] ${t}`,...n?[n]:[]);try{ht().app.log({service:Ah,level:e,message:t,extra:n})}catch{}}var Ve={debug:(e,t)=>gs("debug",e,t),info:(e,t)=>gs("info",e,t),warn:(e,t)=>gs("warn",e,t),error:(e,t)=>gs("error",e,t)};var Cv=16,Tv=8,Rh=6e4,Iv=250,Ev=1e3,Mv=3e4,Ov=5,Dv=.5,jv=3e3,Lv=3e4,Ch=2e4,$v=2e3,Th=8;function Uv(e){if(e.type==="session.status")return`session.status:${e.properties.sessionID}`;if(e.type==="lsp.updated")return"lsp.updated"}function Fv(e,t){if(!e||e.type!==t.type)return;if(t.type==="message.part.delta"){let o=e.properties,i=t.properties;if(o.partID!==i.partID||o.field!==i.field||o.messageID!==i.messageID||o.sessionID!==i.sessionID)return}else if(t.type==="log.block.delta"){let o=e.properties,i=t.properties;if(typeof o.delta!="string"||typeof i.delta!="string"||o.thread_id!==i.thread_id||o.message_id!==i.message_id||o.block_id!==i.block_id)return}else return;let n=e.properties,r=t.properties,s=e.coalesced??[e];return s.push(t),{...t,properties:{...r,delta:n.delta+r.delta},coalesced:s}}function Ih(e,t){let n=[],r,s=0,o=new Map,i=()=>{if(r&&e.clearTimeout(r),r=void 0,n.length===0)return;let l=n;n=[],o.clear(),s=e.now();for(let p of l)p&&t(p.event)},a=()=>{if(r)return;let l=e.now()-s;r=e.setTimeout(i,Math.max(0,Cv-l))};return{push(l){let p=Fv(n[n.length-1]?.event,l);if(p)n[n.length-1]={type:p.type,event:p};else{let d=Uv(l);if(d){let g=o.get(d);g!==void 0&&(n[g]=void 0),o.set(d,n.length)}n.push({type:l.type,event:l})}a()},flush:i,clearTimer:()=>{r&&e.clearTimeout(r)}}}function Eh(e){if(e.aborted)return{promise:Promise.resolve(),cleanup:()=>{}};let t=()=>{};return{promise:new Promise(r=>{t=()=>r(),e.addEventListener("abort",t,{once:!0})}),cleanup:()=>e.removeEventListener("abort",t)}}function Ci(e,t,...n){for(let r of e){let s=t(r);if(s)try{s(...n)}catch(o){console.warn("[opencode-events] subscriber handler threw, skipping",o)}}}async function Nv(e,t,n,r){return new Promise((s,o)=>{let i=!1,a=t.setTimeout(()=>{i||(i=!0,Ve.warn("SSE connect timed out, forcing reconnect",{connectTimeoutMs:n}),r.abort(),o(new Error(`SSE connect timed out after ${n}ms`)))},n);e.global.event({signal:r.signal,sseDefaultRetryDelay:jv,sseMaxRetryDelay:Lv,sseMaxRetryAttempts:1}).then(l=>{i||(i=!0,t.clearTimeout(a),s(l))},l=>{i||(i=!0,t.clearTimeout(a),o(l))})})}async function Bv(e,t,n,r,s){let o=!1,i=t.now(),a=e[Symbol.asyncIterator]();for(;!n.aborted;){let l=a.next().then(f=>({kind:"next",result:f}),f=>({kind:"error",error:f})),p=Eh(n),d=await Promise.race([l,p.promise.then(()=>({kind:"aborted"}))]);if(p.cleanup(),d.kind==="aborted")break;if(d.kind==="error")throw d.error;if(d.result.done)break;s();let g=d.result.value,m=g&&typeof g=="object"&&"payload"in g?g.payload:g;m?.type&&(m.type!=="server.connected"&&(o=!0),r.push(m),!(t.now()-i<Tv)&&(await new Promise(f=>t.setTimeout(f,0)),i=t.now()))}return o}function Mh(e,t,n){let r=t?.cause?.status;return!e&&(typeof r=="number"&&r>=400||n<$v)}function Oh(e,t,n){Ve.error("SSE event stream parked \u2014 giving up after consecutive hard failures",{consecutiveFailures:t,lastError:String(n)}),Ci(e,r=>r.onParked,{consecutiveFailures:t,lastError:n})}function Dh(e,t,n){let r=t?Iv:Math.min(Ev*2**Math.min(e-1,Ov),Mv);return Math.round(r*(1+Dv*(n.random?.()??0)))}function jh(e,t,n){return new Promise(r=>{let s=e.setTimeout(r,n),o=()=>{e.clearTimeout(s),r()};t.addEventListener("abort",o,{once:!0})})}async function Lh(e){let{client:t,t:n,connectTimeoutMs:r,heartbeatTimeoutMs:s,outerSignal:o,retryCount:i,setConnectionState:a,onConnected:l,coalescer:p}=e,d=!1,g=!1,m,f=null,h=new AbortController;a("connecting");let S=Eh(o);S.promise.then(()=>h.abort());try{let{stream:v}=await Nv(t,n,r,h);l();let T=()=>{n.clearTimeout(m),m=n.setTimeout(()=>{Ve.warn("SSE heartbeat timeout, forcing reconnect"),h.abort()},s)};T(),d=await Bv(v,n,h.signal,p,()=>{a("open"),T()}),g=d}catch(v){if(f=v,o.aborted)return{streamHadWork:d,stableConnection:g,error:f};let T=String(v),_=tn(v)||tn(v?.cause);if(Ve.error("SSE event stream error",{error:T,retryCount:i,isAuthError:_}),_)try{mo(),await go(),Ve.info("SSE: refreshed auth token after auth error")}catch(b){Ve.error("SSE: failed to refresh auth token",{error:String(b)})}}finally{n.clearTimeout(m),h.abort(),S.cleanup(),p.flush()}return{streamHadWork:d,stableConnection:g,error:f}}function Kv(e){return{type:"heartbeat-gap",gapMs:e}}function qv(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 Gv={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),random:()=>Math.random()},Wv=5e3,Hv=1e4,Vv=4,An=new WeakMap;function zv(e,t,n){let r=t.timers??Gv,s=t.connectTimeoutMs??Ch,o=t.heartbeatTimeoutMs??Rh,i=t.maxConsecutiveHardFailures??Th,a=new AbortController,l=(v,...T)=>Ci(n,v,...T),p=null,d=!1,g=v=>{p!==v&&(p=v,v&&l(T=>T.onConnectionChange,v))},m=r.now(),f=null,h=Ih(r,v=>{m=r.now(),l(T=>T.onEvent,v)}),S={client:e,t:r,connectTimeoutMs:s,heartbeatTimeoutMs:o,outerSignal:a.signal,setConnectionState:g,onConnected:()=>{if(f){let v=r.now()-f.lastActivityAt,T=f.eventful;f=null,(T||v>Wv)&&l(_=>_.onGapRehydrate,v)}m=r.now()},coalescer:h};return(async()=>{let v=0,T=0,_=0;for(;!a.signal.aborted;){let b=r.now(),O=await Lh({...S,retryCount:v});if(a.signal.aborted)break;let y=O.error,{streamHadWork:w,stableConnection:x}=O,k=r.now()-b;if(T=Mh(w,y,k)?T+1:0,T>=i){Oh(n,T,y),p=null,d=!0;break}g("lost"),f={lastActivityAt:m,eventful:(f?.eventful??!1)||w},_=x&&k<Hv?_+1:0;let R=x&&_<=Vv;R?v=0:(v++,v>1&&Ve.warn("SSE event stream reconnecting",{retryCount:v})),await jh(r,a.signal,Dh(v,R,r))}})(),{subscribers:n,connectionState:()=>p,isParked:()=>d,teardown:()=>{p=null,a.abort(),h.clearTimer()}}}function Ti(e){let{onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s,signal:o}=e,i=e.client??(e.url?He(e.url):void 0);if(!i)throw new Error("openEventStream needs the session runtime `url`");let a={onEvent:t,onGapRehydrate:n,onParked:r,onConnectionChange:s},l=An.get(i);if(l?.isParked()&&(An.delete(i),l=void 0),!l)l=zv(i,e,new Set([a])),An.set(i,l);else{l.subscribers.add(a);let f=l.connectionState();f&&s?.(f)}let p=l,d=!1,g=()=>{d||(d=!0,o&&o.removeEventListener("abort",m),p.subscribers.delete(a),p.subscribers.size===0&&(p.teardown(),An.get(i)===p&&An.delete(i)))},m=()=>g();return o&&(o.aborted?g():o.addEventListener("abort",m,{once:!0})),{close:g}}function $h(e){return{abort:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return He(n).session.abort({sessionID:t})},rewind:async t=>{let{runtimeSessionId:n,runtimeUrl:r}=await e.ensureReady();return He(r).session.revert({sessionID:n,messageID:t})},restoreRewind:async()=>{let{runtimeSessionId:t,runtimeUrl:n}=await e.ensureReady();return He(n).session.unrevert({sessionID:t})},stream:async t=>{let{runtimeUrl:n}=await e.ensureReady();return Ti({url:n,onEvent:t.onEvent,onGapRehydrate:t.onGapRehydrate,signal:t.signal})}}}function Fh(e){if(e.error){let t=e.error,n=t?.data?.message||t?.message||(typeof t?.error=="string"?t.error:null)||"SDK request failed";throw new P(n,{status:t?.response?.status??t?.status,response:t?.response,details:t})}return e.data}async function Mi(e){let t=await e.text().catch(()=>""),n=null;try{n=JSON.parse(t)}catch{}return n?.error||t||e.statusText||`HTTP ${e.status}`}function ae(e){let t=(e??Ge()).trim();if(!t)throw new vn;return t}async function En(e,t){let n=await U(`${ae(t)}${e}`);if(!n.ok)throw new P(await Mi(n),{status:n.status,response:n});return n.json()}async function Oi(e,t,n,r,s){let o=await U(`${ae(s)}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new P(`${r} failed (${o.status}): ${await Mi(o)}`,{status:o.status,response:o});return o.json()}var Di=["/workspace","/tmp","/home","/opt"],Yv=Di.filter(e=>e!=="/workspace");function Nh(e){return Di.some(t=>e===t||e.startsWith(`${t}/`))}function Mn(e){return Nh(e)?e:`/workspace/${e.replace(/^\/+/,"")}`}function _t(e){let t=e||"";if(t==="/workspace"||t==="/workspace/")return"";if(t.startsWith("/workspace/"))t=t.slice(11);else if(Yv.some(n=>t===n||t.startsWith(`${n}/`)))return t;for(;t.startsWith("/");)t=t.slice(1);return t}var Bh=_t;async function On(e,t){let n=ae(t),r=_t(e)||".";return(await En(`/file?path=${encodeURIComponent(r)}`,n)).map(o=>({...o,path:o.absolute||`/workspace/${o.path}`}))}async function Dn(e,t){let n=_t(e);return En(`/file/content?path=${encodeURIComponent(n)}`,t)}async function Jv(e,t,n){let r=ae(n),s=_t(e),o=await U(`${r}/file/raw?path=${encodeURIComponent(s)}`);if(!o.ok)throw new P(await Mi(o),{status:o.status,response:o});if((o.headers.get("content-type")||"").includes("text/html"))throw new P("File could not be loaded (raw byte route unavailable)",{status:o.status,response:o,code:"INVALID_CONTENT_TYPE"});let i=await o.blob();return t&&(!i.type||i.type==="application/octet-stream")?new Blob([i],{type:t}):i}var Qv=8,ms=0,Kh=[];async function Xv(){if(ms<Qv){ms++;return}await new Promise(e=>Kh.push(e)),ms++}function Zv(){ms--,Kh.shift()?.()}function eA(e,t){let n=ae(t);return Rr(`${n}/file/raw?path=${encodeURIComponent(_t(e))}`)}async function jn(e,t){await Xv();try{let n=ae(t);try{return await Jv(e,void 0,n)}catch{}let r=await Dn(e,n);if(r.encoding==="base64"&&r.content){let s=Uint8Array.from(atob(r.content),o=>o.charCodeAt(0));return new Blob([s],{type:r.mimeType||"application/octet-stream"})}return new Blob([r.content??""],{type:r.mimeType||"text/plain;charset=utf-8"})}finally{Zv()}}async function fs(e){return En("/file/status",ae(e))}async function ys(e,t,n){let r=ae(n),s=new URLSearchParams({query:e});return t?.type&&s.set("type",t.type),t?.limit&&s.set("limit",String(t.limit)),En(`/find/file?${s.toString()}`,r)}async function hs(e,t){let n=ae(t);return(await En(`/find?pattern=${encodeURIComponent(e)}`,n)).map(s=>({path:typeof s.path=="string"?s.path:s.path?.text??"",lines:typeof s.lines=="string"?s.lines:s.lines?.text??"",line_number:s.line_number,absolute_offset:s.absolute_offset,submatches:(s.submatches??[]).map(o=>({start:o.start,end:o.end}))}))}var Rn=[400,1200],tA=e=>e===408||e===429||e===502||e===503||e===504,Uh=e=>new Promise(t=>setTimeout(t,e));function nA(e){let t=e?.name;return t==="TimeoutError"||t==="AbortError"}var Ii=3e4,qh=15*6e4,rA=256;function Cn(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return Ii;let t=Ii+e/rA;return Math.min(qh,Math.max(Ii,Math.round(t)))}async function sA(e){let t=await e.text().catch(()=>""),n=null;try{n=t?JSON.parse(t):null}catch{}let r=n?.error||n?.message||n?.data?.message;return typeof r=="string"&&r.trim()?r.trim():(e.headers.get("content-type")||"").includes("text/html")||/<html[\s>]/i.test(t)?e.status===502||/bad gateway/i.test(t)?"Bad gateway while reaching the sandbox upload service. Please retry.":e.statusText||`HTTP ${e.status}`:t.replace(/\s+/g," ").trim().slice(0,500)||e.statusText||`HTTP ${e.status}`}async function Tn(e,t){let n;for(let s=0;s<=Rn.length;s++){let o;try{o=await t(e())}catch(a){if(n=a,nA(a)||s===Rn.length)break;await Uh(Rn[s]);continue}if(o.ok)return o.json();let i=await sA(o);if(n=new P(`Upload failed (${o.status}): ${i}`,{status:o.status,response:o}),!tA(o.status)||s===Rn.length)throw n;await Uh(Rn[s])}if(n instanceof P)throw n;let r=n instanceof Error?n.message:String(n||"request failed");throw new P(`Upload failed: ${r}`)}var Ei=8*1024*1024;function oA(e,t){if(!(typeof e?.size!="number"||!Number.isFinite(t))&&!(e.size>=t))throw new P(`Upload verification failed for ${e.path}: expected ${t} bytes, received ${e.size}`,{code:"UPLOAD_SIZE_MISMATCH"})}function Gh(e,t){try{e?.onProgress?.(t)}catch{}}function Wh(e,t,n){let r=new FormData,s=(t??"").trim();return s&&r.append("path",s.startsWith("/")?s:`/${s}`),n&&r.append("filename",n),n?r.append("file",e,n):r.append("file",e),r}function iA(e){let t=e.lastIndexOf("/");return t<0?{parent:"",name:e}:{parent:e.slice(0,t)||"/",name:e.slice(t+1)}}async function Ln(e,t,n,r,s){let o=typeof r=="string"?r:void 0,i=typeof r=="string"?s:r,a=ae(o),l=Cn(e.size),p=n||(e instanceof File?e.name:"")||"";if(e.size<=Ei){let d=await Tn(()=>Wh(e,t,p),g=>U(`${a}/file/upload`,{method:"POST",body:g},{timeoutMs:l}));return oA(d[0],e.size),Gh(i,{loadedBytes:e.size,totalBytes:e.size}),d}return aA(e,t,p,a,i)}async function aA(e,t,n,r,s){let i=(await Tn(()=>Wh(new Blob([],{type:e.type}),t,n),l=>U(`${r}/file/upload`,{method:"POST",body:l},{timeoutMs:Cn(0)})))[0]?.path;if(!i)throw new P("Upload reservation returned no file path",{code:"UPLOAD_NO_RESULT"});let a=iA(i);if(!a.name)throw new P(`Upload reservation returned an invalid file path: ${i}`,{code:"UPLOAD_INVALID_PATH"});try{for(let l=0;l<e.size;l+=Ei){let p=Math.min(e.size,l+Ei),d=e.slice(l,p,e.type),g=await Tn(()=>{let m=new FormData;return a.parent&&m.append("path",a.parent),m.append("filename",a.name),m.append("first",l===0?"true":"false"),m.append("offset",String(l)),m.append("file",d,a.name),m},m=>U(`${r}/file/append`,{method:"POST",body:m},{timeoutMs:Cn(d.size)}));if(g.path!==i||g.size!==p)throw new P(`Upload verification failed for ${i}: expected ${p} bytes, received ${g.size}`,{code:"UPLOAD_SIZE_MISMATCH"});Gh(s,{loadedBytes:p,totalBytes:e.size})}}catch(l){throw await Wt(i,r).catch(()=>{}),l}return[{path:i,size:e.size}]}function cA(e,t,n){let r=ae(n);return Tn(()=>{let s=new FormData;return t&&s.append("path",t),s.append("file",{uri:e.uri,name:e.name,type:e.type||"application/octet-stream"}),s},s=>U(`${r}/file/upload`,{method:"POST",body:s},{timeoutMs:lA}))}var lA=qh;function uA(e,t,n){let r=ae(n),s=Cn(t.size);return Tn(()=>{let o=new FormData;return o.append(e,t,e.split("/").pop()||"file"),o},o=>U(`${r}/file/upload`,{method:"POST",body:o},{timeoutMs:s}))}var In=class extends P{path;constructor(t){super(`A file or folder already exists at ${t}`,{status:409,code:"FILE_EXISTS"}),this.name="FileExistsError",this.path=t}};async function _s(e,t){let n=ae(t),r=e.trim(),o=(r.startsWith("/")?r:`/${r}`).split("/"),i=o.pop()||"untitled",a=o.join("/")||"/workspace",l=Mn(`${a}/${i}`),p=[];try{p=await On(Hh(l),n)}catch(g){if(!(g instanceof P&&g.status===404))throw g}if(p.some(g=>g.name===Vh(l)))throw new In(l);let d=await zh(l,new Blob([],{type:"application/octet-stream"}),n,{overwrite:!1});return[{path:d.path,size:d.bytes}]}async function bs(e,t,n){let r=ae(n);return uA(t,await jn(e,r),r)}function pA(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function Hh(e){let t=e.lastIndexOf("/");return t<=0?"/":e.slice(0,t)}function Vh(e){return e.slice(e.lastIndexOf("/")+1)}function dA(){let e=typeof crypto<"u"?crypto:void 0;if(e?.randomUUID)return e.randomUUID();if(e?.getRandomValues){let t=new Uint8Array(8);return e.getRandomValues(t),[...t].map(n=>n.toString(16).padStart(2,"0")).join("")}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}async function Ss(e,t,n){let r=ae(n),s=Mn(pA(e.trim()));return zh(s,t,r,{overwrite:!0})}async function zh(e,t,n,r){let s=Vh(e);if(!s)throw new P(`writeFile needs a file path, got "${e}"`,{code:"INVALID_PATH"});let o=Hh(e);await $n(o,n).catch(()=>{});let i=dA(),a=await Ln(t,o,`.${s}.kortix-write-${i}`,n),l=a[0]?.path;if(!l)throw new P(`Upload returned no file for ${e}`,{code:"UPLOAD_NO_RESULT"});let p=Mn(l);try{await Yh(p,e,n,r.overwrite)}catch(g){throw await Wt(p,n).catch(()=>{}),!r.overwrite&&g instanceof P&&g.status===409?new In(e):g}let d=a[0]?.size;return{path:e,bytes:typeof d=="number"?d:t.size}}async function Wt(e,t){return Oi("/file","DELETE",{path:e},"Delete",t)}async function $n(e,t){return Oi("/file/mkdir","POST",{path:e},"Mkdir",t)}async function xs(e,t,n){return Yh(e,t,ae(n),!0)}async function Yh(e,t,n,r){return Oi("/file/rename","POST",r?{from:e,to:t}:{from:e,to:t,overwrite:!1},"Rename",n)}async function Jh(){return Fh(await ht().project.current())}async function ji(){return Fh(await ht().global.health())}async function Qh(){try{return(await ji()).healthy===!0}catch{return!1}}var gA={list:On,read:Dn,readBlob:jn,status:fs,findFiles:ys,findText:hs,upload:Ln,write:Ss,create:_s,copy:bs,remove:Wt,mkdir:$n,rename:xs,currentProject:Jh,health:ji,isReachable:Qh,toDaemonPath:_t,toSandboxAbsolutePath:Mn,toWorkspaceRelative:Bh};function Xh(e){return{list:async t=>On(t,(await e()).runtimeUrl),read:async t=>Dn(t,(await e()).runtimeUrl),readBlob:async t=>jn(t,(await e()).runtimeUrl),status:async()=>fs((await e()).runtimeUrl),findFiles:async(t,n)=>ys(t,n,(await e()).runtimeUrl),findText:async t=>hs(t,(await e()).runtimeUrl),upload:async(t,n,r,s)=>Ln(t,n,r,(await e()).runtimeUrl,s),write:async(t,n)=>Ss(t,n,(await e()).runtimeUrl),create:async t=>_s(t,(await e()).runtimeUrl),copy:async(t,n)=>bs(t,n,(await e()).runtimeUrl),remove:async t=>Wt(t,(await e()).runtimeUrl),mkdir:async t=>$n(t,(await e()).runtimeUrl),rename:async(t,n)=>xs(t,n,(await e()).runtimeUrl)}}function Zh(e){return{get:t=>Dr(e.projectId,e.sessionId,t),presence:(t,n)=>c.put(`/projects/${e.projectId}/sessions/${e.sessionId}/presence`,t,{showErrors:!1,keepalive:n?.keepalive??!t.active}),cost:()=>Hr(e.sessionId,{projectId:e.projectId}),update:t=>Zp(e.projectId,e.sessionId,t),delete:()=>(e.forgetReady(),ed(e.projectId,e.sessionId)),restore:()=>nd(e.projectId,e.sessionId),recover:()=>td(e.projectId,e.sessionId),start:(...t)=>mt(e.projectId,e.sessionId,...t),startOrThrow:(...t)=>Td(e.projectId,e.sessionId,...t),restart:()=>(e.forgetReady(),Ur(e.projectId,e.sessionId)),stop:()=>(e.forgetReady(),Fr(e.projectId,e.sessionId)),configState:()=>rd(e.projectId,e.sessionId),reloadConfig:t=>(e.forgetReady(),sd(e.projectId,e.sessionId,t)),reloadConfigStream:(...t)=>(e.forgetReady(),od(e.projectId,e.sessionId,...t)),setSharing:t=>Mp(e.projectId,e.sessionId,t),previews:()=>Up(e.projectId,e.sessionId),participants:()=>Op(e.projectId,e.sessionId),watch:()=>Dp(e.projectId,e.sessionId),setWatch:t=>jp(e.projectId,e.sessionId,t),setPinned:t=>Lp(e.projectId,e.sessionId,t),setArchived:t=>$p(e.projectId,e.sessionId,t),commit:t=>pp(e.projectId,e.sessionId,t),publicShares:{list:()=>Fp(e.projectId,e.sessionId),create:(...t)=>Np(e.projectId,e.sessionId,...t),revoke:(...t)=>Bp(e.projectId,e.sessionId,...t)}}}function e_(e){return{reminders:{list:()=>$m(e.projectId,e.sessionId),create:t=>Um(e.projectId,e.sessionId,t),update:(t,n)=>$o(e.projectId,e.sessionId,t,n),remove:t=>Uo(e.projectId,e.sessionId,t),run:t=>Fm(e.projectId,e.sessionId,t)},audit:(t,n)=>Gp(e.projectId,e.sessionId,t,n),attachments:{upload:(t,n)=>Ny(e.projectId,e.sessionId,t,n),read:(t,n)=>By(`kortix-attachment://${e.projectId}/${e.sessionId}/${t}`,n)},transcript:t=>Wp(e.projectId,e.sessionId,t),messageAuthors:()=>ld(e.projectId,e.sessionId),modelUsage:()=>ud(e.projectId,e.sessionId),transcriptSync:t=>jr(e.projectId,e.sessionId,t),log:t=>Hp(e.projectId,e.sessionId,t),turn:()=>Lr(e.projectId,e.sessionId),prompts:{create:t=>$r(e.projectId,e.sessionId,t),list:()=>Vp(e.projectId,e.sessionId),remove:t=>zp(e.projectId,e.sessionId,t),retry:t=>Qp(e.projectId,e.sessionId,t),edit:(t,n)=>Yp(e.projectId,e.sessionId,t,n),interrupt:t=>Jp(e.projectId,e.sessionId,t),hold:t=>Xp(e.projectId,e.sessionId,t)},ensureReady:e.ensureReady}}function fA(e,t){return e?.some(n=>n.startsWith("session."))?e.includes(t):!0}var yA=["control_plane","provider_ingress","daemon","upstream_port"];function t_(e){return typeof e=="string"&&yA.includes(e)?e:null}function n_(e){return e?e.runtimeReady!==void 0?e.runtimeReady===!0:e.harness?e.harness.ready===!0:e.opencode!==void 0?e.opencode==="ok"||e.opencode===!0:e.status!=="starting"&&e.status!=="down"&&e.status!=="error":!1}async function r_(e,t){let n=(e===void 0?Ge():e)||null;if(!n)return{status:0,ok:!1,health:null,body:"",hop:null,upstreamStatus:null};let r=await U(`${n}/kortix/health`,{method:"GET",...t},{retryOnAuthError:!1}),s=await r.text().catch(()=>""),o=null;try{o=s?JSON.parse(s):null}catch{o=null}let i=o,a=t_(r.headers.get("X-Kortix-Proxy-Hop"))??t_(o?.hop),l=Number(r.headers.get("X-Kortix-Upstream-Status")),p=o?.upstream_status,d=Number.isFinite(l)&&l>0?l:typeof p=="number"?p:null;return{status:r.status,ok:r.ok,health:i,body:s,hop:a,upstreamStatus:d}}var s_=/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s)"'<>]*/g,o_=/^https?:\/\/p(\d+)-([^.]+)\.localhost(?::(\d+))?(\/.*)?$/,i_=/^https?:\/\/(?:dev|staging|prod|preview)-p(\d+)-([a-z0-9-]+)\.[^/]+?(?::(\d+))?(\/.*)?$/i,a_=new Set([22,4096,parseInt(tt.KORTIX_MASTER,10)]);function hA(e){return o_.test(e)}function Ps(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 _A(e){let t=e.indexOf("](");return t===-1?e:e.slice(0,t)}var bA=new Set(["'",'"',"`","<","(","["]),SA=new Set([">","'",'"',"`",")","]",",",";",".","!","?"]);function xA(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&&bA.has(e[t]);)t++;for(;n>t&&SA.has(e[n-1]);)n--;return e.slice(t,n)}function PA(e){return e.match(/https?:\/\/(?:localhost|127\.0\.0\.1):\d{1,5}[^\s"'<>)]*/i)?.[0]??null}var wA=/^\/proxy\/(\d{1,5})(\/.*)?$/,kA=/^\/(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 vA(e){if(!e)return!1;try{let t=new URL(e);return t.hostname!=="localhost"&&t.hostname!=="127.0.0.1"?!1:kA.test(t.pathname)}catch{return!1}}function ws(e){if(!e)return null;let t=xA(_A(e.trim())),n=d_(t);if(n){let r=Ps(n.path||"/");return{originalUrl:`http://localhost:${n.port}${r}`,port:n.port,path:r}}try{let r=new URL(t);if(r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname!=="localhost"&&r.hostname!=="127.0.0.1"||!r.port)return null;let s=parseInt(r.port,10);if(!Number.isInteger(s)||s<1||s>65535)return null;let o=`${r.pathname||"/"}${r.search}${r.hash}`,i=parseInt(tt.KORTIX_MASTER,10);if(s===i){let l=r.pathname.match(wA);if(l){let p=parseInt(l[1],10);if(p>=1&&p<=65535)return s=p,o=Ps(`${l[2]||"/"}${r.search}${r.hash}`),{originalUrl:`http://localhost:${s}${o}`,port:s,path:o}}}let a=Ps(o);return{originalUrl:`${r.protocol}//${r.hostname}:${s}${a}`,port:s,path:a}}catch{let r=PA(e);return r&&r!==e?ws(r):null}}function AA(e){let t=[],n=/```[\s\S]*?```/g,r;for(;(r=n.exec(e))!==null;)t.push([r.index,r.index+r[0].length]);let s=/`[^`\n]+`/g;for(;(r=s.exec(e))!==null;){let o=r.index,i=o+r[0].length;t.some(([l,p])=>o>=l&&i<=p)||t.push([o,i])}return t}function RA(e,t){return t.some(([n,r])=>e>=n&&e<r)}function CA(e){let t=[],n=new Set,r=AA(e);s_.lastIndex=0;let s;for(;(s=s_.exec(e))!==null;){let o=ws(s[0]);if(!o)continue;let{originalUrl:i,port:a,path:l}=o;a<1||a>65535||a_.has(a)||n.has(i)||(n.add(i),t.push({originalUrl:i,port:a,path:l,startIndex:s.index,endIndex:s.index+i.length,inCodeBlock:RA(s.index,r)}))}return t}function CG(e){return CA(e).length>0}function TA(e){try{let{hostname:t}=new URL(e);return t==="localhost"||t==="127.0.0.1"}catch{return!1}}function c_(e){return e.trim().toLowerCase().split("_").join("-")}function l_(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function IA(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(c_(n.sandboxId));return`${l_(s)}${t}`}function EA(e){return e.sandboxId.trim().length>0}function bt(e,t,n){let r=Ps(t);if(!EA(n))return jA(e,r);let s=IA(e,r,n);return s||(TA(n.apiBaseUrl)?`http://p${e}-${c_(n.sandboxId)}.localhost:${n.backendPort}${r}`:`${l_(n.apiBaseUrl)}/p/${n.sandboxId}/${e}${r}`)}function TG(e,t){if(!e)return;let r=e.replace(/^\/workspace\//,"").replace(/^\/+/,"").split("/").filter(Boolean).map(s=>encodeURIComponent(s)).join("/");return bt(3211,`/open?path=/workspace/${r}`,t)}function MA(e){return`/open?path=/${(e.startsWith("/workspace")?e:`/workspace/${e.replace(/^\/+/,"")}`).split("/").filter(Boolean).map(r=>encodeURIComponent(r)).join("/")}`}function IG(e){return`http://localhost:3211${MA(e)}`}function OA(){return"/health"}function EG(e){return bt(3211,OA(),e)}function MG(e,t){return bt(e,"/",t)}function DA(e){let t=ws(e);return!(!t||a_.has(t.port)||vA(e))}function u_(e,t){if(!e)return e;let n=ws(e);return n?DA(n.originalUrl)?bt(n.port,n.path,t):n.originalUrl:e}function jA(e,t="/"){return`http://localhost:${e}${t}`}var p_=/^https?:\/\/[^/]+\/v1\/p\/([^/]+)\/(\d+)(\/.*)?$/;function d_(e){let t=e.match(o_);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(i_);if(n){let s=443;try{let o=new URL(e);s=o.port?parseInt(o.port,10):o.protocol==="https:"?443:80}catch{return null}return{port:parseInt(n[1],10),sandboxId:n[2],backendPort:s,path:n[4]||"/"}}let r=e.match(p_);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 OG(e){try{let t=d_(e);return t?`http://localhost:${t.port}${t.path}`:null}catch{return null}}function DG(e){return hA(e)||i_.test(e)||p_.test(e)}function jG(e){try{let{hostname:t,port:n}=new URL(e);return(t==="localhost"||t==="127.0.0.1")&&n!==""}catch{return!1}}var Un="/web-proxy/";function LG(e,t){try{let n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:")return null;let r=n.protocol.replace(":",""),s=`${Un}${r}/${n.host}${n.pathname}${n.search}${n.hash}`,o=parseInt(tt.KORTIX_MASTER,10);return`${bt(o,"/",t).replace(/\/$/,"")}${s}`}catch{return null}}function $G(e){try{let t=new URL(e),n=t.pathname.indexOf(Un);if(n===-1)return null;let s=t.pathname.slice(n+Un.length).match(/^(https?)\/([\w.\-]+(?::\d+)?)(\/.*)?$/);if(!s)return null;let o=s[1],i=s[2],a=s[3]||"/";return`${o}://${i}${a}${t.search}${t.hash}`}catch{return null}}function UG(e){try{return new URL(e).pathname.includes(Un)}catch{return e.includes(Un)}}function FG(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 NG(e){let t=e.trim();return t?/^https?:\/\//i.test(t)?t:/^[a-z0-9][\w.-]*\.[a-z]{2,}/i.test(t)?`https://${t}`:null:null}function g_(e){return{health:t=>r_(e.tryResolveReady()?.runtimeUrl??null,t),previewUrl:(t,n="/")=>bt(t,n,e.resolvePreviewOptsForSandbox(e.requireReady("previewUrl").sandboxId)),proxyUrl:t=>u_(t,e.resolvePreviewOptsForSandbox(e.requireReady("proxyUrl").sandboxId)),sandboxPortUrl:t=>Fe(e.requireReady("sandboxPortUrl").sandboxId,t)}}function Li(e,t,n,r){let s,o,{persistedPromptDefaults:i,clearPersistedDefaults:a}=eh(e,t),{ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g}=sh(e,t,n),m={projectId:e,sessionId:t,ensureReady:l,tryResolveReady:p,requireReady:d,forgetReady:g,resolvePreviewOptsForSandbox:r,get model(){return s},set model(f){s=f},get agent(){return o},set agent(f){o=f},clearPersistedDefaults:a,persistedPromptDefaults:i};return{...Zh(m),...e_(m),...g_(m),...lh(m),...fh(m),...$h(m),files:Xh(l),...ch(m),get runtime(){return He(d("runtime").runtimeUrl)}}}function m_(e){return{apps:{list:()=>Cf(e),create:t=>Tf(e,t),get:t=>Bo(e,t),update:(...t)=>If(e,...t),access:{get:(...t)=>Df(e,...t),update:(...t)=>Lf(e,...t),session:(...t)=>$f(e,...t),agents:t=>jf(e,t)},remove:t=>Ef(e,t),token:t=>Mf(e,t),authEnv:t=>Of(e,t),artifacts:{register:t=>Ko(e,t),uploadArchive:(...t)=>Uf(e,...t),finalize:(...t)=>qo(e,...t)},deployments:{create:(...t)=>Ff(e,...t),list:t=>Nf(e,t),get:(...t)=>Bf(e,...t),logs:(...t)=>Kf(e,...t),remove:(...t)=>Wf(e,...t)},start:t=>qf(e,t),stop:t=>Gf(e,t),rollback:(...t)=>Hf(e,...t),machines:{list:t=>Vf(e,t),start:(t,n)=>zf(e,t,n),stop:(t,n)=>Yf(e,t,n),restart:(t,n)=>Jf(e,t,n),destroy:(t,n)=>Qf(e,t,n)},scale:(...t)=>Xf(e,...t),exec:(...t)=>Zf(e,...t),volumes:{list:t=>ey(e,t),create:(...t)=>ty(e,...t),update:(...t)=>ny(e,...t),destroy:(...t)=>ry(e,...t),snapshots:(...t)=>sy(e,...t),snapshot:(...t)=>oy(e,...t),restore:(...t)=>iy(e,...t),fork:(...t)=>ay(e,...t)}}}}function f_(e){return{list:()=>ol(e),invite:(...t)=>cl(e,...t),update:(...t)=>il(e,...t),revoke:t=>al(e,t),pendingInvites:()=>ll(e),resendInvite:(...t)=>pl(e,...t),revokeInvite:(...t)=>ul(e,...t),requests:()=>nl(e),approveRequest:(...t)=>rl(e,...t),rejectRequest:(...t)=>sl(e,...t),groupGrants:()=>dl(e),attachGroupGrant:(...t)=>gl(e,...t),updateGroupGrant:(...t)=>ml(e,...t),detachGroupGrant:t=>fl(e,t),resourceGrants:{list:()=>yl(e),create:t=>hl(e,t),remove:t=>_l(e,t)}}}function y_(e){return{tokens:{list:()=>cf(e),create:t=>lf(e,t),revoke:t=>uf(e,t)},setupLinks:{requestSecret:t=>_f(e,t),requestConnector:t=>bf(e,t)},validateManifest:t=>Mc(e,t),gitToken:()=>Oc(e),agentIdentities:()=>im(e),secrets:{list:()=>Pl(e),upsert:t=>wl(e,t),setStrategy:(...t)=>kl(e,...t),broker:(...t)=>vl(e,...t),remove:t=>wr(e,t),setPersonal:(...t)=>Tl(e,...t),removePersonal:t=>Il(e,t),setGitCredential:t=>Cl(e,t),listProviderOAuth:()=>Al(e),startProviderOAuth:(...t)=>lo(e,...t),pollProviderOAuth:(...t)=>uo(e,...t),removeProviderOAuth:t=>Rl(e,t)},access:f_(e)}}function h_(e){return{list:()=>Gl(e),listAll:()=>Wl(e),reconcile:(...t)=>Hl(e,...t),reconcileMember:(...t)=>Vl(e,...t),updateCredential:(...t)=>zl(e,...t),revoke:(...t)=>Yl(e,...t),activate:(...t)=>Jl(e,...t),setDefault:(...t)=>Ql(e,...t),rename:(...t)=>Xl(e,...t),share:(...t)=>eu(e,...t),addComputer:(...t)=>Zl(e,...t),pipedreamConnect:(...t)=>tu(e,...t),pipedreamFinalize:(...t)=>nu(e,...t)}}function ks(e){return{catalog:t=>on(e,t),tools:()=>fo(e),search:(...t)=>ql(e,...t),describe:(...t)=>yo(e,...t),call:(...t)=>It(e,...t),callAction:(t,n,r,s)=>It(e,`${t}.${n}`,r,s),accounts:(...t)=>ho(e,...t),uploadAttachment:(...t)=>_o(e,...t)}}function $i(e,t){return{slug:t,run:(r,s,o)=>wo(e,t,r,s,o),call:(r,s,o)=>It(e,`${t}.${r}`,s,o),describe:async r=>r!==void 0?yo(e,`${t}.${r}`):(await on(e,{slug:t,includeSchemas:!0,includeOutputSchemas:!0})).find(o=>o.slug===t)??null,accounts:()=>ho(e,t),paginate:(r,s,o)=>Au(e,t,r,s,o),uploadAttachment:(r,s)=>_o(e,r,{...s,connector:t})}}var LA=100,__=0,$A=new Set(["attachment_size_mismatch","attachment_failed"]),b_=()=>new P("Attachment expired. Attach the file again.",{code:"attachment_expired"});function Ui(e){if(!e||typeof e.attachment_id!="string"||!e.attachment_id||typeof e.filename!="string"||!e.filename||typeof e.mime!="string"||!e.mime||!Number.isSafeInteger(e.size)||e.size<=0||e.size>52428800||!Number.isFinite(Date.parse(e.expires_at))||Date.parse(e.expires_at)<=Date.now())throw new Error("Attachment metadata is invalid or expired. Attach the file again.");return{attachment_id:e.attachment_id,filename:e.filename,mime:e.mime,size:e.size,expires_at:e.expires_at}}function UA(e,t,n){let r,s=0,o,i=()=>{o=void 0,!(!t()||e.item.status!=="uploading"||r===void 0)&&(e.item={...e.item,receivedBytes:r},r=void 0,s=Date.now(),n())},a=p=>Math.floor(p*100/e.item.size),l=()=>{o&&clearTimeout(o),o=void 0};return{onProgress:p=>{if(!t()||a(p)===a(e.item.receivedBytes)||(r=p,o))return;let d=s+LA-Date.now();if(d<=0)return i();o=setTimeout(i,d),typeof o=="object"&&"unref"in o&&o.unref()},onProcessing:()=>{l(),r=void 0,t()&&(e.item={...e.item,status:"processing",receivedBytes:e.item.size},n())},clear:l}}function S_(e,t={}){let n=t.concurrency??2;if(!Number.isInteger(n)||n<1||n>20)throw new Error("Attachment concurrency must be between 1 and 20");let r=new Map,s=new Set,o=new Set,i=0,a=!1,l,p={attachments:[]},d=()=>[...r.values()].filter(y=>!y.handedOff);function g(y,w){y.removalDeleted||(y.removalDeleted=!0,ln(e,w).catch(()=>{}))}function m(){l&&clearTimeout(l);let y=d().map(({item:x})=>x);(y.length!==p.attachments.length||y.some((x,k)=>x!==p.attachments[k]))&&(p={attachments:y});let w=Math.min(...y.filter(x=>x.status==="ready").map(x=>Date.parse(x.attachment.expires_at)));Number.isFinite(w)&&!a&&(l=setTimeout(()=>{for(let x of d())x.item.status==="ready"&&Date.parse(x.item.attachment.expires_at)<=Date.now()&&(x.item={...x.item,status:"error",error:b_()});m()},Math.min(2147483647,Math.max(0,w-Date.now()))),typeof l=="object"&&"unref"in l&&l.unref());for(let x of s)x();for(let x of[...o])x()}function f(){if(a)throw new Error("Attachment controller is disposed");if(!e)throw new Error("A project is required to attach files");return e}function h(y){f();let w=d();if(w.length+y.length>20)throw new Error("A message can contain up to 20 attachments");if(y.some(k=>!Number.isSafeInteger(k)||k<=0||k>52428800))throw new Error("Each attachment must contain 1 byte to 50 MiB");if(w.reduce((k,C)=>k+C.item.size,0)+y.reduce((k,C)=>k+C,0)>104857600)throw new Error("Message attachments exceed 100 MiB")}function S(y,w,x){let k=++y.generation,C=new AbortController;y.abort=C,y.item={...y.item,status:"uploading",error:void 0};let j=()=>(!a||y.handedOff===!0)&&r.get(y.item.id)===y&&y.generation===k,R=UA(y,j,m);Er(e,w,{resume:y.upload,signal:C.signal,onUpload:L=>{y.upload=L,y.removed&&(C.abort(),g(y,L.attachment_id))},...R}).then(L=>{j()&&(y.item={...y.item,status:"ready",attachment:Ui(L),receivedBytes:L.size})}).catch(L=>{L instanceof P&&$A.has(L.code??"")&&(y.upload=void 0),j()&&(y.item={...y.item,status:L instanceof P&&L.code==="ABORTED"?"aborted":"error",error:L instanceof Error?L:new Error(String(L))})}).finally(()=>{R.clear(),y.abort===C&&(y.abort=void 0),x()})}function v(){for(let y of r.values()){if(i>=n)break;if(y.item.status!=="pending"||!y.item.file||a&&!y.handedOff)continue;let w=y.item.file;i++,S(y,w,()=>{i--,m(),v()})}m()}function T(y){h(y.map(x=>x.size));let w=y.map(x=>{let k=`attachment-${++__}`;return r.set(k,{generation:0,item:{id:k,file:x,filename:x.name,mime:x.type||"application/octet-stream",size:x.size,status:"pending",receivedBytes:0}}),k});return m(),v(),w}function _(y){let w=y.map(({attachment:k,file:C})=>{try{return{attachment:Ui(k),file:C}}catch{return}});h(w.flatMap(k=>k?[k.attachment.size]:[]));let x=w.map(k=>{if(!k)return;let C=`attachment-${++__}`,{attachment:j,file:R}=k;return r.set(C,{generation:0,item:{id:C,...R?{file:R}:{},filename:j.filename,mime:j.mime,size:j.size,status:"ready",receivedBytes:j.size,attachment:j}}),C});return m(),x}function b(y){let w=r.get(y);!w||w.item.status==="ready"||(w.generation++,w.abort?.abort(),w.item={...w.item,status:"aborted",error:new Error("Attachment upload cancelled")},m())}function O(y,{signal:w}={}){let x=[...y];return new Promise((k,C)=>{let j=()=>{o.delete(le),w?.removeEventListener("abort",L)},R=D=>{j(),C(D)},L=()=>R(ke()),le=()=>{let D=!1;for(let W of x){let K=r.get(W);if(!K)return R(new Error("Attachment was removed before it was sent"));if(a&&!K.handedOff)return R(new Error("Attachment controller is disposed"));if(K.item.status==="error"||K.item.status==="aborted")return R(K.item.error??new Error("Attachment upload failed"));K.item.status!=="ready"&&(D=!0)}if(D)return;let q;try{q=x.map(W=>{let K=Ui(r.get(W).item.attachment);return{type:"file",attachment_id:K.attachment_id,filename:K.filename,mime:K.mime}})}catch(W){return R(W instanceof Error?W:new Error(String(W)))}j(),k(q)};if(w?.aborted)return L();o.add(le),w?.addEventListener("abort",L,{once:!0}),le()})}return{add:y=>T([y])[0],addMany:T,restore:_,retry(y){let w=r.get(y);if(w?.handedOff||f(),!(!w||w.item.status==="ready"||w.item.status==="uploading"||w.item.status==="processing"||w.item.status==="pending")){if(!w.item.file||w.upload&&Date.parse(w.upload.expires_at)<=Date.now())throw b_();w.item={...w.item,status:"pending",error:void 0},v()}},async remove(y){let w=r.get(y);if(!w)return;w.removed=!0,w.generation++,r.delete(y);let x=w.upload?.attachment_id??w.item.attachment?.attachment_id;x&&w.abort?.abort(),m(),v(),x&&g(w,x)},abort:b,submit(y){if(!a){for(let w of y){let x=r.get(w);x&&(x.handedOff=!0)}m()}},reclaim(y){if(!a){for(let w of y){let x=r.get(w);x&&(x.handedOff=!1)}m()}},whenReady:O,forget(y=d().map(w=>w.item.id)){for(let w of y){let x=r.get(w);x&&(x.generation++,x.abort?.abort(),r.delete(w))}m(),v()},dispose(){if(!a){a=!0,l&&clearTimeout(l);for(let y of r.values()){if(y.handedOff)continue;y.generation++,y.abort?.abort();let w=y.upload?.attachment_id??y.item.attachment?.attachment_id;w&&e&&ln(e,w).catch(()=>{})}s.clear(),m()}},getSnapshot:()=>p,subscribe(y){return s.add(y),()=>{s.delete(y)}}}}function x_(e){return{attachments:{upload:(...t)=>Er(e,...t),delete:(...t)=>ln(e,...t),createController:t=>S_(e,t)},get:t=>Ct(e,t),detail:()=>_r(e),skills:{remove:(...t)=>Kc(e,...t),create:(...t)=>Bc(e,...t)},audit:t=>df(e,t),update:t=>xr(e,t),archive:()=>Pr(e),llmCatalog:()=>br(e),modelPicker:()=>Sr(e),modelAccess:()=>Yr(e),setModelAccess:t=>Jr(e,t),customLlmProviders:()=>Qr(e),setCustomLlmProvider:(t,n)=>Xr(e,t,n),deleteCustomLlmProvider:t=>Zr(e,t),sandboxHealth:()=>Ar(e),onboardingComplete:(...t)=>Nc(e,...t)}}function P_(e){return{sessions:{list:t=>Dt(e,t),listPage:t=>Ep(e,t),create:t=>jt(e,t),ensureWarm:()=>Kp(e),claimWarm:t=>qp(e,t)},review:{list:t=>Am(e,t),summary:()=>Rm(e),get:t=>Cm(e,t),submit:t=>Tm(e,t),act:(...t)=>Im(e,...t),bulkAct:t=>Em(e,t)},approvals:{list:t=>bl(e,t),resolve:(...t)=>xl(e,...t),sessionsNeedingInput:t=>Sl(e,t)}}}function w_(e){return{files:{list:t=>Uu(e,t),listDirectory:t=>Fu(e,t),read:(t,n)=>Bu(e,t,n),search:(...t)=>Nu(e,...t),archive:(...t)=>Ku(e,...t),archiveRequest:(...t)=>qu(e,...t),history:(...t)=>ep(e,...t)},git:{commits:()=>Qu(e),commit:t=>Xu(e,t),commitDiff:t=>Zu(e,t),branches:()=>Ju(e),versionDiff:(...t)=>tp(e,...t),inviteCollaborator:(...t)=>Ec(e,...t)},changeRequests:{list:(...t)=>np(e,...t),get:t=>rp(e,t),update:(...t)=>dp(e,...t),diff:t=>sp(e,t),mergePreview:t=>op(e,t),open:(...t)=>ip(e,...t),merge:(...t)=>ap(e,...t),close:(...t)=>cp(e,...t),reopen:(...t)=>lp(e,...t),requestChanges:(...t)=>up(e,...t)},...P_(e)}}function k_(e){return{policies:{list:()=>Ru(e),set:(...t)=>Cu(e,...t)},reminders:{list:()=>qm(e),updateMany:(...t)=>Bm(e,...t),removeMany:(...t)=>Km(e,...t)},rooms:{list:(...t)=>Gm(e,...t),create:(...t)=>Wm(e,...t),get:(...t)=>Hm(e,...t),update:(...t)=>Vm(e,...t),messages:(...t)=>zm(e,...t),post:(...t)=>Ym(e,...t),markRead:(...t)=>Jm(e,...t),addSession:(...t)=>Qm(e,...t),removeSession:(...t)=>Xm(e,...t),addPerson:(...t)=>Zm(e,...t),removePerson:(...t)=>ef(e,...t),people:(...t)=>tf(e,...t)},triggers:{list:()=>pd(e),eventApps:()=>Pd(e),eventTypes:(...t)=>xd(e,...t),create:(...t)=>dd(e,...t),update:(...t)=>gd(e,...t),remove:(...t)=>md(e,...t),fire:((t,n)=>hd(e,t,n)),runs:(...t)=>_d(e,...t),projectRuns:(...t)=>bd(e,...t),replay:(...t)=>Sd(e,...t),setActivation:(...t)=>fd(e,...t)},...w_(e)}}function v_(e,t){return{connectors:{...ks(e),list:()=>ru(e),config:(...n)=>uu(e,...n),create:(...n)=>gu(e,...n),remove:(...n)=>hu(e,...n),sync:()=>su(e),auth:{discover:(...n)=>mu(e,...n)},setName:(...n)=>pu(e,...n),setCredentialMode:(...n)=>ou(e,...n),setAuthorizationStrategy:(...n)=>iu(e,...n),setCredential:(...n)=>Pu(e,...n),deleteCredential:(...n)=>wu(e,...n),setSensitive:(...n)=>au(e,...n),connections:t,policies:{get:(...n)=>cu(e,...n),set:(...n)=>lu(e,...n)},listMoves:()=>fu(e),move:(...n)=>yu(e,...n),pipedream:{listApps:(...n)=>_u(e,...n),listSections:(...n)=>bu(e,...n),connect:(...n)=>du(e,...n),finalize:(...n)=>ku(e,...n)},discover:{list:(...n)=>bo(e,...n),sections:(...n)=>Su(e,...n),detail:(...n)=>So(e,...n)}},...k_(e)}}function A_(e){return{gateway:{logs:t=>Og(e,t),log:t=>Dg(e,t),overview:t=>jg(e,t),series:t=>Lg(e,t),breakdown:t=>$g(e,t),sessions:t=>Ug(e,t),errors:t=>Fg(e,t),budgets:()=>Ng(e),setBudget:t=>Bg(e,t),deleteBudget:t=>Kg(e,t),keys:()=>qg(e),createKey:t=>Gg(e,t),revokeKey:t=>Wg(e,t),routing:{get:()=>Tg(e),set:t=>Ig(e,t),reset:()=>Eg(e),preview:t=>Mg(e,t)},playground:(t,n,r)=>Hg(e,t,n,r)}}}function R_(e){return{modelDefaults:{get:()=>Ed(e),set:t=>Md(e,t),clear:t=>Od(e,t)},setDefaultAgent:t=>Ld(e,t),sandbox:{list:()=>$u(e),snapshots:()=>Iu(e),rebuildSnapshot:t=>Eu(e,t),fixWithAgent:()=>Mu(e),createTemplate:t=>Ou(e,t),updateTemplate:(...t)=>Du(e,...t),removeTemplate:t=>ju(e,t),buildTemplate:t=>Lu(e,t),setProvider:t=>Fc(e,t)},setAgentScope:(...t)=>jd(e,...t)}}function C_(e){return{channels:{slack:{installation:()=>mg(e),connect:t=>fg(e,t),mode:()=>yg(e),completeInstall:t=>_g(e,t),manifest:()=>Sg(e),disconnect:()=>xg(e),getFile:t=>Pg(e,t),uploadFile:t=>wg(e,t)},teams:{completeInstall:t=>bg(e,t)},email:{installation:t=>kg(e,t),mode:()=>vg(e),connect:t=>Ag(e,t),disconnect:t=>Rg(e,t),updatePolicy:(...t)=>Cg(e,...t)}},updateFeatureFlag:(...t)=>$c(e,...t),updateExperimentalFeature:(...t)=>Uc(e,...t),...R_(e)}}var C1=["screen","actions","audio"],T1=["password_managers","messaging","banking"],I1={localHours:8760,remoteDays:3650},E1=[500,1e3,2e3,5e3,1e4],M1=[720,1080,1440,2160],O1={intervalMs:2e3,maxHeight:1440},FA=/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;function D1(e){let t=e.trim().toLowerCase();if(!t)return null;let n;try{n=new URL(t.includes("://")?t:`https://${t}`).hostname}catch{return null}return n=n.replace(/^www\./,"").replace(/\.$/,""),FA.test(n)?n:null}function j1(e){let t=e.trim();return!t||t.length>255||t.startsWith("-")||/[\u0000-\u001f\u007f]/.test(t)||t.endsWith("*")&&t.slice(0,-1).trim().length<3?null:t}function F1(e){let{state:t,idle:n}=e.health;return t==="healthy"?n?"idle":"recording":t}var Y=e=>`/accounts/${e}/capture`;function ze(e){let t=new URLSearchParams;for(let[r,s]of Object.entries(e))s!==void 0&&s!==""&&t.set(r,String(s));let n=t.toString();return n?`?${n}`:""}var T_=e=>ze({q:e.q,kinds:e.kinds?.join(","),app:e.app,limit:e.limit,day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,scope:e.scope}),Fi=(e={})=>({day:e.day,from:e.from,to:e.to,user_id:e.userId,device_id:e.deviceId,display_id:e.displayId});async function I_(e,t={}){return u(await c.get(`${Y(e)}/devices${ze({user_id:t.userId,scope:t.scope})}`))}async function E_(e,t){return u(await c.delete(`${Y(e)}/devices/${t}`))}async function M_(e,t,n){return u(await c.put(`${Y(e)}/devices/${t}/link`,{user_id:n}))}async function O_(e){return u(await c.get(`${Y(e)}/enrollment-tokens`))}async function D_(e,t){return u(await c.post(`${Y(e)}/enrollment-tokens`,t))}async function j_(e,t){return u(await c.delete(`${Y(e)}/enrollment-tokens/${t}`))}async function L_(e,t={}){return u(await c.get(`${Y(e)}/enrollments${ze({status:t.status})}`))}async function $_(e,t,n){return u(await c.post(`${Y(e)}/enrollments/${t}/approve`,n?{user_id:n}:{}))}async function U_(e,t){return u(await c.post(`${Y(e)}/enrollments/${t}/deny`,{}))}async function F_(e){return u(await c.get(`${Y(e)}/policy`))}async function N_(e,t){return u(await c.put(`${Y(e)}/policy`,{policy:t}))}async function B_(e){return u(await c.get(`${Y(e)}/storage`))}async function K_(e,t){return u(await c.put(`${Y(e)}/storage`,t))}async function q_(e,t={}){return u(await c.get(`${Y(e)}/timeline${ze(Fi(t))}`))}async function G_(e,t={}){return u(await c.get(`${Y(e)}/timeline/items${ze(Fi(t))}`))}async function W_(e,t={}){return u(await c.get(`${Y(e)}/days${ze({tz:t.tz,user_id:t.userId,device_id:t.deviceId})}`))}async function H_(e,t){return u(await c.get(`${Y(e)}/search${T_(t)}`))}async function V_(e,t,n={}){return u(await c.get(`${Y(e)}/frames/${t}${ze({user_id:n.userId,device_id:n.deviceId})}`))}async function z_(e,t,n={}){return u(await c.get(`${Y(e)}/chunks/${t}/media${ze({user_id:n.userId,device_id:n.deviceId})}`))}async function Y_(e,t,n){return u(await c.get(`${Y(e)}/devices/${t}/assets/${encodeURIComponent(n)}`))}async function J_(e){return u(await c.get(`/capture/device/grants/${encodeURIComponent(e)}`))}async function Q_(e,t){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/approve`,t?{account_id:t}:{}))}async function X_(e){return u(await c.post(`/capture/device/grants/${encodeURIComponent(e)}/deny`,{}))}async function Z_(e){return u(await c.get(Y(e)))}async function eb(e,t){return u(await c.patch(Y(e),{enabled:t}))}async function tb(e){return u(await c.get(`/capture/me/search${T_(e)}`))}async function nb(e={}){return u(await c.get(`/capture/me/timeline${ze(Fi(e))}`))}async function rb(e){return u(await c.get(`/capture/me/frames/${e}`))}function BA(e){return{workspace:{get:()=>Z_(e),setEnabled:t=>eb(e,t)},devices:{list:t=>I_(e,t),revoke:t=>E_(e,t),link:(t,n)=>M_(e,t,n),assetUrl:(t,n)=>Y_(e,t,n)},enrollment:{tokens:{list:()=>O_(e),create:t=>D_(e,t),revoke:t=>j_(e,t)},list:t=>L_(e,t),approve:(t,n)=>$_(e,t,n),deny:t=>U_(e,t)},policy:{get:()=>F_(e),set:t=>N_(e,t)},storage:{get:()=>B_(e),set:t=>K_(e,t)},timeline:{get:t=>q_(e,t),items:t=>G_(e,t),days:t=>W_(e,t)},search:t=>H_(e,t),frame:(t,n)=>V_(e,t,n),media:(t,n)=>z_(e,t,n)}}var sb={account:e=>BA(e),deviceGrant:J_,approveDevice:Q_,denyDevice:X_,me:{search:tb,timeline:nb,frame:rb}};async function ob(e){let t=e?.fetch??I().fetch??((s,o)=>fetch(s,o)),n=e?.backendUrl??I().backendUrl,r=await t(`${Ne(n)}/clients/mobile`,{headers:{accept:"application/json"},...e?.signal?{signal:e.signal}:{}});if(!r.ok)throw new P(`Mobile client policy request failed (HTTP ${r.status})`,{status:r.status,response:r});return await r.json()}var KA=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/i;function W1(e,t){let n=o=>{let i=KA.exec(o.trim());return i?[Number(i[1]),Number(i[2]??0),Number(i[3]??0)]:null},r=n(e),s=n(t);if(!r||!s)return null;for(let o=0;o<3;o++)if(r[o]!==s[o])return r[o]<s[o]?-1:1;return 0}function qA(){return ht()}var ib=null,ab=!1;function GA(e){let t=ib;ib=e,!(ab||!t)&&(t.backendUrl===e.backendUrl&&t.getToken===e.getToken||(ab=!0,console.warn("[kortix] createKortix() was called again with a different backendUrl or getToken. Every client shares one process-global config, so the earlier client now uses the new one. For several tenants in one process use createScopedKortix() from @kortix/sdk/server.")))}function WA(e,t){t?.global!==!1&&GA(e),Xs(e,t);let n=Zy(e),{auth:r,accounts:s,iam:o,accountInvites:i}=zy(),{billing:a,sandboxShares:l}=Wy(),{projects:p,github:d,gitBackend:g,connectStatus:m,marketplace:f}=Gy();function h(S){let v=h_(S);return{...x_(S),...m_(S),...y_(S),...v_(S,v),...A_(S),...C_(S),connector:T=>$i(S,T),session:T=>Li(S,T,e,n)}}return{config:e,auth:r,accounts:s,iam:o,accountInvites:i,projects:p,connectors:ks(),connector:S=>$i(void 0,S),project:h,session:(S,v)=>Li(S,v,e,n),github:d,gitBackend:g,billing:a,sandboxShares:l,connectStatus:m,marketplace:f,capture:sb,notifications:{registerDeviceToken:ly,unregisterDeviceToken:uy,releaseDeviceToken:py,list:dy,markRead:gy,preferences:my,updatePreferences:fy,webPushPublicKey:yy,registerWebPushSubscription:hy,unregisterWebPushSubscription:_y},mobileClientPolicy:ob,validateToken:Cc,runtime:qA}}function HA(){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 VA(){return{pending:[],failed:[],inFlightId:null,inFlightIds:[]}}function Ht(e){return e.inFlightIds?.length?e.inFlightIds:e.inFlightId?[e.inFlightId]:[]}function zA(e,t){return{...e,pending:[...e.pending,{...t,attempts:0}]}}function YA(e){if(Ht(e).length>0)return{state:e};let t=e.pending[0];if(!t)return{state:e};let n={...t,attempts:t.attempts+1};return{state:{...e,pending:[n,...e.pending.slice(1)],inFlightId:n.id,inFlightIds:[n.id]},claimed:n}}function JA(e){let t=Ht(e);return t.length===0?e:{...e,pending:e.pending.filter(n=>!t.includes(n.id)),inFlightId:null,inFlightIds:[]}}function QA(e,t){let n=Ht(e);if(n.length===0)return e;let r=e.pending.filter(s=>n.includes(s.id));return r.length===0?{...e,inFlightId:null,inFlightIds:[]}:{pending:e.pending.filter(s=>!n.includes(s.id)),failed:[...e.failed,...r.map(s=>({...s,lastError:t}))],inFlightId:null,inFlightIds:[]}}function XA(e,t){let n=e.failed.find(o=>o.id===t);if(!n)return e;let{lastError:r,...s}=n;return{...e,pending:[...e.pending,s],failed:e.failed.filter(o=>o.id!==t)}}function ZA(e,t){return Ht(e).includes(t)?e:e.pending.some(n=>n.id===t)?{...e,pending:e.pending.filter(n=>n.id!==t)}:e.failed.some(n=>n.id===t)?{...e,failed:e.failed.filter(n=>n.id!==t)}:e}function eR(e,t,n){return Ht(e).includes(t)||!e.pending.some(r=>r.id===t)?e:{...e,pending:e.pending.map(r=>r.id===t?{...r,text:n}:r)}}function tR(e,t,n){let r=Ht(e);if(r.includes(t))return e;let s=e.pending.findIndex(p=>p.id===t);if(s===-1)return e;let o=r.length,i=Math.min(Math.max(n,o),e.pending.length-1);if(i===s)return e;let a=[...e.pending],[l]=a.splice(s,1);return a.splice(i,0,l),{...e,pending:a}}var cb={thinking:!1,toolDetails:!0,assistantMetadata:!0};function nR(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function rR(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 sR(e,t){if(e.type==="text"&&!e.synthetic)return`${e.text??""}
|
|
22
22
|
|
|
23
23
|
`;if(e.type==="reasoning")return t.thinking?`> _Thinking:_
|
|
24
24
|
>
|
|
@@ -35,13 +35,13 @@ ${r}
|
|
|
35
35
|
\`\`\`
|
|
36
36
|
|
|
37
37
|
</details>
|
|
38
|
-
`}catch{}if(t.toolDetails&&e.state?.status==="completed"&&e.state.output){let r=e.state.output,
|
|
38
|
+
`}catch{}if(t.toolDetails&&e.state?.status==="completed"&&e.state.output){let r=e.state.output,s=r.length>2e3?r.slice(0,2e3)+`
|
|
39
39
|
... (truncated)`:r;n+=`
|
|
40
40
|
<details>
|
|
41
41
|
<summary>Output</summary>
|
|
42
42
|
|
|
43
43
|
\`\`\`
|
|
44
|
-
${
|
|
44
|
+
${s}
|
|
45
45
|
\`\`\`
|
|
46
46
|
|
|
47
47
|
</details>
|
|
@@ -51,15 +51,15 @@ ${o}
|
|
|
51
51
|
${e.state.error}
|
|
52
52
|
\`\`\`
|
|
53
53
|
`),n+=`
|
|
54
|
-
`,n}return""}function
|
|
54
|
+
`,n}return""}function oR(e,t){if(!t)return`## Assistant
|
|
55
55
|
|
|
56
|
-
`;let n=e.agent?
|
|
56
|
+
`;let n=e.agent?nR(e.agent):"Assistant",r=e.modelID||"",s="";e.time?.completed&&e.time?.created&&(s=rR(e.time.completed-e.time.created));let o=[r,s].filter(Boolean).join(" \xB7 ");return o?`## ${n} (${o})
|
|
57
57
|
|
|
58
58
|
`:`## ${n}
|
|
59
59
|
|
|
60
|
-
`}function
|
|
60
|
+
`}function iR(e,t,n){let r="";e.role==="user"?r+=`## User
|
|
61
61
|
|
|
62
|
-
`:r+=
|
|
62
|
+
`:r+=oR(e,n.assistantMetadata);for(let s of t)r+=sR(s,n);return r}function aR(e,t,n=cb){let r=`# ${e.title||"Untitled Session"}
|
|
63
63
|
|
|
64
64
|
`;r+=`**Session ID:** \`${e.id}\`
|
|
65
65
|
`,r+=`**Created:** ${new Date(e.time.created).toLocaleString()}
|
|
@@ -67,32 +67,32 @@ ${e.state.error}
|
|
|
67
67
|
|
|
68
68
|
`,r+=`---
|
|
69
69
|
|
|
70
|
-
`;for(let
|
|
70
|
+
`;for(let s of t)r+=iR(s.info,s.parts,n),r+=`---
|
|
71
71
|
|
|
72
|
-
`;return r}function
|
|
72
|
+
`;return r}function cR(e,t){return`session-${e}.md`}var Ni="An error occurred";var lR=["message","error","detail","error_description","msg","errors","data"];function Bi(e){let t=e.trim();for(let n=0;n<4;n++){let r=t.replace(/^(?:\d{3}\s+)?(?:[A-Za-z_$][\w$]*)?Error:\s*/,"").trim();if(r===t)break;t=r}return t}function Vt(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function uR(e){let t=e.match(/"(?:message|detail|error_description|msg)"\s*:\s*"((?:[^"\\]|\\.)*)"/);if(!t)return;let n=Vt(`"${t[1]}"`);return typeof n=="string"&&n.trim()?n.trim():void 0}function pR(e){if(!/^\s*<(?:!doctype|html|head|body)\b/i.test(e))return;let t=e.toLowerCase(),n=dR(e,t);if(n)return n;let r=mR(e,t);return r?r.slice(0,200):void 0}function db(e){return Number.isNaN(e)?!0:!(e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122)}function lb(e,t){let n=e.indexOf(">",t);return n===-1?e.length:n+1}function dR(e,t){let n=0;for(;;){let r=t.indexOf("<title",n);if(r===-1)return;let s=r+6;if(!db(t.charCodeAt(s))){n=s;continue}let o=e.indexOf(">",s);if(o===-1)return;let i=e.indexOf("<",o+1);if(i!==-1&&t.startsWith("</title",i)){let a=e.slice(o+1,i).trim();if(a)return a}n=o+1}}var gR=["script","style"];function mR(e,t){let n=[],r=0;for(;r<e.length;){let s=e.indexOf("<",r);if(s===-1){n.push(e.slice(r));break}n.push(e.slice(r,s));let o=gR.find(i=>t.startsWith(`<${i}`,s)&&db(t.charCodeAt(s+i.length+1)));if(o){let i=t.indexOf(`</${o}`,s);r=i===-1?e.length:lb(e,i);continue}r=lb(e,s)}return n.join(" ").replace(/\s+/g," ").trim()}function fR(e){if(!e.startsWith("JSON parsing failed: Text:"))return;let t=e.match(/"model"\s*:\s*"([^"\\]{1,120})"/)?.[1]?.trim();return t?`The response from ${t} could not be read.`:"The model response could not be read."}function yR(e){let t=e.replace(/[_-]+/g," ").trim();return t&&t.charAt(0).toUpperCase()+t.slice(1)}function ub(e,t,n){if(typeof e=="string")return vs(e,t,n);if(e&&typeof e=="object")return As(e,t,n)}function vs(e,t,n=new WeakSet){let r=Bi(e);if(!r)return;if(t>=4)return r;let s=fR(r);if(s)return s;let o=Vt(r);if(o!==void 0)return typeof o=="string"?vs(o,t+1,n):o&&typeof o=="object"?As(o,t+1,n):String(o);let i=gb(r);if(i){let a=Vt(i);if(a&&typeof a=="object"){let l=As(a,t+1,n);if(l)return l}}if(r.includes("{")){let a=uR(r);if(a)return vs(a,t+1,n)??a}return pR(r)??r}function As(e,t,n=new WeakSet){if(t>=4||n.has(e))return;if(n.add(e),Array.isArray(e)){for(let i of e){let a=ub(i,t,n);if(a)return a}return}let r=e;for(let i of lR){let a=ub(r[i],t,n);if(a)return a}let s=r.type??r.code;if(typeof s=="string"&&s.trim())return yR(s);let o=r.status??r.statusCode??r.upstream_status;if(typeof o=="number"&&Number.isFinite(o))return`Request failed with status ${o}`}function _e(e){return e?typeof e=="string"?vs(e,0)??Ni:typeof e=="object"?As(e,0)??Ni:String(e):Ni}function Rs(e){let t=hR(e)?.trim();if(!t)return;let n=_e(e);if(!(t===n||Bi(t)===n))return t}function hR(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return;let t=e,n=t.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let{message:r,responseBody:s}=n,o=[r,s].filter((i,a,l)=>typeof i=="string"&&i.trim()!==""&&l.indexOf(i)===a);if(o.length>0)return o.join(`
|
|
73
73
|
|
|
74
|
-
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function
|
|
75
|
-
`||e==="\r"||e==="\u2028"||e==="\u2029"}function Ki(e){return e!==void 0&&
|
|
74
|
+
`)}if(typeof t.message=="string"&&t.message)return t.message;try{return JSON.stringify(e)}catch{return}}function gb(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(!(t===-1||n===-1||n<=t))return e.slice(t,n+1)}function _R(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(typeof t.message=="string"&&t.message)return t.message;if(typeof t.error=="string"&&t.error)return t.error;let n=t.data;if(typeof n?.message=="string")return n.message;let r=t.error;if(typeof r?.message=="string")return r.message}function bR(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n;!Number.isInteger(r.attempt)||r.attempt<1||typeof r.provider!="string"||!r.provider||typeof r.route_model!="string"||!r.route_model||typeof r.resolved_model!="string"||!r.resolved_model||typeof r.stage!="string"||!r.stage||typeof r.code!="string"&&!(typeof r.code=="number"&&Number.isFinite(r.code))||typeof r.message!="string"||!r.message||r.status!==void 0&&(!Number.isInteger(r.status)||r.status<100||r.status>599)||t.push({attempt:r.attempt,provider:r.provider,routeModel:r.route_model,resolvedModel:r.resolved_model,stage:r.stage,...typeof r.status=="number"?{status:r.status}:{},code:r.code,message:r.message})}return t.length>0?t:void 0}function pb(e){let t=typeof e.provider=="string"&&e.provider?e.provider:void 0,n=typeof e.code=="string"&&e.code?e.code:void 0,r=typeof e.suggestion=="string"&&e.suggestion?e.suggestion:void 0,s=typeof e.upstream_status=="number"?e.upstream_status:void 0,o=typeof e.request_id=="string"&&e.request_id?e.request_id:void 0,i=bR(e.attempt_failures),a=typeof e.requested_model=="string"&&e.requested_model?e.requested_model:void 0,l=typeof e.resolved_model=="string"&&e.resolved_model?e.resolved_model:void 0;return!t&&!n&&!r&&s===void 0&&!o&&!i?void 0:{message:typeof e.message=="string"&&e.message||_R(e)||"",provider:t,code:n,suggestion:r,upstreamStatus:s,requestId:o,attemptFailures:i,...a?{requestedModel:a}:{},...l?{resolvedModel:l}:{}}}function Pe(e){if(e==null)return;if(typeof e=="string"){let a=Bi(e),l=Vt(a)??Vt(gb(a));return l!==void 0?Pe(l):void 0}if(typeof e!="object")return;let t=e,n=pb(t),r=typeof t.name=="string"&&typeof t.data=="object";if(n&&!r)return n;let s=t.error;if(s&&typeof s=="object"&&!Array.isArray(s)){let a=pb(s);if(a)return a}let o=t.data;if(o&&typeof o.responseBody=="string"){let a=Vt(o.responseBody);if(a!==void 0){let l=Pe(a);if(l)return l}}if(o&&typeof o.message=="string"){let a=Pe(o.message);if(a)return a}let i=t.cause;if(i&&typeof i=="object"){let a=i.body;if(a!==void 0){let l=Pe(a);if(l)return l}}return n}var mb={};function V(e,t){for(let n of t)mb[n]=e}V("read",["read"]);V("list",["list","ls"]);V("glob",["glob"]);V("grep",["grep"]);V("write",["write"]);V("edit",["edit","multiedit","morph_edit","MultiEdit","NotebookEdit"]);V("apply_patch",["apply_patch","patch"]);V("bash",["bash"]);V("script",["codemode"]);V("web_search",["web_search","websearch","image_search"]);V("webfetch",["webfetch","web_fetch","scrape_webpage","scrapewebpage"]);V("media",["image_gen","video_gen"]);V("show",["show","show_user","presentation_gen"]);V("task",["task"]);V("delegate",["agent_spawn","agent_task","agent_task_create","agent_task_start","task_create","task_start","session_spawn","session_start_background","agent_message","agent_task_message","task_message","agent_task_update","task_update","session_message","agent_status","agent_task_list","agent_task_get","task_list","task_get","agent_stop","agent_task_cancel","task_cancel","agent_task_approve","task_approve","task_done","task_delete"]);V("todowrite",["todowrite","todo_write","todoread"]);V("question",["question","ask"]);V("memory",["memory","memory_search","mem_search","ltm_search","get_mem"]);V("connectors",["connector_get","connector_list","connector_setup","kortix_connector_call","kortix_connectors","kortix_connectors_connectors","kortix_connectors_discover","kortix_connectors_describe","kortix_connectors_call","kortix_connector_describe","kortix_connector_discover"]);V("automations",["triggers"]);V("skill",["skill"]);V("context",["prune","distill","compress","context_info"]);V("retired",["integration_list","integration_connect","integration_search","integration_actions","integration_run","integration_request","integration_exec"]);var SR=[["pty_","pty"],["agent_","delegate"],["task_","delegate"],["session_","sessions"],["trigger_","automations"],["project_","projects"]];function ce(e){let t=e.replace(/^oc[-_]/,"").replace(/-/g,"_"),n=mb[t];if(n)return n;for(let[r,s]of SR)if(t.startsWith(r))return s;return"other"}function Ie(e){for(let t of[e?.filePath,e?.file_path,e?.path,e?.notebook_path])if(typeof t=="string"&&t)return t}var xR=["site","filetype","ext","inurl","allinurl","intitle","allintitle","intext","allintext","inanchor","inbody","before","after","daterange","related","cache","define","link","source","lang","loc","location","imagesize"];function PR(){return new RegExp(`(^|\\s)([-+]?)(${xR.join("|")}):("[^"]*"|\\S+)`,"gi")}function wR(){return/(^|\s)-(?:"[^"]*"|\S+)/g}function kR(){return/(^|\s)(?:OR|AND)(?=\s|$)/g}function vR(e){return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function AR(e){return vR(e).replace(/^[a-z]+:\/\//i,"").replace(/^www\./i,"").replace(/\/.*$/,"").trim()}function fb(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} or ${e[e.length-1]}`}function Cs(e){let t=typeof e=="string"?e.trim():"";if(!t)return"";let n=[],r=t.replace(PR(),(s,o,i,a,l)=>{if(!i&&a.toLowerCase()==="site"){let p=AR(l);p&&!n.includes(p)&&n.push(p)}return o});return r=r.replace(wR(),"$1").replace(kR(),"$1").replace(/[()]/g," ").replace(/\s+/g," ").trim(),r?n.length>0?`${r} on ${fb(n)}`:r:n.length>0?fb(n):t}var RR=/\s/,CR=/\w/;function fe(e){return e!==void 0&&RR.test(e)}function Fn(e){return e===`
|
|
75
|
+
`||e==="\r"||e==="\u2028"||e==="\u2029"}function Ki(e){return e!==void 0&&CR.test(e)}function St(e){let t="";for(let n of e)t+=n.length===1?String.fromCharCode(TR(n.charCodeAt(0))):n;return t}function TR(e){if(e<128)return e>=97&&e<=122?e-32:e;let t=String.fromCharCode(e).toUpperCase();if(t.length!==1)return e;let n=t.charCodeAt(0);return n<128?e:n}function Ye(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t--;return e.slice(0,t)}function yb(e){let t=0;for(;t<e.length&&e[t]==="/";)t++;return Ye(e.slice(t))}function Nn(e,t,n){let r=e.indexOf(t);if(r===-1)return null;let s=e.indexOf(n,r+t.length);return s===-1?null:e.slice(r+t.length,s)}function qi(e,t){let n=Nn(e,`<${t}>`,`</${t}>`);return n===null?null:(n.startsWith(`
|
|
76
76
|
`)&&(n=n.slice(1)),n.endsWith(`
|
|
77
|
-
`)&&(n=n.slice(0,-1)),n)}function Gi(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let o=e.indexOf(">",r+1+t.length);return o===-1?null:{open:r,end:o}}function fb(e,t){let n=Gi(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function yb(e,t){let n=Gi(e,t);if(!n)return null;let r=e.indexOf(`</${t}>`,n.end+1);return r===-1?null:e.slice(n.end+1,r)}function hb(e,t){let n=`</${t}>`,r="",o=0;for(;;){let s=Gi(e,t,o);if(!s)break;let i=e.indexOf(n,s.end+1);if(i===-1)break;r+=e.slice(o,s.open),o=i+n.length}return r+e.slice(o)}function _b(e,t,n){let r=[];for(let o of e.split(/[\n\r\u2028\u2029]/)){let s=0;for(;;){let i=o.indexOf(t,s);if(i===-1)break;let a=o.indexOf(n,i+t.length);if(a===-1)break;r.push(o.slice(i+t.length,a)),s=a+n.length}}return r}function To(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&me(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function bb(e,t,n){let r=Pt(t),o=Pt(n);for(let s of Pt(e).split(/[\n\r\u2028\u2029]/)){let i=s.indexOf(r);if(i!==-1&&s.lastIndexOf(o)>=i+r.length)return!0}return!1}function Pb(e,t){let n=Pt(e),r=t.map(Pt),o=e.length,s=l=>{let p=l;for(;p<o&&me(e[p]);)p++;return p},i=l=>{for(let p=l;p<o;p++)if(Fn(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=o;){let l=s(a);if(l>=o)return null;let p=r.find(d=>n.startsWith(d,l));if(p!==void 0){let d=s(l+p.length);if(e[d]===":"){let g=s(d+1);if(g<o){let m=g;for(;m<o&&!Fn(e[m]);)m++;for(;m>g+1&&me(e[m-1]);)m--;return e.slice(g,m)}for(let m=o-1;m>d;m--)if(!Fn(e[m]))return e[m];return null}}a=i(l)}return null}function Sb(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=me(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!me(e[a-1]))continue;let l=a+1;if(me(e[l])){for(;l<t&&me(e[l]);)l++;Ki(e[l])&&(r[a]=a)}}let o=new Array(t+1);o[0]=0;for(let a=0;a<t;a++)o[a+1]=o[a]+(Fn(e[a])?1:0);let s=(a,l)=>o[l]===o[a],i=a=>{let l=a+1;for(;me(e[l]);)l++;let p=l;for(;p<t&&Ki(e[p]);)p++;return e.slice(l,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let l=a+7;for(;l<t&&/[a-z0-9]/.test(e[l]);)l++;if(l===a+7||e[l]!=="*"||e[l+1]!=="*")continue;let p=l+2,d=p;for(;d<t&&me(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(s(d,m))return{id:e.slice(a+2,l),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Fn(e[g]))return{id:e.slice(a+2,l),title:e[g],status:i(d)}}}}return null}function xb(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&me(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&me(e[i]);)i++;n=i}let r=e.slice(n),o="",s=0;for(;s<r.length;){if(t(r,s)&&(s===0||!Ki(r[s-1]))){let i=s,a=0;for(;t(r,i);){for(i+=6;i<r.length&&me(r[i]);)i++;a++}if(a>=2){s=i;continue}}o+=r[s],s++}return o}function wb(e,t){let n=t?"![":"[",r="",o=0,s=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let l=a+n.length;if(s<l&&(s=e.indexOf("]",l)),s===-1)break;let p=s;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(o,a)+(t?" ":e.slice(l,p)),o=i+1,a=e.indexOf(n,o)}return r+e.slice(o)}function kb(e){return wb(e,!0)}function vb(e){return wb(e,!1)}function AR(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Ab(e,t){let n=Pt(e),r=Pt(t),o=e.length,s=i=>{let a=i;for(;a<o&&me(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=s(i+r.length);if(e[a]!==":")continue;let l=s(a+1);for(let p=l;p<o;){if(!me(e[p])){p++;continue}let d=s(p);if(AR(e,d))return e.slice(l,p);p=d}return e.slice(l)}return null}var RR=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function hW(e){return RR.has(ce(e))}function _W(e){let t=0,n=0,r=0;for(let o of e){let s=ce(o.tool);s==="read"?t++:s==="glob"||s==="grep"?n++:s==="list"&&r++}return{read:t,search:n,list:r}}function Wi(e){if(!e)return"";let t=Ye(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Io(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Hi(e){let t=Ke(e),r=(t.state??{}).input??{};switch(ee(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=Ie(r);return i?Wi(i):""}case"glob":return r.pattern?String(r.pattern):"";case"grep":{let i=r.pattern??r.query,a=r.path??r.include;return i&&a?`"${Io(String(i),40)}" in ${Wi(String(a))}`:i?`"${Io(String(i),60)}"`:""}case"list":return r.path?Wi(String(r.path)):"";case"bash":return Io(String(r.command??""),80);default:break}let s=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let i of s){let a=r[i];if(typeof a=="string"&&a.length>0)return Io(i==="query"&&Co(a)||a,60)}return""}var CR={read:"Read",search:"Search",list:"List",shell:"Shell",edit:"Edit",write:"Write",fetch:"Fetch",webSearch:"Web Search",scrape:"Scrape",applyPatch:"Apply Patch",task:"Task",worker:"Worker",workspace:"Workspace"};function bW(e,t={}){let n=ge(e)?oe(e):e,r={...CR,...t},o=ee(n.tool),s=Hi(n);switch(o){case"read":return{title:r.read,subtitle:s};case"glob":case"grep":return{title:r.search,subtitle:s};case"list":return{title:r.list,subtitle:s};case"bash":return{title:r.shell,subtitle:s};case"edit":case"morph_edit":return{title:r.edit,subtitle:s};case"write":return{title:r.write,subtitle:s};case"webfetch":case"web_fetch":return{title:r.fetch,subtitle:s};case"websearch":case"web_search":return{title:r.webSearch,subtitle:s};case"scrape":case"scrape_webpage":return{title:r.scrape,subtitle:s};case"apply_patch":return{title:r.applyPatch,subtitle:s};case"task":return{title:r.task,subtitle:s};case"session_spawn":case"session_start_background":return{title:r.worker,subtitle:s};case"project_select":case"project_list":return{title:r.workspace,subtitle:s};default:return{title:o.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase()),subtitle:s}}}function Je(e){return e.type==="text"}function we(e){return e.type==="reasoning"}function te(e){return e.type==="tool"}function Cb(e){return e.type==="file"}function vW(e){return e.type==="agent"}function AW(e){return e.type==="compaction"}function RW(e){return e.type==="snapshot"}function CW(e){return e.type==="patch"}function TW(e){return e.type==="step-start"||e.type==="step-finish"}function IW(e){if(Je(e)||we(e))return e.text}function EW(e){if(!Cb(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function MW(e){let t=[],n=[];for(let r of e)Cb(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function OW(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function DW(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var TR=new Set(["todoread","context_info"]);function Kn(e){return!TR.has(ge(e)?e.name:e.tool)}var IR=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function Eo(e){let t=ge(e)?oe(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=ce(n);if(r==="task"||r==="delegate"){let o=t.state?.metadata?.sessionId;if(typeof o=="string"&&o)return o;if(r==="task"&&t.state?.status==="error")return t.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return ER(n,t.state)}function ER(e,t){let n=ee(e);if(IR.has(n)){let r=t?.title?.match(/\bses_[a-zA-Z0-9]+/);return r?r[0]:t?.output?.match(/\bses_[a-zA-Z0-9]+/)?.[0]}if(n==="session_spawn"||n==="session_start_background")return t?.output?.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/)?.[1]}function LW(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return he(n.error)}}function jW(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)te(r)&&Kn(r)&&t.push(r);return t}var MR={webfetch:{icon:"globe",title:"Web Fetch",subtitle:e=>e.url},websearch:{icon:"search",title:"Web Search",subtitle:e=>e.query},web_search:{icon:"search",title:"Web Search",subtitle:e=>e.query},scrape_webpage:{icon:"globe",title:"Scrape",subtitle:e=>e.urls?.split?.(",")[0]},image_search:{icon:"image",title:"Image Search",subtitle:e=>e.query},image_gen:{icon:"image",title:"Image Gen",subtitle:e=>e.prompt?.slice?.(0,40)},video_gen:{icon:"cpu",title:"Video Gen",subtitle:e=>e.prompt?.slice?.(0,40)},presentation_gen:{icon:"presentation",title:e=>{let t=e.action||"";return{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[t]||"Presentation"},subtitle:e=>e.slide_title||e.presentation_name},show:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},show_user:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},task:{icon:"square-kanban",title:e=>`Agent (${e.subagent_type||"task"})`,subtitle:e=>jR(e)},session_spawn:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},session_start_background:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},apply_patch:{icon:"file-pen",title:"Patch",subtitle:e=>e.files?.length?`${e.files.length} file${e.files.length>1?"s":""}`:void 0},todoread:{icon:"check-square",title:"Todos (read)"},prune:{icon:"scissors",title:"DCP Prune",subtitle:e=>e.reason},distill:{icon:"scissors",title:"DCP Distill"},compress:{icon:"scissors",title:"DCP Compress",subtitle:e=>e.topic},context_info:{icon:"scissors",title:"Context Info"},session_read:{icon:"glasses",title:e=>`Session Read (${e.mode||"summary"})`,subtitle:e=>e.session_id?.slice(-12)},session_search:{icon:"search",title:"Session Search",subtitle:e=>e.query},session_message:{icon:"message-circle",title:"Message \u2192 Session",subtitle:e=>e.session_id?.slice(-12)},session_lineage:{icon:"list-tree",title:"Session Lineage",subtitle:e=>e.session_id?.slice(-12)},session_list_background:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_list_spawned:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_stats:{icon:"layers",title:"Session Stats",subtitle:e=>e.session_id?.slice(-12)||"current"},session_list:{icon:"list",title:"Session List",subtitle:e=>e.search},session_get:{icon:"book-open",title:"Session Get",subtitle:e=>e.session_id?.slice(-12)},session_context:{icon:"book-open",title:"Session Context",subtitle:e=>e.session_id?.slice(-12)},project_delete:{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:e=>e.project},project_list:{icon:"folder",title:"Projects"},project_get:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_update:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_select:{icon:"folder",title:"Project Select",subtitle:e=>e.project},project_create:{icon:"folder-plus",title:"Project Create",subtitle:e=>e.name},triggers:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_create:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_list:{icon:"clock",title:"List Triggers"},trigger_get:{icon:"clock",title:"Trigger Details",subtitle:e=>e.name||e.id},trigger_delete:{icon:"clock",title:"Delete Trigger",subtitle:e=>e.name||e.id},trigger_update:{icon:"clock",title:"Update Trigger",subtitle:e=>e.name||e.id},trigger_test:{icon:"clock",title:"Test Trigger",subtitle:e=>e.name||e.id},trigger_pause:{icon:"clock",title:"Pause Trigger",subtitle:e=>e.name||e.id},trigger_resume:{icon:"clock",title:"Resume Trigger",subtitle:e=>e.name||e.id},agent_spawn:{icon:"cpu",title:e=>`Agent (${e.agent_type||"worker"})`,subtitle:e=>e.description},agent_message:{icon:"message-circle",title:"Agent Message",subtitle:e=>e.agent_id},agent_stop:{icon:"ban",title:"Agent Stop",subtitle:e=>e.agent_id},agent_status:{icon:"layers",title:"Agent Status"},agent_task:{icon:"check-square",title:"Create Task",subtitle:e=>e.title},agent_task_update:{icon:"check-square",title:"Update Task",subtitle:e=>e.task_id},agent_task_list:{icon:"check-square",title:"List Tasks"},agent_task_get:{icon:"check-square",title:"Task Details",subtitle:e=>e.task_id},task_create:{icon:"plus",title:"Create Task",subtitle:e=>e.title},task_list:{icon:"list",title:"Tasks",subtitle:e=>e.status||"all"},task_update:{icon:"refresh-cw",title:"Update Task",subtitle:e=>e.id},task_done:{icon:"check-circle",title:"Task Done",subtitle:e=>e.id},task_delete:{icon:"trash-2",title:"Delete Task",subtitle:e=>e.id},pty_spawn:{icon:"terminal",title:"Spawn",subtitle:e=>e.title||e.command},pty_read:{icon:"terminal",title:"Terminal Output",subtitle:e=>e.id},pty_write:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_input:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_kill:{icon:"terminal",title:"Kill Process",subtitle:e=>e.id}};function $W(e,t={}){let n=MR[ee(e)];if(!n)return OR(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function OR(e,t){switch(ce(e)){case"read":return{icon:"glasses",title:"Read",subtitle:DR(Ie(t))};case"list":return{icon:"list",title:"List",subtitle:LR(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":return{icon:"file-pen",title:"Edit",subtitle:Rb(Ie(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Rb(Ie(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function DR(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Rb(e){if(!e)return;let t=e.split("/"),n=t[t.length-1]||e;if(t.length<=1)return n;let r=t[t.length-2];return r?`${n} /${r}`:n}function LR(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function UW(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function Bn(e,t=120){if(typeof e!="string")return"";let n=e.split(`
|
|
78
|
-
`).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function
|
|
79
|
-
`):void 0),after:
|
|
80
|
-
`):
|
|
81
|
-
`))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function
|
|
82
|
-
|
|
83
|
-
`)}function wH(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function kH(e,t=2e3){let n=(e??"").trim();try{let r=JSON.parse(n);if(typeof r=="string")try{r=JSON.parse(r)}catch{}r&&typeof r=="object"&&(n=JSON.stringify(r,null,2))}catch{}return n.length>t?{text:n.slice(0,t).trimEnd(),truncatedChars:n.length-t}:{text:n,truncatedChars:0}}function vH(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=kb(n),n=vb(n),n=n.replace(/[#*_`>]+/g," "),n=n.replace(/\s+/g," ").trim(),n=n.replace(/\b(\w{2,})(?:\s+\1\b)+/gi,"$1"),n.length>t?n.slice(0,t).trimEnd()+"\u2026":n}function AH(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let o=r.error.trim(),s;for(let i=0;i<3;i++){let a=To(o);if(a===null)break;let l;try{l=JSON.parse(a)}catch{break}if(typeof l.status=="number"&&(s=l.status),typeof l.message=="string"&&l.message.trim())o=l.message.trim();else if(typeof l.error=="string"&&l.error.trim())o=l.error.trim();else break}return{message:o,status:s}}function Gn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function ta(e,t=30){if(!e)return[];let n=[],r=new Set,o=(a,l,p)=>{!/^https?:\/\//i.test(l)||r.has(l)||n.length>=t||(r.add(l),n.push({title:a.trim()||l,url:l,snippet:p?.trim()||void 0}))},s=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=s.exec(e))!==null;)if(o(Gn(i[1]),Gn(i[2]),i[3]?Gn(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(o(Gn(i[2]),Gn(i[1])),n.length>=t)return n}return n}function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wb(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{let r=JSON.parse(n);return typeof r=="object"&&r!==null?r:null}catch{}return null}}function jo(e){return e.filter(t=>it(t)&&!!t.title&&!!t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function Hb(e){if(!e)return[];let t=Wb(e,!0),n=t&&!Array.isArray(t)?t:void 0;if(n?.success===!1)return[];let r=n&&Array.isArray(n.results)?n.results:void 0;if(r&&r.length>0){let o=r[0];if(it(o)&&typeof o.query=="string"){let s=[];for(let i of r)!it(i)||typeof i.query!="string"||s.push({query:i.query,answer:i.answer||void 0,sources:Array.isArray(i.results)?jo(i.results):[]});if(s.length>0)return s}else if(it(o)&&(o.title||o.url)){let s=jo(r);if(s.length>0)return[{query:n?.query||"",answer:n?.answer||void 0,sources:s}]}}if(n?.query&&typeof n.query=="string")return[{query:n.query,answer:n.answer||void 0,sources:r?jo(r):[]}];if(Array.isArray(t)&&t.length>0){let o=t[0];if(it(o)&&(o.title||o.url)){let s=jo(t);if(s.length>0)return[{query:"",sources:s}]}}if(typeof e=="string"){let o=e.split(/(?=^Title: )/m).filter(Boolean),s=[];for(let i of o){let a=i.match(/^Title:\s*(.+)/m),l=i.match(/^URL:\s*(.+)/m),p=i.match(/^Author:\s*(.+)/m),d=i.match(/^Published Date:\s*(.+)/m),g=i.match(/^Text:\s*([\s\S]*?)$/m);a&&l&&s.push({title:a[1].trim(),url:l[1].trim(),snippet:g?.[1]?.trim()||void 0,author:p?.[1]?.trim()||void 0,publishedDate:d?.[1]?.trim()||void 0})}if(s.length>0)return[{query:"",sources:s}]}if(typeof e=="string"){let o=ta(e);if(o.length>0)return[{query:"",sources:o.map(s=>({title:s.title,url:s.url,snippet:s.snippet}))}]}return[]}function na(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function IH(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return na(e)}}function EH(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function MH(e){if(!e)return!1;let t=e.slice(0,600).toLowerCase();return t.includes("<!doctype html")||t.includes("<html")?!0:/<\/(body|head|div|p|span|table)>/i.test(e.slice(0,3e3))}function hC(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let o=r.trim();/^https?:\/\//i.test(o)&&n.push(o)}return n}return[]}function _C(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let o=Ab(n,r)?.trim()||n;return{url:r,success:!1,error:o}})}function OH(e,t){let n=bC(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?_C(r,hC(t)):[]}function bC(e){if(!e)return null;let t=Wb(e),n=t&&!Array.isArray(t)?t:void 0;if(!n)return null;if(n.results&&Array.isArray(n.results)){let r=n.results;return{total:n.total||r.length,successful:n.successful??r.filter(o=>it(o)&&o.success!==!1).length,failed:n.failed??r.filter(o=>it(o)&&o.success===!1).length,results:r.map(o=>{let s=it(o)?o:{};return{url:s.url||"",success:s.success!==!1,title:s.title||void 0,content:s.content||s.text||s.snippet||void 0,error:s.error||void 0}})}}if(typeof e=="string"){let r=ta(e);if(r.length>0)return{total:r.length,successful:r.length,failed:0,results:r.map(o=>({url:o.url,success:!0,title:o.title||void 0,content:o.snippet||void 0}))}}return null}function PC(e){if(typeof e!="string"||!e.trim())return null;try{let t=new URL(e.trim());return t.protocol==="http:"||t.protocol==="https:"?t.toString():null}catch{return null}}var SC={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",script:"script",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function Hn(e){return SC[ce(e)]}function $o(e){let t=ee(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var xC={run:"Terminal",memory:"Memory"};function NH(e){let t=Hn(e);return(t==="hidden"?void 0:xC[t])??$o(e)}function Wn(e,t,n){return e===1?t:n}function ra(e){return e.length===0?"":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function Yb(e){return e.length?Hi(e[0]):""}function Ee(e){return(e.state??{}).input??{}}var wC={agent_spawn:"spawn",agent_task:"spawn",agent_task_create:"spawn",agent_task_start:"spawn",task:"spawn",task_create:"spawn",task_start:"spawn",session_spawn:"spawn",session_start_background:"spawn",agent_message:"message",agent_task_message:"message",task_message:"message",session_message:"message",agent_status:"status",agent_task_list:"status",agent_task_get:"status",task_list:"status",task_get:"status",agent_stop:"stop",agent_task_cancel:"stop",task_cancel:"stop",agent_task_approve:"done",task_approve:"done",task_done:"done",task_delete:"delete"};function kC(e){let t=ee(e.tool);if(t==="agent_task_update"||t==="task_update")switch(Ee(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return wC[t]??"message"}function Vb(e){switch(e){case"create":return"create";case"update":return"update";case"delete":return"delete";case"test":return"test";case"pause":case"resume":return"control";case"list":case"get":return"read";default:return"unknown"}}function vC(e){let t=ee(e.tool);if(t==="triggers"){let r=Ee(e).action||"list";return Vb(r)}let n=t.match(/^trigger_(.+)$/);return Vb(n?n[1]:"list")}var AC={connector_setup:"connect",connector_get:"read",connector_list:"read",kortix_connector_discover:"read",kortix_connector_describe:"read",kortix_connectors:"read",kortix_connectors_connectors:"read",kortix_connectors_discover:"read",kortix_connectors_describe:"read",kortix_connector_call:"call",kortix_connectors_call:"call"};function RC(e){return AC[ee(e.tool)]??"read"}var CC={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function TC(e){return CC[ee(e.tool)]??"open"}function zt(e){return e.every(t=>t===e[0])}var IC={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function EC(e){if(ee(e.tool)!=="memory")return"read";let n=Ee(e).command;return n&&IC[n]||"unknown"}var MC={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},OC={create_slide:"Added a slide to a presentation",list_slides:"Checked a presentation's slides",list_presentations:"Checked your presentations",delete_slide:"Deleted a slide from a presentation",delete_presentation:"Deleted a presentation",validate_slide:"Checked a slide",export_pdf:"Exported a presentation to PDF",export_pptx:"Exported a presentation to PPTX",preview:"Previewed a presentation",serve:"Previewed a presentation"};function DC(e){let t=Ye(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function LC(e){let t=Ee(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return jC(r,60);let o=typeof t.path=="string"?t.path:"";if(o)return DC(o);let s=typeof t.url=="string"?t.url:"";if(s){let i=PC(s);return i?na(i):"a link"}return""}function jC(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function $C(e){let t=Ee(e).action;return t&&MC[t]||"Worked on an image"}function UC(e){let t=Ee(e).action;return t&&OC[t]||"Worked on a presentation"}function FC(e){return e.slice(0,e.indexOf(":"))}var NC={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},BC={create_slide:"presentation:create_slide",list_slides:"presentation:list_slides",list_presentations:"presentation:list_presentations",delete_slide:"presentation:delete_slide",delete_presentation:"presentation:delete_presentation",validate_slide:"presentation:validate_slide",export_pdf:"presentation:export_pdf",export_pptx:"presentation:export_pptx",preview:"presentation:preview",serve:"presentation:preview"};function KC(e){let t=ee(e.tool);if(t==="image_gen"){let n=Ee(e).action;return n&&NC[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=Ee(e).action;return n&&BC[n]||"presentation:unknown"}return"shown:result"}var qC=new Set(["create_slide","export_pdf","export_pptx"]);function BH(e){let t=Ke(e),n=ee(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=Ee(t).action;return r?qC.has(r)?"presentation":null:"presentation"}return null}var GC={"image:generate":e=>`Made ${e} images`,"image:edit":e=>`Edited ${e} images`,"image:upscale":e=>`Upscaled ${e} images`,"image:remove_bg":e=>`Removed backgrounds from ${e} images`,"image:unknown":e=>`Worked on ${e} images`,"video:create":e=>`Made ${e} videos`,"presentation:create_slide":e=>`Added ${e} slides`,"presentation:delete_slide":e=>`Deleted ${e} slides`,"presentation:delete_presentation":e=>`Deleted ${e} presentations`,"presentation:list_slides":()=>"Checked a presentation's slides","presentation:list_presentations":()=>"Checked your presentations","presentation:validate_slide":()=>"Checked slides","presentation:export_pdf":e=>`Exported ${e} presentations to PDF`,"presentation:export_pptx":e=>`Exported ${e} presentations to PPTX`,"presentation:preview":e=>`Previewed ${e} presentations`,"presentation:unknown":e=>`Worked on ${e} presentations`,"shown:result":e=>`Showed you ${e} results`},zb={image:"image",video:"video",presentation:"presentation",shown:"result"};function WC(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[FC(r)]++;let n=[];return Object.keys(t).forEach(r=>{let o=t[r];o&&n.push(`${o} ${Wn(o,zb[r],`${zb[r]}s`)}`)}),`Worked on ${ra(n)}`}function Uo(e,t){let n=t.map(Ke),r=n.length,o=Yb(n);switch(e){case"explore":{let s=n.filter(i=>ee(i.tool)==="read").length;return s===r?`Read ${r} ${Wn(r,"file","files")}`:s===0?"Looked through your files":`Looked through your files \xB7 ${s} read`}case"edit":{let s=new Set(n.map(a=>Ie(Ee(a))).filter(Boolean)).size||r,i=n.every(a=>ee(a.tool)==="write")?"Wrote":"Updated";return s===1?o?`${i} ${o}`:`${i} a file`:`${i} ${s} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"script":return r===1?"Ran a script":`Ran ${r} scripts`;case"web":{let s=p=>{let d=ee(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(s).length;if(i===r)return`Searched the web \xB7 ${r} ${Wn(r,"query","queries")}`;if(i===0)return`Read ${r} ${Wn(r,"page","pages")}`;let a=new Set;for(let p of n)if(s(p)){let d=p.state?.output;for(let g of Hb(d).flatMap(m=>m.sources))g.url&&a.add(g.url)}else{let d=p.state?.input?.url;typeof d=="string"&&d&&a.add(d)}let l=a.size||r;return`Searched and read ${l} ${Wn(l,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return $C(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return UC(i);let l=LC(i);return l?`Showed you ${l}`:"Showed you the result"}let s=n.map(KC);return zt(s)?GC[s[0]](r):WC(s)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let s=n.map(kC);if(zt(s))switch(s[0]){case"spawn":return r===1?"Asked a helper agent":`Worked with ${r} helper agents`;case"message":return r===1?"Sent instructions to a helper agent":`Sent instructions to ${r} helper agents`;case"status":return"Checked on a helper agent";case"stop":return r===1?"Stopped a helper agent":`Stopped ${r} helper agents`;case"done":return r===1?"A helper agent finished a task":`Helper agents finished ${r} tasks`;case"delete":return r===1?"Removed a task":`Removed ${r} tasks`}return r===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${r} steps`}case"sessions":return"Checked earlier work";case"memory":{let s=n.map(EC);if(zt(s))switch(s[0]){case"write":return r===1?"Wrote to its memory":`Wrote to its memory \xB7 ${r} updates`;case"delete":return r===1?"Deleted from its memory":`Deleted ${r} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let s=n.map(RC);if(zt(s))switch(s[0]){case"connect":return r===1?o?`Connected to ${o}`:"Connected a connector":`Connected ${r} connectors`;case"call":return r===1?"Used a connector":`Made ${r} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let s=n.map(vC);if(zt(s))switch(s[0]){case"create":return r===1?"Set up an automation":`Set up ${r} automations`;case"update":return r===1?"Updated an automation":`Updated ${r} automations`;case"delete":return r===1?"Deleted an automation":`Deleted ${r} automations`;case"control":return r===1?"Adjusted an automation":`Adjusted ${r} automations`;case"test":return r===1?"Tested an automation":`Tested ${r} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let s=n.map(TC);if(zt(s))switch(s[0]){case"delete":return r===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${r} projects \u2014 deletion isn't allowed`;case"create":return r===1?o?`Created ${o}`:"Created a project":`Created ${r} projects`;case"update":return r===1?o?`Updated ${o}`:"Updated your project":`Updated ${r} projects`;case"open":return r===1?o?`Opened ${o}`:"Opened your project":`Opened ${r} projects`}return o?`Worked in ${o}`:"Worked in your project"}case"skills":return r===1?o?`Used the ${o} skill`:"Used a skill":`Used ${r} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(r===1)return`Used ${$o(n[0].tool)}`;let s=Array.from(new Set(n.map(i=>$o(i.tool))));return s.length===1?`Used ${s[0]} \xB7 ${r} times`:`Used ${ra(s)}`}}}function Jb(e,t){let n=t.map(Ke),r=Yb(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let o=ee(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${o} ${r}`:`Couldn't ${o} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let o=n.filter(a=>a.state?.status==="error"),s=o.length?o:n,i=Array.from(new Set(s.map(a=>$o(a.tool))));return`Couldn't finish using ${ra(i)}`}}}var HC=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),VC={read:{verb:"Read",running:"Reading",objectKeys:["filePath","path","file"]},write:{verb:"Wrote",running:"Writing",objectKeys:["filePath","path","file"]},edit:{verb:"Edited",running:"Editing",objectKeys:["filePath","path","file"]},apply_patch:{verb:"Edited",running:"Editing",objectKeys:["filePath","path"]},bash:{verb:"Ran",running:"Running",objectKeys:["command"]},glob:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},grep:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},list:{verb:"Listed",running:"Listing",objectKeys:["path"]},web_search:{verb:"Searched",running:"Searching",objectKeys:["query"]},websearch:{verb:"Searched",running:"Searching",objectKeys:["query"]},webfetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},web_fetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},scrape:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},scrape_webpage:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},task:{verb:"Delegated",running:"Delegating",objectKeys:["description"]},memory:{verb:"Remembered",running:"Remembering"},get_mem:{verb:"Recalled",running:"Recalling"},memory_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},mem_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},ltm_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},dcp_compress:{verb:"Compacted",running:"Compacting"},dcp_distill:{verb:"Distilled",running:"Distilling"},dcp_prune:{verb:"Pruned",running:"Pruning"},compress:{verb:"Compacted",running:"Compacting"},distill:{verb:"Distilled",running:"Distilling"},prune:{verb:"Pruned",running:"Pruning"},context_info:{verb:"Checked context",running:"Checking context"}};function zC(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Co(t)||t}function YC(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim())return zC(r,o.trim())}}function Vn(e){let t=ge(e)?oe(e):e;if(we(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!te(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=ye(t.tool),r=VC[n],o=t.state?.input;return r?{verb:r.verb,running:r.running,object:YC(o,r.objectKeys),tier:HC.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function sa(e){let t=0,n=0,r=!1,o=!1;for(let s of e){if(Vn(s).tier==="plumbing"){r=!0;continue}if(we(s)){if(!s.text?.trim())continue;o||(o=!0,t+=1);continue}o=!1,t+=1,te(s)&&ea(s)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function oa(e){return`${e} ${e===1?"step":"steps"}`}function JC(e,t){let{total:n,failed:r,completed:o,hasPlumbing:s}=e;return t?n===0?"Working":`Working \xB7 ${oa(n)}`:n===0?s?"Housekeeping":"Worked":r===0?`Completed ${oa(n)}`:o===0?`${oa(n)} failed`:`Completed ${o} of ${n} steps \xB7 ${r} failed`}function Qb(e){let t=new Map,n=0;for(let o of e){if(!te(o)||Vn(o).tier==="plumbing")continue;let s=Hn(o.tool);s!=="hidden"&&(t.set(s,[...t.get(s)??[],o]),ea(o)!=="ok"&&(n+=1))}if(t.size===0)return JC(sa(e),!1);let r=[...t].map(([o,s],i)=>{let a=Uo(o,s);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function ZH(e){let t=!1,n=!1,r=!1,o=null,s=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),o==null&&d.error!=null&&(o=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},l=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");l&&(t=!0),e.userMessage&&s(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)s(p.info),i(p.parts);return l&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:o}}function QC(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function XC(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let o=r.state.time;typeof o?.start=="number"&&(t=Math.min(t,o.start)),typeof o?.end=="number"&&(n=Math.max(n,o.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function Xb(e,t){let n=t.map(Ke),r=QC(n);return{id:n[0].callID,family:e,label:r==="error"?Jb(e,n):Uo(e,n),parts:t,status:r,durationMs:r==="running"?void 0:XC(n)}}function Zb(e){let t=[],n=null,r=[],o=()=>{n&&r.length&&t.push(Xb(n,r)),n=null,r=[]};for(let s of e){let i=Ke(s),a=Hn(i.tool);if(a!=="hidden"&&!ei(i)){if($y(i.tool)){o(),t.push(Xb(a,[s]));continue}a!==n&&(o(),n=a),r.push(s)}}return o(),t}function ia(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function eP(e,t){let n=[],r=null,o=[],s=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:l}=r,p=typeof a=="number"&&typeof l=="number"&&l>a?l-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(o.length!==0){for(let a of Zb(o))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});o=[]}};for(let a of e)if(t(a)!=="plumbing"){if(we(a)){let l=a.text?.trim();if(!l)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(l);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=ia(a);continue}if(s(),te(a)){o.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}s(),i();for(let a=0;a<n.length-1;a++){let l=n[a];l.kind==="thought"&&(l.running=!1)}return n}var ZC=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function eT(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]*)`/g,"$1").replace(/^#{1,6}\s*/gm,"").replace(/\*\*([^*]*)\*\*/g,"$1").replace(/(^|\s)[*_]([^*_]+)[*_]/g,"$1$2").replace(/^\s*[-*+]\s+/gm,"").replace(/\s+/g," ").trim()}function aV(e){let t=e.flatMap(o=>{let s=eT(o);return s?[s]:[]}).join(" ").trim();return t?ZC.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function tT(e){return e?.info?.time??{}}function lV(e){let t=tT(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Fo=6e4,nT=10080*Fo,tP=1440;function nP(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function rT(e,t){let n=t.getTime()-e.getTime(),r=n/Fo,o=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return o(Math.round(r),"minute");if(r<tP)return o(Math.round(r/60),"hour");let s=(n-(nP(t)-nP(e)))/Fo;return o(Math.round(s/tP),"day")}function sP(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}var rP=new Map;function oT(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,o=rP.get(r);return o||(o=new Intl.DateTimeFormat(t.locale,n),rP.set(r,o)),o}function No(e,t,n){return oT(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?sT(r.value,n):r.value).join("")}function sT(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function oP(e,t){return No(e,{year:"numeric"},t)}function uV(e,t,n={}){let r=sP(e);if(!r)return"";let o=i=>No(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return o(!0);let s=Math.max(0,t-r.getTime());return s<Fo?"just now":s<nT?rT(r,new Date(t)):o(oP(r,n)!==oP(new Date(t),n))}function pV(e,t={}){let n=sP(e);if(!n)return"";let r=No(n,{month:"long",day:"numeric",year:"numeric"},t),o=No(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${o}`}function iP(e,t={}){let n=[],r=[],o=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let s of e)if(!Uy(s)){if(Je(s)){o(),n.push({kind:"text",part:s});continue}if(te(s)&&(Fy(s.tool)||!!t.standaloneCallIds?.has(s.callID))){o(),n.push({kind:"standalone",part:s});continue}r.push(s)}return o(),n}function iT(e){let t=ye(e);return t==="show"||t==="show_user"}function cP(e,t={}){let n=[],r=[],o=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(s=>s.part)}),r=[]};for(let s of e){if(s.kind==="standalone"&&iT(s.part.tool)&&!t.standaloneCallIds?.has(s.part.callID)){r.push(s);continue}o(),n.push(s)}return o(),n}var aT=["title","description","path","url","content","language","aspect_ratio","attachment"];function aP(e,t){if(!t||typeof t!="object")return null;let n=t;if(Zr(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let o of aT){let s=n[o];typeof s=="string"&&s&&(r[o]=s)}return r}function cT(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 lP(e){let t=[];for(let n of e){let r=n.state,o=r.input??{};if(r.status==="error"){let a=typeof o.title=="string"&&o.title?o.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let s=cT(o.items),i=s?s.map(a=>aP(n.callID,a)).filter(a=>!!a):[aP(n.callID,o)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function uP(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var zn=e=>"id"in e?e.id:e.userMessage.info.id,pP=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,lT=e=>e.time?.completed;function SV(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function uT(e,t){let n=zn(e);return t.pendingTurnIds.has(n)||pP(e)===0&&t.pendingPromptIds.has(n)}function xV(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(zn(r)));if(t)return zn(t);let n=e.turns.findIndex(r=>uT(r,e));return n<=0?null:zn(e.turns[n-1])}function wV(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function kV(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function vV(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:uP({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function AV(e,t){for(let n=e.length-1;n>=0;n--){let r=zn(e[n]);if(t(r))return pP(e[n])===0?r:null}return null}function dP(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),o=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(l=>l.userMessage.info.id)}),s=e.hintMessageId??null;if(s){if(n>=0&&t[n].userMessage.info.id===s)return o(n);let a=r.indexOf(s);if(a>=0)return o(n+1+a)}if(n>=0){let a=t[n],l=a.assistantMessages[a.assistantMessages.length-1];if(!lT(l.info)&&!l.info.error)return o(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return o(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:o(n)}function IV(e,t){for(let n=t.length-1;n>=0;n--)if(t[n].info.role==="user")return t[n].info.id===e;return!1}function EV(e,t){return!t||!e?!1:e.type!=="idle"}function MV(e,t){return!e&&!!t}function OV(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)?.message||he(n.error)}}function DV(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Ro(n.error)}}function LV(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return xe(n.error)}}function gP(e){if(e){if(te(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(we(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(Je(e))return"Gathering thoughts..."}}var pT=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function dT(e){if(!(!e||e.length===0))for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.info.role==="assistant")for(let r=n.parts.length-1;r>=0;r--){let o=gP(n.parts[r]);if(o)return o}}}function gT(e,t){let n=te(e)?e:void 0;if(n&&pT.has(n.tool)&&n.state.status==="running"){let r=dT(t);return r||(t?.length?"Handing off to an agent...":void 0)}return gP(e)}function mP(e,t){for(let n=e.length-1;n>=0;n--){let r=gT(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function fP(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}var yP=1.055;function hP(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),o=e.cache?.read??0,s=e.cache?.write??0,i=Math.max(0,n-o-s),l=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*l.inputPer1M;return p+=r/1e6*l.outputPer1M,o>0&&(p+=o/1e6*(l.cacheReadPer1M??l.inputPer1M)),s>0&&(p+=s/1e6*(l.cacheWritePer1M??l.inputPer1M)),p}function aa(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function _P(e,t,n,r){if(aa(t,n))return 0;let o=e.cost||0;if(o>0)return o;if(!r||!t||!n)return 0;let s=r(t,n);return s?hP(e.tokens,s):0}function bP(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function ca(e,t){let n=0,r=0,o=0,s=0,i=0,a=0,l=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){l=!0;let g=p,{providerID:m,modelID:f}=bP(d.info);n+=_P(g,m,f,t),r+=g.tokens?.input||0,o+=g.tokens?.output||0,s+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!l){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=PP(g,t),f=g.tokens&&aa(g.providerID,g.modelID);if(m<=0&&!f)continue;l=!0,n+=m;let _=g.tokens;_&&(r+=_.input??0,o+=_.output??0,s+=_.reasoning??0,i+=_.cache?.read??0,a+=_.cache?.write??0)}}if(l)return{cost:n*yP,tokens:{input:r,output:o,reasoning:s,cacheRead:i,cacheWrite:a}}}function PP(e,t){if(aa(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?hP({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function jV(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let o=r.info,{providerID:s,modelID:i}=bP(o),a=0,l=!1;for(let p of r.parts)p.type==="step-finish"&&(l=!0,a+=_P(p,s,i,t));l||(a+=PP(o,t)),n+=a}return n*yP}function $V(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function UV(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function FV(e){if(!e||e.type!=="retry")return;let t=e,n=he(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:xe(t.message)}}function NV(e){if(!(!e||e.type!=="retry"))return he(e.message)}function BV(e){return(e.info.summary?.diffs?.length??0)>0}function SP(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=ye(e.part.tool);return t==="show"||t==="show_user"}function mT(e){return e.kind==="text"&&!e.part.text?.trim()}function xP(e,t){if(t.working)return null;let n=-1;for(let o=e.length-1;o>=0;o--){let s=e[o];if(!(SP(s)||mT(s))){s.kind==="text"&&(n=o);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((o,s)=>{s===n?r.final.push(o):SP(o)?r.hoisted.push(o):r.work.push(o)}),r.work.length>0?r:null}function WV(e){let t=e==null?"":fP(e);return t?`Worked for ${t}`:"Worked"}function fT(e){let t=e.userMessage.parts;if(t.length===0||!t.every(s=>Je(s)&&s.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let o=r[0];return te(o)&&o.tool==="bash"}function zV(e){if(fT(e))return e.assistantMessages[0].parts[0]}function QV(e){if(!e)return"";let t=e;return t=t.replace(/^##\s*Worker Result\s*\n/i,""),t=t.replace(/^\*\*Agent:\*\*.*\n?/m,""),t=t.replace(/^\*\*Task:\*\*.*\n?/m,""),t=t.replace(/^\*\*Status:\*\*.*\n?/m,""),t=t.replace(/^\*\*Session:\*\*.*\n?/m,""),t=t.replace(/^\*\*Duration:\*\*.*\n?/m,""),t=hb(t,"kortix_goal_system"),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created and started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created:.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* failed to start.*$/gm,""),t=t.replace(/^Message sent to task.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* approved.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* cancelled.*$/gm,""),t=t.replace(/Worker session: ses_[a-zA-Z0-9]+/g,""),t=t.replace(/^---\s*\n/gm,""),t=t.trim(),t||""}function XV(e){return e?e.split(`
|
|
84
|
-
`).filter(n=>n.trim()).length<=3:!1}function
|
|
85
|
-
`).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function
|
|
86
|
-
`).filter(r=>r.trim());for(let r of n){let
|
|
87
|
-
`),r=n===-1?e:e.slice(0,n),
|
|
77
|
+
`)&&(n=n.slice(0,-1)),n)}function Gi(e,t,n=0){let r=e.indexOf(`<${t}`,n);if(r===-1)return null;let s=e.indexOf(">",r+1+t.length);return s===-1?null:{open:r,end:s}}function hb(e,t){let n=Gi(e,t);return n?e.slice(n.open+1+t.length,n.end):null}function _b(e,t){let n=Gi(e,t);if(!n)return null;let r=e.indexOf(`</${t}>`,n.end+1);return r===-1?null:e.slice(n.end+1,r)}function bb(e,t){let n=`</${t}>`,r="",s=0;for(;;){let o=Gi(e,t,s);if(!o)break;let i=e.indexOf(n,o.end+1);if(i===-1)break;r+=e.slice(s,o.open),s=i+n.length}return r+e.slice(s)}function Sb(e,t,n){let r=[];for(let s of e.split(/[\n\r\u2028\u2029]/)){let o=0;for(;;){let i=s.indexOf(t,o);if(i===-1)break;let a=s.indexOf(n,i+t.length);if(a===-1)break;r.push(s.slice(i+t.length,a)),o=a+n.length}}return r}function Ts(e){let t=e.trimEnd();if(!t.endsWith("}"))return null;let n=t.indexOf(":");for(;n!==-1;){let r=n+1;for(;r<t.length&&fe(t[r]);)r++;if(t[r]==="{")return t.slice(r);n=t.indexOf(":",n+1)}return null}function xb(e,t,n){let r=St(t),s=St(n);for(let o of St(e).split(/[\n\r\u2028\u2029]/)){let i=o.indexOf(r);if(i!==-1&&o.lastIndexOf(s)>=i+r.length)return!0}return!1}function Pb(e,t){let n=St(e),r=t.map(St),s=e.length,o=l=>{let p=l;for(;p<s&&fe(e[p]);)p++;return p},i=l=>{for(let p=l;p<s;p++)if(Fn(e[p]))return p+1;return-1},a=0;for(;a!==-1&&a<=s;){let l=o(a);if(l>=s)return null;let p=r.find(d=>n.startsWith(d,l));if(p!==void 0){let d=o(l+p.length);if(e[d]===":"){let g=o(d+1);if(g<s){let m=g;for(;m<s&&!Fn(e[m]);)m++;for(;m>g+1&&fe(e[m-1]);)m--;return e.slice(g,m)}for(let m=s-1;m>d;m--)if(!Fn(e[m]))return e[m];return null}}a=i(l)}return null}function wb(e){let t=e.length,n=new Array(t+1);n[0]=0;for(let a=1;a<=t;a++)n[a]=fe(e[a-1])?n[a-1]:a;let r=new Array(t+1).fill(-1);for(let a=t-1;a>=0;a--){if(r[a]=r[a+1],e[a]!=="\u2014"||!fe(e[a-1]))continue;let l=a+1;if(fe(e[l])){for(;l<t&&fe(e[l]);)l++;Ki(e[l])&&(r[a]=a)}}let s=new Array(t+1);s[0]=0;for(let a=0;a<t;a++)s[a+1]=s[a]+(Fn(e[a])?1:0);let o=(a,l)=>s[l]===s[a],i=a=>{let l=a+1;for(;fe(e[l]);)l++;let p=l;for(;p<t&&Ki(e[p]);)p++;return e.slice(l,p)};for(let a=e.indexOf("**task-");a!==-1;a=e.indexOf("**task-",a+1)){let l=a+7;for(;l<t&&/[a-z0-9]/.test(e[l]);)l++;if(l===a+7||e[l]!=="*"||e[l+1]!=="*")continue;let p=l+2,d=p;for(;d<t&&fe(e[d]);)d++;if(d!==p){if(d<t&&d+2<=t){let g=r[d+2]??-1;if(g!==-1){let m=Math.max(d+1,n[g]);if(o(d,m))return{id:e.slice(a+2,l),title:e.slice(d,m),status:i(g)}}}if(d<t&&r[d]===d){for(let g=d-2;g>=p+1;g--)if(!Fn(e[g]))return{id:e.slice(a+2,l),title:e[g],status:i(d)}}}}return null}function Wi(e){let t=(i,a)=>i.slice(a,a+6).toLowerCase()==="error:",n=0;for(;;){let i=n;for(;i<e.length&&fe(e[i]);)i++;if(!t(e,i))break;for(i+=6;i<e.length&&fe(e[i]);)i++;n=i}let r=e.slice(n),s="",o=0;for(;o<r.length;){if(t(r,o)&&(o===0||!Ki(r[o-1]))){let i=o,a=0;for(;t(r,i);){for(i+=6;i<r.length&&fe(r[i]);)i++;a++}if(a>=2){o=i;continue}}s+=r[o],o++}return s}function kb(e,t){let n=t?"![":"[",r="",s=0,o=-2,i=-2;for(let a=e.indexOf(n);a!==-1;){let l=a+n.length;if(o<l&&(o=e.indexOf("]",l)),o===-1)break;let p=o;if(e[p+1]!=="("){a=e.indexOf(n,p+1);continue}if(i<p+2&&(i=e.indexOf(")",p+2)),i===-1)break;r+=e.slice(s,a)+(t?" ":e.slice(l,p)),s=i+1,a=e.indexOf(n,s)}return r+e.slice(s)}function vb(e){return kb(e,!0)}function Ab(e){return kb(e,!1)}function IR(e,t){let n=e.slice(t,t+8).toLowerCase();return n.startsWith("http://")||n.startsWith("https://")}function Rb(e,t){let n=St(e),r=St(t),s=e.length,o=i=>{let a=i;for(;a<s&&fe(e[a]);)a++;return a};for(let i=n.indexOf(r);i!==-1;i=n.indexOf(r,i+1)){let a=o(i+r.length);if(e[a]!==":")continue;let l=o(a+1);for(let p=l;p<s;){if(!fe(e[p])){p++;continue}let d=o(p);if(IR(e,d))return e.slice(l,p);p=d}return e.slice(l)}return null}var ER=new Set(["read","glob","grep","list"]);function ee(e){return e.replace(/^oc-/,"").replace(/-/g,"_")}function wW(e){return ER.has(ce(e))}function kW(e){let t=0,n=0,r=0;for(let s of e){let o=ce(s.tool);o==="read"?t++:o==="glob"||o==="grep"?n++:o==="list"&&r++}return{read:t,search:n,list:r}}function Hi(e){if(!e)return"";let t=Ye(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function Is(e,t=60){if(!e)return"";let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}\u2026`:n}function Vi(e){let t=Ke(e),r=(t.state??{}).input??{};switch(ee(t.tool)){case"read":case"edit":case"write":case"morph_edit":{let i=Ie(r);return i?Hi(i):""}case"glob":return r.pattern?String(r.pattern):"";case"grep":{let i=r.pattern??r.query,a=r.path??r.include;return i&&a?`"${Is(String(i),40)}" in ${Hi(String(a))}`:i?`"${Is(String(i),60)}"`:""}case"list":return r.path?Hi(String(r.path)):"";case"bash":return Is(String(r.command??""),80);default:break}let o=["description","query","url","filePath","file_path","path","pattern","name","prompt"];for(let i of o){let a=r[i];if(typeof a=="string"&&a.length>0)return Is(i==="query"&&Cs(a)||a,60)}return""}var MR={read:"Read",search:"Search",list:"List",shell:"Shell",edit:"Edit",write:"Write",fetch:"Fetch",webSearch:"Web Search",scrape:"Scrape",applyPatch:"Apply Patch",task:"Task",worker:"Worker",workspace:"Workspace"};function vW(e,t={}){let n=me(e)?se(e):e,r={...MR,...t},s=ee(n.tool),o=Vi(n);switch(s){case"read":return{title:r.read,subtitle:o};case"glob":case"grep":return{title:r.search,subtitle:o};case"list":return{title:r.list,subtitle:o};case"bash":return{title:r.shell,subtitle:o};case"edit":case"morph_edit":return{title:r.edit,subtitle:o};case"write":return{title:r.write,subtitle:o};case"webfetch":case"web_fetch":return{title:r.fetch,subtitle:o};case"websearch":case"web_search":return{title:r.webSearch,subtitle:o};case"scrape":case"scrape_webpage":return{title:r.scrape,subtitle:o};case"apply_patch":return{title:r.applyPatch,subtitle:o};case"task":return{title:r.task,subtitle:o};case"session_spawn":case"session_start_background":return{title:r.worker,subtitle:o};case"project_select":case"project_list":return{title:r.workspace,subtitle:o};default:return{title:s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase()),subtitle:o}}}function Je(e){return e.type==="text"}function we(e){return e.type==="reasoning"}function te(e){return e.type==="tool"}function Tb(e){return e.type==="file"}function EW(e){return e.type==="agent"}function MW(e){return e.type==="compaction"}function OW(e){return e.type==="snapshot"}function DW(e){return e.type==="patch"}function jW(e){return e.type==="step-start"||e.type==="step-finish"}function LW(e){if(Je(e)||we(e))return e.text}function $W(e){if(!Tb(e))return!1;let t=e.mime;return t.startsWith("image/")||t==="application/pdf"}function UW(e){let t=[],n=[];for(let r of e)Tb(r)?t.push(r):n.push(r);return{attachments:t,stickyParts:n}}function FW(e,t){let n=[];return e?.tool&&n.push(e.tool),t?.tool&&n.push(t.tool),n}function NW(e,t,n){return n.some(r=>r.messageID===t&&r.callID===e.callID)}var OR=new Set(["todoread","context_info"]);function Kn(e){return!OR.has(me(e)?e.name:e.tool)}var DR=new Set(["task","agent_spawn","agent_message","agent_task","agent_task_update","agent_task_message","agent_task_start","task_create","task_start","task_update","task_message"]);function Es(e){let t=me(e)?se(e):e,n=t.tool||"";if(n.startsWith("oc-"))return;let r=ce(n);if(r==="task"||r==="delegate"){let s=t.state?.metadata?.sessionId;if(typeof s=="string"&&s)return s;if(r==="task"&&t.state?.status==="error")return t.state.error?.match(/\btask_id:\s*(ses_[A-Za-z0-9]+)/)?.[1]}return jR(n,t.state)}function jR(e,t){let n=ee(e);if(DR.has(n)){let r=t?.title?.match(/\bses_[a-zA-Z0-9]+/);return r?r[0]:t?.output?.match(/\bses_[a-zA-Z0-9]+/)?.[0]}if(n==="session_spawn"||n==="session_start_background")return t?.output?.match(/\*?\*?Session:?\*?\*?\s*(ses_[a-zA-Z0-9]+)/)?.[1]}function BW(e){if(e)for(let t=e.length-1;t>=0;t--){let n=e[t]?.info;if(n?.role==="assistant"&&n.error)return _e(n.error)}}function KW(e){let t=[];for(let n of e)if(n.info.role==="assistant")for(let r of n.parts)te(r)&&Kn(r)&&t.push(r);return t}var LR={webfetch:{icon:"globe",title:"Web Fetch",subtitle:e=>e.url},websearch:{icon:"search",title:"Web Search",subtitle:e=>e.query},web_search:{icon:"search",title:"Web Search",subtitle:e=>e.query},scrape_webpage:{icon:"globe",title:"Scrape",subtitle:e=>e.urls?.split?.(",")[0]},image_search:{icon:"image",title:"Image Search",subtitle:e=>e.query},image_gen:{icon:"image",title:"Image Gen",subtitle:e=>e.prompt?.slice?.(0,40)},video_gen:{icon:"cpu",title:"Video Gen",subtitle:e=>e.prompt?.slice?.(0,40)},presentation_gen:{icon:"presentation",title:e=>{let t=e.action||"";return{create_slide:"Create Slide",list_slides:"List Slides",preview:"Preview",export_pdf:"Export PDF",export_pptx:"Export PPTX"}[t]||"Presentation"},subtitle:e=>e.slide_title||e.presentation_name},show:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},show_user:{icon:"globe",title:"Output",subtitle:e=>e.title||e.description},task:{icon:"square-kanban",title:e=>`Agent (${e.subagent_type||"task"})`,subtitle:e=>NR(e)},session_spawn:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},session_start_background:{icon:"square-kanban",title:e=>`Worker (${e.agent||"KortixWorker"})`,subtitle:e=>e.description||e.prompt?.slice(0,60)},apply_patch:{icon:"file-pen",title:"Patch",subtitle:e=>e.files?.length?`${e.files.length} file${e.files.length>1?"s":""}`:void 0},todoread:{icon:"check-square",title:"Todos (read)"},prune:{icon:"scissors",title:"DCP Prune",subtitle:e=>e.reason},distill:{icon:"scissors",title:"DCP Distill"},compress:{icon:"scissors",title:"DCP Compress",subtitle:e=>e.topic},context_info:{icon:"scissors",title:"Context Info"},session_read:{icon:"glasses",title:e=>`Session Read (${e.mode||"summary"})`,subtitle:e=>e.session_id?.slice(-12)},session_search:{icon:"search",title:"Session Search",subtitle:e=>e.query},session_message:{icon:"message-circle",title:"Message \u2192 Session",subtitle:e=>e.session_id?.slice(-12)},session_lineage:{icon:"list-tree",title:"Session Lineage",subtitle:e=>e.session_id?.slice(-12)},session_list_background:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_list_spawned:{icon:"layers",title:"Background Sessions",subtitle:e=>e.project||"all"},session_stats:{icon:"layers",title:"Session Stats",subtitle:e=>e.session_id?.slice(-12)||"current"},session_list:{icon:"list",title:"Session List",subtitle:e=>e.search},session_get:{icon:"book-open",title:"Session Get",subtitle:e=>e.session_id?.slice(-12)},session_context:{icon:"book-open",title:"Session Context",subtitle:e=>e.session_id?.slice(-12)},project_delete:{icon:"trash-2",title:"Workspace Delete Disabled",subtitle:e=>e.project},project_list:{icon:"folder",title:"Projects"},project_get:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_update:{icon:"folder",title:"Project",subtitle:e=>e.name||e.project},project_select:{icon:"folder",title:"Project Select",subtitle:e=>e.project},project_create:{icon:"folder-plus",title:"Project Create",subtitle:e=>e.name},triggers:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_create:{icon:"clock",title:"Create Trigger",subtitle:e=>e.name},trigger_list:{icon:"clock",title:"List Triggers"},trigger_get:{icon:"clock",title:"Trigger Details",subtitle:e=>e.name||e.id},trigger_delete:{icon:"clock",title:"Delete Trigger",subtitle:e=>e.name||e.id},trigger_update:{icon:"clock",title:"Update Trigger",subtitle:e=>e.name||e.id},trigger_test:{icon:"clock",title:"Test Trigger",subtitle:e=>e.name||e.id},trigger_pause:{icon:"clock",title:"Pause Trigger",subtitle:e=>e.name||e.id},trigger_resume:{icon:"clock",title:"Resume Trigger",subtitle:e=>e.name||e.id},agent_spawn:{icon:"cpu",title:e=>`Agent (${e.agent_type||"worker"})`,subtitle:e=>e.description},agent_message:{icon:"message-circle",title:"Agent Message",subtitle:e=>e.agent_id},agent_stop:{icon:"ban",title:"Agent Stop",subtitle:e=>e.agent_id},agent_status:{icon:"layers",title:"Agent Status"},agent_task:{icon:"check-square",title:"Create Task",subtitle:e=>e.title},agent_task_update:{icon:"check-square",title:"Update Task",subtitle:e=>e.task_id},agent_task_list:{icon:"check-square",title:"List Tasks"},agent_task_get:{icon:"check-square",title:"Task Details",subtitle:e=>e.task_id},task_create:{icon:"plus",title:"Create Task",subtitle:e=>e.title},task_list:{icon:"list",title:"Tasks",subtitle:e=>e.status||"all"},task_update:{icon:"refresh-cw",title:"Update Task",subtitle:e=>e.id},task_done:{icon:"check-circle",title:"Task Done",subtitle:e=>e.id},task_delete:{icon:"trash-2",title:"Delete Task",subtitle:e=>e.id},pty_spawn:{icon:"terminal",title:"Spawn",subtitle:e=>e.title||e.command},pty_read:{icon:"terminal",title:"Terminal Output",subtitle:e=>e.id},pty_write:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_input:{icon:"terminal",title:"Terminal Input",subtitle:e=>e.id},pty_kill:{icon:"terminal",title:"Kill Process",subtitle:e=>e.id}};function qW(e,t={}){let n=LR[ee(e)];if(!n)return $R(e,t);let r=typeof n.title=="string"?n.title:n.title(t);return{icon:n.icon,title:r,subtitle:n.subtitle?.(t)}}function $R(e,t){switch(ce(e)){case"read":return{icon:"glasses",title:"Read",subtitle:UR(Ie(t))};case"list":return{icon:"list",title:"List",subtitle:FR(t.path)};case"glob":return{icon:"search",title:"Glob",subtitle:t.pattern};case"grep":return{icon:"search",title:"Grep",subtitle:t.pattern};case"bash":return{icon:"terminal",title:"Shell",subtitle:t.description};case"edit":return{icon:"file-pen",title:"Edit",subtitle:Cb(Ie(t))};case"write":return{icon:"file-pen",title:"Write",subtitle:Cb(Ie(t))};case"todowrite":return{icon:"check-square",title:"Todos"};case"question":return{icon:"message-circle",title:"Questions"};default:return{icon:"cpu",title:e}}}function UR(e){if(!e)return;let t=e.split("/");return t[t.length-1]||e}function Cb(e){if(!e)return;let t=e.split("/"),n=t[t.length-1]||e;if(t.length<=1)return n;let r=t[t.length-2];return r?`${n} /${r}`:n}function FR(e){if(!e)return;let t=e.lastIndexOf("/");if(!(t<0))return e.slice(0,t)||"/"}function GW(e,t){if(!t)return e;if(e.startsWith(t)){let n=e.slice(t.length);return n.startsWith("/")?n.slice(1):n}return e}function Bn(e,t=120){if(typeof e!="string")return"";let n=e.split(`
|
|
78
|
+
`).map(r=>r.trim()).find(Boolean);return n?n.length>t?`${n.slice(0,t).trim()}\u2026`:n:""}function NR(e){let t=Bn(e.description);if(t)return t;let n=Bn(e.title,80);if(n)return n;let r=Bn(e.message);if(r)return r;let s=Bn(e.prompt);if(s)return s;let o=Bn(e.agent_id,40);return o?`Agent ${o}`:"Worker task"}function WW(e,t){return!e||!t?[]:(e[t]??[]).filter(r=>r.severity===1).slice(0,3)}function HW(e,t){return e.find(n=>n.tool?.callID===t)}function VW(e,t){return e.find(n=>n.tool?.callID===t)}var BR=/\x1B\[[\d;]*[A-Za-z]|\x1B\][^\x07]{0,512}\x07|\x1B[()#][A-Z0-9]|\x1B\[?[\d;]*[hl]|\x1B[>=<]|\x1B\[[?]?\d*[A-Z]|\x1B\[\d*[JKHG]|\x1B\[\d*;\d*[Hf]|\x1b\[[0-9;]*m/g;function Ib(e){return e?e.replace(BR,""):""}function Ms(e){let t=Eb(e);return t?[t]:(Array.isArray(e?.edits)?e.edits:[]).flatMap(r=>{let s=r&&typeof r=="object"?Eb(r):void 0;return s?[s]:[]})}function Eb(e){let t=e?.oldString??e?.old_string??e?.oldText,n=e?.newString??e?.new_string??e?.newText;return typeof t=="string"&&typeof n=="string"?[t,n]:void 0}var KR={bash:"Shell",pty_spawn:"Spawn Terminal",pty_read:"Terminal Output",pty_write:"Terminal Input",pty_input:"Terminal Input",pty_kill:"Kill Process",read:"Read File",list:"List Directory",ls:"List Directory",write:"Write File",edit:"Edit File",multiedit:"Edit File",morph_edit:"Edit File",apply_patch:"Apply Patch",patch:"Apply Patch",grep:"Search Code",glob:"Find Files",image_search:"Image Search",session_search:"Search Sessions",webfetch:"Fetch Page",scrape_webpage:"Scrape Page",websearch:"Web Search",web_search:"Web Search",image_gen:"Generate Image",video_gen:"Generate Video",task:"Delegate to Agent",todowrite:"Plan Tasks",todoread:"Read Plan",question:"Ask Question",presentation_gen:"Presentation",show:"Show Output",show_user:"Show Output",prune:"Prune Context",distill:"Distill Context",compress:"Compress Context",context_info:"Context Info"},qR={read:"files",list:"files",glob:"search",grep:"search",write:"edit",edit:"edit",apply_patch:"edit",bash:"shell",pty:"shell",script:"shell",web_search:"web",webfetch:"web",media:"web",show:"task",task:"task",delegate:"task",sessions:"task",todowrite:"task",question:"task",automations:"task",projects:"task",memory:"other",connectors:"other",skill:"other",context:"other",retired:"other",other:"other"};function GR(e){return e.replace(/^oc[-_]/,"")}function Mb(e){return GR(e).replace(/-/g,"_")}function Ob(e){return Mb(e).split(/[_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}function zi(e){return{label:KR[Mb(e)]??Ob(e),category:qR[ce(e)]}}var WR=256*1024;function HR(e){switch(e.status){case"pending":return"pending";case"running":return"running";case"completed":return"done";case"error":return"error";default:return e}}function VR(e){if(e===void 0)return{};if(e.length>WR)return{outputText:e};try{return{outputParsed:JSON.parse(e),outputText:e}}catch{return{outputText:e}}}function zR(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e,n=t.success===!1,r=t.error,s=typeof r=="string"&&r.length>0||typeof r=="object"&&r!==null;if(!(!n&&!s))return s?_e(r):typeof t.message=="string"&&t.message?t.message:"Tool reported failure"}var de=e=>typeof e=="string"?e:void 0,Os=e=>typeof e=="number"?e:void 0,Ds=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0;function Yi(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}var YR=new Set(["add","update","delete","move"]);function JR(e,t,n){if(e==="apply_patch"){let p=(Array.isArray(n.files)?n.files:[]).flatMap(d=>{let g=Ds(d),m=g&&(de(g.relativePath)||de(g.filePath));if(!g||!m)return[];let f=de(g.type);return[Yi({path:m,type:f&&YR.has(f)?f:void 0,before:de(g.before),after:de(g.after),patch:de(g.patch)??de(g.diff),additions:Os(g.additions),deletions:Os(g.deletions),movePath:de(g.movePath)})]});return p.length?p:void 0}let r=Ie(t);if(!r)return;if(e==="read")return[{path:r}];if(e==="write")return[Yi({path:r,after:de(t.content)})];if(e!=="edit")return;let s=Ds(n.filediff),o=s?void 0:de(n.patch),i=o?QR(o):void 0,a=s||o?[]:Ms(t);return[Yi({path:r,before:de(s?.before)??(a.length?a.map(([l])=>l).join(`
|
|
79
|
+
`):void 0),after:de(s?.after)??(a.length?a.map(([,l])=>l).join(`
|
|
80
|
+
`):de(t.new_source)),patch:o,additions:Os(s?.additions)??i?.additions,deletions:Os(s?.deletions)??i?.deletions})]}function QR(e){let t=0,n=0;for(let r of e.split(`
|
|
81
|
+
`))r.startsWith("+")&&!r.startsWith("+++")?t++:r.startsWith("-")&&!r.startsWith("---")&&n++;return{additions:t,deletions:n}}function XR(e){let t=e.answers;if(Array.isArray(t))return t.map(n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[])}function Db(e,t){let n="title"in t?t.title:void 0,r=t.status==="completed"?t.output:void 0,{outputParsed:s,outputText:o}=VR(r),i=HR(t),a=t.status==="error"?t.error:void 0;if(i==="done"){let m=zR(s);m&&(i="error",a=m)}let l=ce(e),p=t.input??{},d="metadata"in t&&Ds(t.metadata)||{},g=Ds(d.diagnostics);return{name:e,kind:l,title:n||zi(e).label,status:i,input:t.input,output:r,outputParsed:s,outputText:o,error:a,files:JR(l,p,d),diff:de(d.patch)??de(d.diff),diagnostics:g,answers:l==="question"?XR(d):void 0,childSessionId:Es({tool:e,state:t})}}function jb(e){let t=me(e)?se(e):e;return Db(t.tool,t.state)}function ZR(e){return{kind:"text",id:e.id,text:e.text,synthetic:!!e.synthetic}}function eC(e){return{kind:"reasoning",id:e.id,text:e.text}}function tC(e){return{kind:"tool",id:e.id,tool:Db(e.tool,e.state)}}function nC(e){let t=e.mime;return{kind:"file",id:e.id,filename:e.filename,mime:t,url:e.url,isImage:t.startsWith("image/"),isPdf:t==="application/pdf"}}function rC(e){return{kind:"subtask",id:e.id,description:e.description,agent:e.agent,prompt:e.prompt,model:e.model}}function sC(e){return{kind:"patch",id:e.id,hash:e.hash,files:e.files,fileCount:e.files.length}}function oC(e){return{kind:"snapshot",id:e.id,snapshot:e.snapshot}}function iC(e){return{kind:"agent",id:e.id,name:e.name}}function aC(e){return{kind:"retry",id:e.id,attempt:e.attempt,message:_e(e.error),createdAt:e.time.created}}function cC(e){return{kind:"compaction",id:e.id,auto:e.auto,overflow:!!e.overflow,tailStartId:e.tail_start_id}}function lC(e){return{kind:"step",id:e.id,phase:"start",snapshot:e.snapshot}}function uC(e){return{kind:"step",id:e.id,phase:"finish",snapshot:e.snapshot,reason:e.reason,cost:e.cost,tokens:e.tokens}}function Lb(e){switch(e.type){case"text":return ZR(e);case"reasoning":return eC(e);case"tool":return tC(e);case"file":return nC(e);case"subtask":return rC(e);case"patch":return sC(e);case"snapshot":return oC(e);case"agent":return iC(e);case"retry":return aC(e);case"compaction":return cC(e);case"step-start":return lC(e);case"step-finish":return uC(e);default:return{kind:"unknown",raw:e}}}function pC(e){if(!e)return;let t=typeof e=="object"&&"name"in e&&typeof e.name=="string"?e.name:"Error",n=Pe(e);return{name:t,message:n?.message||_e(e),provider:n?.provider,code:n?.code,suggestion:n?.suggestion,upstreamStatus:n?.upstreamStatus,requestId:n?.requestId,attemptFailures:n?.attemptFailures}}function dC(e){switch(e.kind){case"text":case"reasoning":return e.text.trim().length>0;case"step":return!1;default:return!0}}function Ji(e){let t=e.parts.map(Lb),n=e.info.role==="assistant"?e.info.error:void 0,r=pC(n),s=!r&&!t.some(dC);return{parts:t,error:r,isEmpty:s}}var Qi=st+BigInt(1),$b=Qi/BigInt(2);function js(e){return BigInt(Math.trunc(e))*Pn}function Xi(e,t){let r=t-(t&st)+e;return r-t>$b?r-=Qi:t-r>$b&&(r+=Qi),r}function Ub(e,t){let n=Kt(e.info.id)??BigInt(0),r=e.info.time?.created;if(typeof r!="number")return Xi(n,t);let s=js(r),o=Xi(n,s);return(o>s?o-s:s-o)<=yt?o:s}function Fb(e){return Kt(e)===null?1:0}function Nb(e,t){return e<t?-1:e>t?1:0}function lH(e,t){return Zi(e,t,js(Date.now()))}function Bb(e){let t=null;for(let n of e){let r=n.info.time?.created;typeof r=="number"&&(t===null||r>t)&&(t=r)}return js(t??Date.now())}function Zi(e,t,n){let r=Fb(e.info.id),s=Fb(t.info.id);if(r!==s)return r-s;if(r===0){let a=Ub(e,n),l=Ub(t,n);return a!==l?a<l?-1:1:Nb(e.info.id,t.info.id)}let o=typeof e.info.time?.created=="number"?e.info.time.created:null,i=typeof t.info.time?.created=="number"?t.info.time.created:null;return o===null&&i===null?0:o===null?1:i===null?-1:o!==i?o<i?-1:1:Nb(e.info.id,t.info.id)}function uH(e){let t=new Map;for(let n of e){if(!n.parentID)continue;let r=t.get(n.parentID);r?r.push(n.id):t.set(n.parentID,[n.id])}return t}function pH(e){let t=e-6e4;return(n,r)=>{let s=n.time.updated??n.time.created,o=r.time.updated??r.time.created,i=s>t,a=o>t;return i&&a?n.id<r.id?-1:n.id>r.id?1:0:i&&!a?-1:!i&&a?1:o-s}}function gC(e,t){let n=e.get(t);if(!n||n.length===0)return[];let r=[];for(let s of n)r.push(s),r.push(...gC(e,s));return r}function fH(e,t){let n=new Map([...t?.pendingMessageIds??[]].map((d,g)=>[d,g])),r=Bb(e),s=[...e].sort((d,g)=>{let m=n.get(d.info.id),f=n.get(g.info.id);return m!==void 0&&f!==void 0?m-f:m!==void 0?1:f!==void 0?-1:Zi(d,g,r)}),o=[],i=new Map;for(let d of s)if(d.info.role==="user"){if(i.has(d.info.id))continue;let g={userMessage:d,assistantMessages:[]};o.push(g),i.set(d.info.id,g)}let a=null,l=[],p=[];for(let d of s){if(d.info.role==="user"){a=i.get(d.info.id)??null;continue}if(d.info.role!=="assistant")continue;let g=d.info,m=g.tokens;if(!(!g.error&&d.parts.length===0&&m?.input===0&&m.output===0&&m.reasoning===0)){if(g.parentID){let f=i.get(g.parentID);if(f){f.assistantMessages.push(d);continue}}if(a){a.assistantMessages.push(d);continue}if(g.parentID){let f=l[l.length-1];f&&f.userMessage.info.id===g.parentID?f.assistantMessages.push(d):l.push({userMessage:fC(g.parentID,d),assistantMessages:[d],partial:!0});continue}p.push(d)}}if(p.length>0){let d=o[0]??l[0];if(d)d.assistantMessages.unshift(...p);else{let[g,...m]=p;o.push({userMessage:g,assistantMessages:m})}}return l.length>0?[...l,...o]:o}var qn=new Map,mC=256;function fC(e,t){let n=t.info,r=n.time?.created,s=`${n.sessionID??""}|${e}|${r??""}`,o=qn.get(s);if(o)return o;let i={info:{id:e,role:"user",...n.sessionID?{sessionID:n.sessionID}:{},...typeof r=="number"?{time:{created:r}}:{}},parts:[]};if(qn.size>=mC){let a=qn.keys().next().value;a!==void 0&&qn.delete(a)}return qn.set(s,i),i}function yH(e){let t=[];for(let n of e.assistantMessages)for(let r of n.parts)t.push({part:r,message:n});return t}function hH(e){for(let t=e.length-1;t>=0;t--){let n=e[t].part;if(Je(n)&&n.text?.trim())return n}}function _H(e){return e.some(({part:t})=>t.type==="tool"||t.type==="compaction"||t.type==="snapshot"||t.type==="patch")}function bH(e,t,n){if(n)return[];let r=[];for(let s of e.assistantMessages)for(let o of s.parts){if(!te(o))continue;let i=o,a=i.state?.metadata?.answers;i.tool==="question"&&(a?.length??0)>0&&r.push({part:o,message:s})}return r}function yC(e){if(!e||typeof e!="object")return!1;let t=e.data;return!!t&&typeof t=="object"&&t.isRetryable===!0}function Kb(e){if(!e?.length)return!1;for(let t=e.length-1;t>=0;t--){let n=e[t].info;if(n.role==="assistant")return!n.time?.completed&&yC(n.error)}return!1}function Gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Gb(e){let t=e.trim();return t.length>500?!1:!!(/^Error:\s/i.test(t)||/^([\w._-]+Error|[\w._-]+Exception):\s/i.test(t)||/Traceback \(most recent call last\)/i.test(t)||/^\s*\[\s*\{[\s\S]*"message"\s*:/.test(t))}function kH(e){return!!e&&(Gb(e)||Wb(e)!==null)}function ea(e){let t=me(e)?se(e):e,n=qb.get(t);if(n&&n.state===t.state)return n.outcome;let r=hC(t);return qb.set(t,{state:t.state,outcome:r}),r}var qb=new WeakMap;function hC(e){let t=e.state;if(t.status==="error")return"failed";if(t.status!=="completed")return"ok";let n=typeof t.output=="string"?t.output.trim():"";if(!n)return"ok";if(Gb(n))return"failed";let r=_C(n);return r===void 0?"ok":bC(r)?"failed":SC(r)}function _C(e){try{return JSON.parse(e)}catch{return}}function bC(e){return Gn(e)&&e.success===!1&&typeof e.error=="string"}function SC(e){let t=Gn(e)?e.results:void 0;if(!Array.isArray(t)||t.length===0)return"ok";let n=t.filter(r=>r!==null&&typeof r=="object"&&r.success===!1).length;return n===0?"ok":n===t.length?"failed":"partial"}function Wb(e){let t=e.trim();if(!t)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Gn(n)||n.success!==!1||typeof n.error!="string")return null;let r={errorSummary:n.error.trim(),hint:typeof n.hint=="string"?n.hint.trim():void 0},s=xC.exec(Wi(r.errorSummary));s&&(r.status=Number(s[1]));let o=Ts(r.errorSummary);if(o===null)return r;try{let i=JSON.parse(o),a=PC(i);a&&(r.nestedMessage=a),typeof i.status=="number"&&(r.status=i.status),typeof i.error=="boolean"&&(r.nestedError=i.error)}catch{}return r}var xC=/^([1-5]\d{2}) Error\b/;function PC(e){let{message:t,error:n,detail:r}=e,s=[t,Gn(n)?n.message:void 0,Gn(r)?r.error:void 0,r];for(let o of s)if(typeof o=="string"&&o.trim())return o.trim()}function vH(e){return Wi(e).replace(/\s+/g," ").trim()||e.trim()}function AH(e){let t=Wb(e);if(!t)return null;let n=[];return n.push(t.errorSummary),t.nestedMessage!==void 0&&n.push(`Details: ${t.nestedMessage}`),t.hint&&n.push(`Hint: ${t.hint}`),n.join(`
|
|
82
|
+
|
|
83
|
+
`)}function TH(e){let t=(e??"").trimStart();return t.startsWith("{")||t.startsWith("[")}function IH(e,t=2e3){let n=(e??"").trim();try{let r=JSON.parse(n);if(typeof r=="string")try{r=JSON.parse(r)}catch{}r&&typeof r=="object"&&(n=JSON.stringify(r,null,2))}catch{}return n.length>t?{text:n.slice(0,t).trimEnd(),truncatedChars:n.length-t}:{text:n,truncatedChars:0}}function EH(e,t=200){let n=e??"";return n=n.replace(/\\n/g," "),n=vb(n),n=Ab(n),n=n.replace(/[#*_`>]+/g," "),n=n.replace(/\s+/g," ").trim(),n=n.replace(/\b(\w{2,})(?:\s+\1\b)+/gi,"$1"),n.length>t?n.slice(0,t).trimEnd()+"\u2026":n}function MH(e){let t=(e??"").trim();if(!t)return null;let n;try{if(n=JSON.parse(t),typeof n=="string")try{n=JSON.parse(n)}catch{return null}}catch{return null}if(!n||typeof n!="object"||Array.isArray(n))return null;let r=n;if(r.success!==!1||typeof r.error!="string"||!r.error.trim())return null;let s=r.error.trim(),o;for(let i=0;i<3;i++){let a=Ts(s);if(a===null)break;let l;try{l=JSON.parse(a)}catch{break}if(typeof l.status=="number"&&(o=l.status),typeof l.message=="string"&&l.message.trim())s=l.message.trim();else if(typeof l.error=="string"&&l.error.trim())s=l.error.trim();else break}return{message:s,status:o}}function Wn(e){try{return JSON.parse(`"${e}"`)}catch{return e}}function ta(e,t=30){if(!e)return[];let n=[],r=new Set,s=(a,l,p)=>{!/^https?:\/\//i.test(l)||r.has(l)||n.length>=t||(r.add(l),n.push({title:a.trim()||l,url:l,snippet:p?.trim()||void 0}))},o=/"title"\s*:\s*"((?:\\.|[^"\\])*)"\s*,\s*"url"\s*:\s*"((?:\\.|[^"\\])*)"(?:\s*,\s*"(?:snippet|content|text)"\s*:\s*"((?:\\.|[^"\\])*)")?/g,i;for(;(i=o.exec(e))!==null;)if(s(Wn(i[1]),Wn(i[2]),i[3]?Wn(i[3]):void 0),n.length>=t)return n;if(n.length===0){let a=/"url"\s*:\s*"((?:\\.|[^"\\])*)"[^{}]{0,400}?"title"\s*:\s*"((?:\\.|[^"\\])*)"/g;for(;(i=a.exec(e))!==null;)if(s(Wn(i[2]),Wn(i[1])),n.length>=t)return n}return n}function it(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hb(e,t=!1){if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;try{let n=JSON.parse(e);if(typeof n=="string")try{n=JSON.parse(n)}catch{}return typeof n=="object"?n:null}catch{let n=t&&e.trim().replace(/^\uFEFF/,"");if(n&&n!==e)try{let r=JSON.parse(n);return typeof r=="object"&&r!==null?r:null}catch{}return null}}function Ls(e){return e.filter(t=>it(t)&&!!t.title&&!!t.url).map(t=>({title:t.title,url:t.url,snippet:t.snippet||t.content||t.text||void 0,author:t.author||void 0,publishedDate:t.publishedDate||t.published_date||void 0}))}function Vb(e){if(!e)return[];let t=Hb(e,!0),n=t&&!Array.isArray(t)?t:void 0;if(n?.success===!1)return[];let r=n&&Array.isArray(n.results)?n.results:void 0;if(r&&r.length>0){let s=r[0];if(it(s)&&typeof s.query=="string"){let o=[];for(let i of r)!it(i)||typeof i.query!="string"||o.push({query:i.query,answer:i.answer||void 0,sources:Array.isArray(i.results)?Ls(i.results):[],...i.success===!1?{error:typeof i.error=="string"&&i.error.trim()||"Search failed"}:{}});if(o.length>0)return o}else if(it(s)&&(s.title||s.url)){let o=Ls(r);if(o.length>0)return[{query:n?.query||"",answer:n?.answer||void 0,sources:o}]}}if(n?.query&&typeof n.query=="string")return[{query:n.query,answer:n.answer||void 0,sources:r?Ls(r):[]}];if(Array.isArray(t)&&t.length>0){let s=t[0];if(it(s)&&(s.title||s.url)){let o=Ls(t);if(o.length>0)return[{query:"",sources:o}]}}if(typeof e=="string"){let s=e.split(/(?=^Title: )/m).filter(Boolean),o=[];for(let i of s){let a=i.match(/^Title:\s*(.+)/m),l=i.match(/^URL:\s*(.+)/m),p=i.match(/^Author:\s*(.+)/m),d=i.match(/^Published Date:\s*(.+)/m),g=i.match(/^Text:\s*([\s\S]*?)$/m);a&&l&&o.push({title:a[1].trim(),url:l[1].trim(),snippet:g?.[1]?.trim()||void 0,author:p?.[1]?.trim()||void 0,publishedDate:d?.[1]?.trim()||void 0})}if(o.length>0)return[{query:"",sources:o}]}if(typeof e=="string"){let s=ta(e);if(s.length>0)return[{query:"",sources:s.map(o=>({title:o.title,url:o.url,snippet:o.snippet}))}]}return[]}function na(e){try{return new URL(e).hostname.replace("www.","")}catch{return e}}function LH(e){try{let t=new URL(e).hostname.replace(/^www\./,""),n=t.split(".");return n.length<=2?t:n.slice(-2).join(".")}catch{return na(e)}}function $H(e){try{return`https://www.google.com/s2/favicons?domain=${new URL(e).hostname.replace(/^www\./,"")}&sz=128`}catch{return null}}function UH(e){if(!e)return!1;let t=e.slice(0,600).toLowerCase();return t.includes("<!doctype html")||t.includes("<html")?!0:/<\/(body|head|div|p|span|table)>/i.test(e.slice(0,3e3))}function wC(e){let t=e.urls??e.url;if(typeof t=="string")return t.split(/[\s,]+/).map(n=>n.trim()).filter(n=>/^https?:\/\//i.test(n));if(Array.isArray(t)){let n=[];for(let r of t){if(typeof r!="string")continue;let s=r.trim();/^https?:\/\//i.test(s)&&n.push(s)}return n}return[]}function kC(e,t){if(t.length===0)return[];let n=e.replace(/^Error:\s*/i,"").trim();return t.map(r=>{let s=Rb(n,r)?.trim()||n;return{url:r,success:!1,error:s}})}function FH(e,t){let n=vC(e);if(n?.results?.length)return n.results;let r=typeof e=="string"?e:"";return r.trim()?kC(r,wC(t)):[]}function vC(e){if(!e)return null;let t=Hb(e),n=t&&!Array.isArray(t)?t:void 0;if(!n)return null;if(n.results&&Array.isArray(n.results)){let r=n.results;return{total:n.total||r.length,successful:n.successful??r.filter(s=>it(s)&&s.success!==!1).length,failed:n.failed??r.filter(s=>it(s)&&s.success===!1).length,results:r.map(s=>{let o=it(s)?s:{};return{url:o.url||"",success:o.success!==!1,title:o.title||void 0,content:o.content||o.text||o.snippet||void 0,error:o.error||void 0}})}}if(typeof e=="string"){let r=ta(e);if(r.length>0)return{total:r.length,successful:r.length,failed:0,results:r.map(s=>({url:s.url,success:!0,title:s.title||void 0,content:s.snippet||void 0}))}}return null}function AC(e){if(typeof e!="string"||!e.trim())return null;try{let t=new URL(e.trim());return t.protocol==="http:"||t.protocol==="https:"?t.toString():null}catch{return null}}var RC={read:"explore",list:"explore",glob:"explore",grep:"explore",write:"edit",edit:"edit",apply_patch:"edit",bash:"run",pty:"run",script:"script",web_search:"web",webfetch:"web",media:"create",show:"create",task:"delegate",delegate:"delegate",sessions:"sessions",todowrite:"plan",question:"ask",memory:"memory",connectors:"connectors",automations:"automations",projects:"projects",skill:"skills",context:"hidden",retired:"retired",other:"other"};function Vn(e){return RC[ce(e)]}function $s(e){let t=ee(e).replace(/__+/g,"/");return(t.includes("/")?t.slice(t.lastIndexOf("/")+1):t).replace(/_/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase())}var CC={run:"Terminal",memory:"Memory"};function HH(e){let t=Vn(e);return(t==="hidden"?void 0:CC[t])??$s(e)}function Hn(e,t,n){return e===1?t:n}function ra(e){return e.length===0?"":e.length===1?e[0]:e.length===2?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`}function Jb(e){return e.length?Vi(e[0]):""}function Ee(e){return(e.state??{}).input??{}}var TC={agent_spawn:"spawn",agent_task:"spawn",agent_task_create:"spawn",agent_task_start:"spawn",task:"spawn",task_create:"spawn",task_start:"spawn",session_spawn:"spawn",session_start_background:"spawn",agent_message:"message",agent_task_message:"message",task_message:"message",session_message:"message",agent_status:"status",agent_task_list:"status",agent_task_get:"status",task_list:"status",task_get:"status",agent_stop:"stop",agent_task_cancel:"stop",task_cancel:"stop",agent_task_approve:"done",task_approve:"done",task_done:"done",task_delete:"delete"};function IC(e){let t=ee(e.tool);if(t==="agent_task_update"||t==="task_update")switch(Ee(e).action||""){case"start":return"spawn";case"cancel":return"stop";case"approve":return"done";default:return"message"}return TC[t]??"message"}function zb(e){switch(e){case"create":return"create";case"update":return"update";case"delete":return"delete";case"test":return"test";case"pause":case"resume":return"control";case"list":case"get":return"read";default:return"unknown"}}function EC(e){let t=ee(e.tool);if(t==="triggers"){let r=Ee(e).action||"list";return zb(r)}let n=t.match(/^trigger_(.+)$/);return zb(n?n[1]:"list")}var MC={connector_setup:"connect",connector_get:"read",connector_list:"read",kortix_connector_discover:"read",kortix_connector_describe:"read",kortix_connectors:"read",kortix_connectors_connectors:"read",kortix_connectors_discover:"read",kortix_connectors_describe:"read",kortix_connector_call:"call",kortix_connectors_call:"call"};function OC(e){return MC[ee(e.tool)]??"read"}var DC={project_get:"open",project_list:"open",project_select:"open",project_update:"update",project_create:"create",project_delete:"delete"};function jC(e){return DC[ee(e.tool)]??"open"}function zt(e){return e.every(t=>t===e[0])}var LC={view:"read",create:"write",str_replace:"write",insert:"write",rename:"write",delete:"delete"};function $C(e){if(ee(e.tool)!=="memory")return"read";let n=Ee(e).command;return n&&LC[n]||"unknown"}var UC={generate:"Made an image",edit:"Edited an image",upscale:"Upscaled an image",remove_bg:"Removed an image background"},FC={create_slide:"Added a slide to a presentation",list_slides:"Checked a presentation's slides",list_presentations:"Checked your presentations",delete_slide:"Deleted a slide from a presentation",delete_presentation:"Deleted a presentation",validate_slide:"Checked a slide",export_pdf:"Exported a presentation to PDF",export_pptx:"Exported a presentation to PPTX",preview:"Previewed a presentation",serve:"Previewed a presentation"};function NC(e){let t=Ye(e.replace(/\\/g,"/")),n=t.lastIndexOf("/");return n>=0?t.slice(n+1):t}function BC(e){let t=Ee(e),n=typeof t.title=="string"?t.title.trim():"";if(n)return n;let r=typeof t.description=="string"?t.description.trim():"";if(r)return KC(r,60);let s=typeof t.path=="string"?t.path:"";if(s)return NC(s);let o=typeof t.url=="string"?t.url:"";if(o){let i=AC(o);return i?na(i):"a link"}return""}function KC(e,t=60){let n=e.replace(/\s+/g," ").trim();return n.length>t?n.slice(0,t-1)+"\u2026":n}function qC(e){let t=Ee(e).action;return t&&UC[t]||"Worked on an image"}function GC(e){let t=Ee(e).action;return t&&FC[t]||"Worked on a presentation"}function WC(e){return e.slice(0,e.indexOf(":"))}var HC={generate:"image:generate",edit:"image:edit",upscale:"image:upscale",remove_bg:"image:remove_bg"},VC={create_slide:"presentation:create_slide",list_slides:"presentation:list_slides",list_presentations:"presentation:list_presentations",delete_slide:"presentation:delete_slide",delete_presentation:"presentation:delete_presentation",validate_slide:"presentation:validate_slide",export_pdf:"presentation:export_pdf",export_pptx:"presentation:export_pptx",preview:"presentation:preview",serve:"presentation:preview"};function zC(e){let t=ee(e.tool);if(t==="image_gen"){let n=Ee(e).action;return n&&HC[n]||"image:unknown"}if(t==="video_gen")return"video:create";if(t==="presentation_gen"){let n=Ee(e).action;return n&&VC[n]||"presentation:unknown"}return"shown:result"}var YC=new Set(["create_slide","export_pdf","export_pptx"]);function VH(e){let t=Ke(e),n=ee(t.tool);if(n==="image_gen")return"image";if(n==="video_gen")return"video";if(n==="presentation_gen"){let r=Ee(t).action;return r?YC.has(r)?"presentation":null:"presentation"}return null}var JC={"image:generate":e=>`Made ${e} images`,"image:edit":e=>`Edited ${e} images`,"image:upscale":e=>`Upscaled ${e} images`,"image:remove_bg":e=>`Removed backgrounds from ${e} images`,"image:unknown":e=>`Worked on ${e} images`,"video:create":e=>`Made ${e} videos`,"presentation:create_slide":e=>`Added ${e} slides`,"presentation:delete_slide":e=>`Deleted ${e} slides`,"presentation:delete_presentation":e=>`Deleted ${e} presentations`,"presentation:list_slides":()=>"Checked a presentation's slides","presentation:list_presentations":()=>"Checked your presentations","presentation:validate_slide":()=>"Checked slides","presentation:export_pdf":e=>`Exported ${e} presentations to PDF`,"presentation:export_pptx":e=>`Exported ${e} presentations to PPTX`,"presentation:preview":e=>`Previewed ${e} presentations`,"presentation:unknown":e=>`Worked on ${e} presentations`,"shown:result":e=>`Showed you ${e} results`},Yb={image:"image",video:"video",presentation:"presentation",shown:"result"};function QC(e){let t={image:0,video:0,presentation:0,shown:0};for(let r of e)t[WC(r)]++;let n=[];return Object.keys(t).forEach(r=>{let s=t[r];s&&n.push(`${s} ${Hn(s,Yb[r],`${Yb[r]}s`)}`)}),`Worked on ${ra(n)}`}function Us(e,t){let n=t.map(Ke),r=n.length,s=Jb(n);switch(e){case"explore":{let o=n.filter(i=>ee(i.tool)==="read").length;return o===r?`Read ${r} ${Hn(r,"file","files")}`:o===0?"Looked through your files":`Looked through your files \xB7 ${o} read`}case"edit":{let o=new Set(n.map(a=>Ie(Ee(a))).filter(Boolean)).size||r,i=n.every(a=>ee(a.tool)==="write")?"Wrote":"Updated";return o===1?s?`${i} ${s}`:`${i} a file`:`${i} ${o} files`}case"run":return r===1?"Ran a command":`Ran ${r} commands`;case"script":return r===1?"Ran a script":`Ran ${r} scripts`;case"web":{let o=p=>{let d=ee(p.tool);return d==="web_search"||d==="websearch"||d==="image_search"},i=n.filter(o).length;if(i===r)return`Searched the web \xB7 ${r} ${Hn(r,"query","queries")}`;if(i===0)return`Read ${r} ${Hn(r,"page","pages")}`;let a=new Set;for(let p of n)if(o(p)){let d=p.state?.output;for(let g of Vb(d).flatMap(m=>m.sources))g.url&&a.add(g.url)}else{let d=p.state?.input?.url;typeof d=="string"&&d&&a.add(d)}let l=a.size||r;return`Searched and read ${l} ${Hn(l,"source","sources")}`}case"create":{if(r===1){let i=n[0],a=ee(i.tool);if(a==="image_gen")return qC(i);if(a==="video_gen")return"Made a video";if(a==="presentation_gen")return GC(i);let l=BC(i);return l?`Showed you ${l}`:"Showed you the result"}let o=n.map(zC);return zt(o)?JC[o[0]](r):QC(o)}case"plan":return r===1?"Planned the work":`Planned the work \xB7 ${r} steps`;case"delegate":{let o=n.map(IC);if(zt(o))switch(o[0]){case"spawn":return r===1?"Asked a helper agent":`Worked with ${r} helper agents`;case"message":return r===1?"Sent instructions to a helper agent":`Sent instructions to ${r} helper agents`;case"status":return"Checked on a helper agent";case"stop":return r===1?"Stopped a helper agent":`Stopped ${r} helper agents`;case"done":return r===1?"A helper agent finished a task":`Helper agents finished ${r} tasks`;case"delete":return r===1?"Removed a task":`Removed ${r} tasks`}return r===1?"Worked with a helper agent":`Worked with helper agents \xB7 ${r} steps`}case"sessions":return"Checked earlier work";case"memory":{let o=n.map($C);if(zt(o))switch(o[0]){case"write":return r===1?"Wrote to its memory":`Wrote to its memory \xB7 ${r} updates`;case"delete":return r===1?"Deleted from its memory":`Deleted ${r} things from its memory`;case"read":return"Recalled what you told it before"}return"Worked with its memory"}case"connectors":{let o=n.map(OC);if(zt(o))switch(o[0]){case"connect":return r===1?s?`Connected to ${s}`:"Connected a connector":`Connected ${r} connectors`;case"call":return r===1?"Used a connector":`Made ${r} connector calls`;case"read":return"Checked your connectors"}return"Worked with your connectors"}case"automations":{let o=n.map(EC);if(zt(o))switch(o[0]){case"create":return r===1?"Set up an automation":`Set up ${r} automations`;case"update":return r===1?"Updated an automation":`Updated ${r} automations`;case"delete":return r===1?"Deleted an automation":`Deleted ${r} automations`;case"control":return r===1?"Adjusted an automation":`Adjusted ${r} automations`;case"test":return r===1?"Tested an automation":`Tested ${r} automations`;case"read":return"Checked your automations";case"unknown":return"Worked with your automations"}return"Worked with your automations"}case"projects":{let o=n.map(jC);if(zt(o))switch(o[0]){case"delete":return r===1?"Tried to delete a project \u2014 deletion isn't allowed":`Tried to delete ${r} projects \u2014 deletion isn't allowed`;case"create":return r===1?s?`Created ${s}`:"Created a project":`Created ${r} projects`;case"update":return r===1?s?`Updated ${s}`:"Updated your project":`Updated ${r} projects`;case"open":return r===1?s?`Opened ${s}`:"Opened your project":`Opened ${r} projects`}return s?`Worked in ${s}`:"Worked in your project"}case"skills":return r===1?s?`Used the ${s} skill`:"Used a skill":`Used ${r} skills`;case"ask":return"Asked you a question";case"retired":return"Used a connector that has since been removed";case"other":{if(r===1)return`Used ${$s(n[0].tool)}`;let o=Array.from(new Set(n.map(i=>$s(i.tool))));return o.length===1?`Used ${o[0]} \xB7 ${r} times`:`Used ${ra(o)}`}}}function Qb(e,t){let n=t.map(Ke),r=Jb(n);switch(e){case"explore":return"Couldn't read your files";case"edit":{if(n.length===1){let s=ee(n[0].tool)==="write"?"write":"update";return r?`Couldn't ${s} ${r}`:`Couldn't ${s} a file`}return"Couldn't update some files"}case"run":return"A command failed";case"script":return"A script failed";case"web":return"Couldn't finish searching the web";case"create":return"Couldn't finish making that";case"plan":return"Couldn't update the plan";case"delegate":return"A helper agent hit a problem";case"sessions":return"Couldn't check earlier work";case"memory":return"Couldn't reach its memory";case"connectors":return"Couldn't reach a connector";case"automations":return"Hit a problem with your automations";case"projects":return"Hit a problem with your project";case"skills":return"Couldn't use a skill";case"ask":return"Couldn't ask you a question";case"retired":return"Used a connector that has since been removed";case"other":{let s=n.filter(a=>a.state?.status==="error"),o=s.length?s:n,i=Array.from(new Set(o.map(a=>$s(a.tool))));return`Couldn't finish using ${ra(i)}`}}}var XC=new Set(["get_mem","memory_search","mem_search","ltm_search","dcp_compress","dcp_distill","dcp_prune","prune","distill","compress","context_info"]),ZC={read:{verb:"Read",running:"Reading",objectKeys:["filePath","path","file"]},write:{verb:"Wrote",running:"Writing",objectKeys:["filePath","path","file"]},edit:{verb:"Edited",running:"Editing",objectKeys:["filePath","path","file"]},apply_patch:{verb:"Edited",running:"Editing",objectKeys:["filePath","path"]},bash:{verb:"Ran",running:"Running",objectKeys:["command"]},glob:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},grep:{verb:"Searched",running:"Searching",objectKeys:["pattern"]},list:{verb:"Listed",running:"Listing",objectKeys:["path"]},web_search:{verb:"Searched",running:"Searching",objectKeys:["query"]},websearch:{verb:"Searched",running:"Searching",objectKeys:["query"]},webfetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},web_fetch:{verb:"Fetched",running:"Fetching",objectKeys:["url"]},scrape:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},scrape_webpage:{verb:"Scraped",running:"Scraping",objectKeys:["url"]},task:{verb:"Delegated",running:"Delegating",objectKeys:["description"]},memory:{verb:"Remembered",running:"Remembering"},get_mem:{verb:"Recalled",running:"Recalling"},memory_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},mem_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},ltm_search:{verb:"Recalled",running:"Recalling",objectKeys:["query"]},dcp_compress:{verb:"Compacted",running:"Compacting"},dcp_distill:{verb:"Distilled",running:"Distilling"},dcp_prune:{verb:"Pruned",running:"Pruning"},compress:{verb:"Compacted",running:"Compacting"},distill:{verb:"Distilled",running:"Distilling"},prune:{verb:"Pruned",running:"Pruning"},context_info:{verb:"Checked context",running:"Checking context"}};function eT(e,t){if(e==="filePath"||e==="path"||e==="file"){let n=t.split("/");return n[n.length-1]||t}return e==="query"&&Cs(t)||t}function tT(e,t){if(!t||typeof e!="object"||e===null)return;let n=e;for(let r of t){let s=n[r];if(typeof s=="string"&&s.trim())return eT(r,s.trim())}}function zn(e){let t=me(e)?se(e):e;if(we(t))return{verb:"Thought",running:"Thinking",object:void 0,tier:"reasoning"};if(!te(t))return{verb:"Used",running:"Using",object:void 0,tier:"primary"};let n=he(t.tool),r=ZC[n],s=t.state?.input;return r?{verb:r.verb,running:r.running,object:tT(s,r.objectKeys),tier:XC.has(n)?"plumbing":"primary"}:{verb:"Used",running:"Using",object:n,tier:"primary"}}function oa(e){let t=0,n=0,r=!1,s=!1;for(let o of e){if(zn(o).tier==="plumbing"){r=!0;continue}if(we(o)){if(!o.text?.trim())continue;s||(s=!0,t+=1);continue}s=!1,t+=1,te(o)&&ea(o)!=="ok"&&(n+=1)}return{total:t,failed:n,completed:t-n,hasPlumbing:r}}function sa(e){return`${e} ${e===1?"step":"steps"}`}function nT(e,t){let{total:n,failed:r,completed:s,hasPlumbing:o}=e;return t?n===0?"Working":`Working \xB7 ${sa(n)}`:n===0?o?"Housekeeping":"Worked":r===0?`Completed ${sa(n)}`:s===0?`${sa(n)} failed`:`Completed ${s} of ${n} steps \xB7 ${r} failed`}function Xb(e){let t=new Map,n=0;for(let s of e){if(!te(s)||zn(s).tier==="plumbing")continue;let o=Vn(s.tool);o!=="hidden"&&(t.set(o,[...t.get(o)??[],s]),ea(s)!=="ok"&&(n+=1))}if(t.size===0)return nT(oa(e),!1);let r=[...t].map(([s,o],i)=>{let a=Us(s,o);return i===0?a:a.charAt(0).toLowerCase()+a.slice(1)}).join(", ");return n>0?`${r} \xB7 ${n} failed`:r}function oV(e){let t=!1,n=!1,r=!1,s=null,o=p=>{let d=p;return d?.summary!==!0?!1:(t=!0,!d.time?.completed&&!d.error&&(r=!0),s==null&&d.error!=null&&(s=d.error),!0)},i=p=>{for(let d of p??[])d.type==="compaction"?(t=!0,n=!0):d.type==="text"&&d.text?.trim()&&(n=!0)},l=(e.userMessage?.parts??[]).some(p=>p.type==="compaction");l&&(t=!0),e.userMessage&&o(e.userMessage.info)&&i(e.userMessage.parts);for(let p of e.assistantMessages)o(p.info),i(p.parts);return l&&e.assistantMessages.length===0&&(r=!0),{isCompaction:t,hasContent:n,inFlight:r,error:s}}function rT(e){return e.some(t=>t.state?.status==="running"||t.state?.status==="pending")?"running":e.some(t=>t.state?.status==="error")?"error":"done"}function sT(e){let t=Number.POSITIVE_INFINITY,n=0;for(let r of e){let s=r.state.time;typeof s?.start=="number"&&(t=Math.min(t,s.start)),typeof s?.end=="number"&&(n=Math.max(n,s.end))}if(!(!Number.isFinite(t)||n<=t))return n-t}function Zb(e,t){let n=t.map(Ke),r=rT(n);return{id:n[0].callID,family:e,label:r==="error"?Qb(e,n):Us(e,n),parts:t,status:r,durationMs:r==="running"?void 0:sT(n)}}function eS(e){let t=[],n=null,r=[],s=()=>{n&&r.length&&t.push(Zb(n,r)),n=null,r=[]};for(let o of e){let i=Ke(o),a=Vn(i.tool);if(a!=="hidden"&&!ei(i)){if($y(i.tool)){s(),t.push(Zb(a,[o]));continue}a!==n&&(s(),n=a),r.push(o)}}return s(),t}function ia(e){let t=e.time?.end;return!(typeof t=="number"&&t>0)}function tS(e,t){let n=[],r=null,s=[],o=()=>{if(r&&r.texts.length>0){let{startedAt:a,endedAt:l}=r,p=typeof a=="number"&&typeof l=="number"&&l>a?l-a:void 0;n.push({kind:"thought",key:r.key,texts:r.texts,running:r.running,durationMs:p})}r=null},i=()=>{if(s.length!==0){for(let a of eS(s))n.push(a.parts.length===1?{kind:"part",key:a.parts[0].id,part:a.parts[0]}:{kind:"group",key:`group-${a.parts[0].id}`,step:a});s=[]}};for(let a of e)if(t(a)!=="plumbing"){if(we(a)){let l=a.text?.trim();if(!l)continue;i(),r||(r={key:`thought-${a.id}`,texts:[],running:!1}),r.texts.push(l);let p=a.time;r.startedAt===void 0&&typeof p?.start=="number"&&(r.startedAt=p.start),r.endedAt=typeof p?.end=="number"&&p.end>0?p.end:void 0,r.running=ia(a);continue}if(o(),te(a)){s.push(a);continue}i(),n.push({kind:"part",key:a.id,part:a})}o(),i();for(let a=0;a<n.length-1;a++){let l=n[a];l.kind==="thought"&&(l.running=!1)}return n}var oT=/^(thinking|thought|considering|planning|deciding|weighing|exploring|analy[sz]ing|reasoning|working out|figuring)/i;function iT(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`([^`]*)`/g,"$1").replace(/^#{1,6}\s*/gm,"").replace(/\*\*([^*]*)\*\*/g,"$1").replace(/(^|\s)[*_]([^*_]+)[*_]/g,"$1$2").replace(/^\s*[-*+]\s+/gm,"").replace(/\s+/g," ").trim()}function gV(e){let t=e.flatMap(s=>{let o=iT(s);return o?[o]:[]}).join(" ").trim();return t?oT.test(t)?t:`Thinking about ${/^[A-Z][a-z]/.test(t)?t[0].toLowerCase()+t.slice(1):t}`:"Thinking"}function aT(e){return e?.info?.time??{}}function fV(e){let t=aT(e).created;return typeof t!="number"||!Number.isFinite(t)||t<=0?null:t}var Fs=6e4,cT=10080*Fs,nS=1440;function rS(e){let t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}function lT(e,t){let n=t.getTime()-e.getTime(),r=n/Fs,s=(i,a)=>`${i} ${a}${i===1?"":"s"} ago`;if(r<60)return s(Math.round(r),"minute");if(r<nS)return s(Math.round(r/60),"hour");let o=(n-(rS(t)-rS(e)))/Fs;return s(Math.round(o/nS),"day")}function iS(e){if(typeof e!="number"||!Number.isFinite(e)||e<=0)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}var sS=new Map;function uT(e,t){let n={...e,...t.timeZone?{timeZone:t.timeZone}:{}},r=`${t.locale??""}|${JSON.stringify(n)}`,s=sS.get(r);return s||(s=new Intl.DateTimeFormat(t.locale,n),sS.set(r,s)),s}function Ns(e,t,n){return uT(t,n).formatToParts(e).map(r=>r.type==="dayPeriod"?pT(r.value,n):r.value).join("")}function pT(e,t){let n=/^([ap])\.?\s?m\.?$/i.exec(e.trim());return n?`${n[1].toUpperCase()}M`:e.toLocaleUpperCase(t.locale)}function oS(e,t){return Ns(e,{year:"numeric"},t)}function yV(e,t,n={}){let r=iS(e);if(!r)return"";let s=i=>Ns(r,{month:"long",day:"numeric",...i?{year:"numeric"}:{}},n);if(t===null)return s(!0);let o=Math.max(0,t-r.getTime());return o<Fs?"just now":o<cT?lT(r,new Date(t)):s(oS(r,n)!==oS(new Date(t),n))}function hV(e,t={}){let n=iS(e);if(!n)return"";let r=Ns(n,{month:"long",day:"numeric",year:"numeric"},t),s=Ns(n,{hour:"numeric",minute:"2-digit"},t);return`${r} ${s}`}function aS(e,t={}){let n=[],r=[],s=()=>{r.length>0&&(n.push({kind:"burst",parts:r}),r=[])};for(let o of e)if(!Uy(o)){if(Je(o)){s(),n.push({kind:"text",part:o});continue}if(te(o)&&(Fy(o.tool)||!!t.standaloneCallIds?.has(o.callID))){s(),n.push({kind:"standalone",part:o});continue}r.push(o)}return s(),n}function dT(e){let t=he(e);return t==="show"||t==="show_user"}function lS(e,t={}){let n=[],r=[],s=()=>{r.length===1?n.push(r[0]):r.length>1&&n.push({kind:"show-group",parts:r.map(o=>o.part)}),r=[]};for(let o of e){if(o.kind==="standalone"&&dT(o.part.tool)&&!t.standaloneCallIds?.has(o.part.callID)){r.push(o);continue}s(),n.push(o)}return s(),n}var gT=["title","description","path","url","content","language","aspect_ratio","attachment"];function cS(e,t){if(!t||typeof t!="object")return null;let n=t;if(es(n))return null;let r={callID:e,status:"ready",type:typeof n.type=="string"?n.type:""};for(let s of gT){let o=n[s];typeof o=="string"&&o&&(r[s]=o)}return r}function mT(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 uS(e){let t=[];for(let n of e){let r=n.state,s=r.input??{};if(r.status==="error"){let a=typeof s.title=="string"&&s.title?s.title:void 0;t.push({callID:n.callID,status:"error",type:"error",...a?{title:a}:{},error:typeof r.error=="string"?r.error:""});continue}let o=mT(s.items),i=o?o.map(a=>cS(n.callID,a)).filter(a=>!!a):[cS(n.callID,s)].filter(a=>!!a);if(i.length>0){t.push(...i);continue}(r.status==="running"||r.status==="pending")&&t.push({callID:n.callID,status:"pending",type:""})}return t}function pS(e){return!e.working||e.awaitingUser?!1:e.isRetrying?!0:!e.hasError}var Yn=e=>"id"in e?e.id:e.userMessage.info.id,dS=e=>"assistant"in e?e.assistant.length:e.assistantMessages.length,fT=e=>e.time?.completed;function RV(e){return!e.hasPendingTurns||!e.newestAssistantCompleted?!1:e.pendingDelivery||!!e.deliveringBelow||e.activeTurnId!==null&&e.activeTurnId!==e.workingTurnId}function yT(e,t){let n=Yn(e);return t.pendingTurnIds.has(n)||dS(e)===0&&t.pendingPromptIds.has(n)}function CV(e){let t=e.turns.find(r=>e.deliveringPromptIds.has(Yn(r)));if(t)return Yn(t);let n=e.turns.findIndex(r=>yT(r,e));return n<=0?null:Yn(e.turns[n-1])}function TV(e){return e.isTurnWorking&&!e.pendingDelivery&&e.activeTurnId===e.turnId}function IV(e){if(e.confirmedActive)return!1;let{workingTurnId:t,pendingTurnIds:n}=e.resolution;return e.sessionWorking&&(t===null?n[0]:t)===e.turnId?e.inboxPrompt?.state==="waiting"||e.inboxPrompt?.state==="failed":n.includes(e.turnId)||!!e.inboxPrompt}function EV(e){return!e.lastTurnWorking||e.workingTurnId===null||e.suppressed?!1:pS({working:!0,hasError:e.workingTurnHasError,isRetrying:e.isRetrying,awaitingUser:e.awaitingUser})}function MV(e,t){for(let n=e.length-1;n>=0;n--){let r=Yn(e[n]);if(t(r))return dS(e[n])===0?r:null}return null}function gS(e){let{turns:t}=e;if(t.length===0)return{workingTurnId:null,pendingTurnIds:[]};let n=-1;for(let a=t.length-1;a>=0;a--)if(t[a].assistantMessages.length>0){n=a;break}let r=t.slice(n+1).map(a=>a.userMessage.info.id),s=a=>({workingTurnId:t[a].userMessage.info.id,pendingTurnIds:t.slice(a+1).map(l=>l.userMessage.info.id)}),o=e.hintMessageId??null;if(o){if(n>=0&&t[n].userMessage.info.id===o)return s(n);let a=r.indexOf(o);if(a>=0)return s(n+1+a)}if(n>=0){let a=t[n],l=a.assistantMessages[a.assistantMessages.length-1];if(!fT(l.info)&&!l.info.error)return s(n)}let i=e.unrunTurnIds;if(r.length>0){for(let a=t.length-1;a>n;a--)if(!i?.has(t[a].userMessage.info.id))return s(a)}return n<0?{workingTurnId:null,pendingTurnIds:r}:s(n)}function LV(e,t){for(let n=t.length-1;n>=0;n--)if(t[n].info.role==="user")return t[n].info.id===e;return!1}function $V(e,t){return!t||!e?!1:e.type!=="idle"}function UV(e,t){return!e&&!!t}function FV(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Pe(n.error)?.message||_e(n.error)}}function NV(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Rs(n.error)}}function BV(e){for(let t of e.assistantMessages){let n=t.info;if(n.error)return Pe(n.error)}}function mS(e){if(e){if(te(e))switch(e.tool){case"task":case"session_spawn":case"session_start_background":case"session-spawn":case"session-start-background":return"Handing off to an agent...";case"agent_spawn":case"agent-spawn":case"agent_task":case"agent-task":return"Handing off to an agent...";case"agent_task_update":case"agent-task-update":case"task_update":case"task-update":return"Updating progress...";case"agent_message":case"agent-message":case"agent_task_message":case"agent-task-message":case"task_message":case"task-message":return"Checking in with an agent...";case"task_create":case"task-create":case"task_start":case"task-start":return"Starting a new task...";case"task_list":case"task-list":return"Reviewing the task list...";case"task_done":case"task-done":return"Updating progress...";case"todowrite":case"todoread":return"Planning...";case"read":return"Reading files...";case"list":case"grep":case"glob":return"Searching files...";case"webfetch":case"scrape-webpage":return"Reading a web page...";case"websearch":case"web-search":case"web_search":return"Searching the web...";case"image-search":return"Searching for images...";case"image-gen":return"Creating an image...";case"video-gen":return"Creating a video...";case"presentation-gen":return"Creating a presentation...";case"show":case"show-user":return"Sharing the result...";case"edit":case"write":case"morph_edit":return"Making changes...";case"bash":return"Working on the computer...";case"apply_patch":return"Making changes...";case"prune":return"Tidying up memory...";case"distill":return"Tidying up memory...";case"compress":return"Tidying up memory...";case"context_info":return"Refreshing memory...";default:return"Working on it..."}if(we(e)){let t=e.text?.trimStart();if(t){let n=t.match(/^\*\*(.+?)\*\*/);if(n)return`Thinking about ${n[1].trim()}...`}return"Thinking..."}if(Je(e))return"Gathering thoughts..."}}var hT=new Set(["task","agent_task","agent-task","task_create","task-create","task_start","task-start"]);function _T(e){if(!(!e||e.length===0))for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.info.role==="assistant")for(let r=n.parts.length-1;r>=0;r--){let s=mS(n.parts[r]);if(s)return s}}}function bT(e,t){let n=te(e)?e:void 0;if(n&&hT.has(n.tool)&&n.state.status==="running"){let r=_T(t);return r||(t?.length?"Handing off to an agent...":void 0)}return mS(e)}function fS(e,t){for(let n=e.length-1;n>=0;n--){let r=bT(e[n].part,t);if(r)return r}return"Figuring out what\u2019s next..."}function yS(e){if(!Number.isFinite(e)||e<1e3)return"";let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r>0?`${n}m ${r}s`:`${n}m`}var hS=1.055;function _S(e,t){if(!e)return 0;let n=e.input??0,r=(e.output??0)+(e.reasoning??0),s=e.cache?.read??0,o=e.cache?.write??0,i=Math.max(0,n-s-o),l=[...t.tiers??[],...t.contextOver200k?[t.contextOver200k]:[]].filter(d=>n>d.contextThreshold).sort((d,g)=>g.contextThreshold-d.contextThreshold)[0]??t,p=i/1e6*l.inputPer1M;return p+=r/1e6*l.outputPer1M,s>0&&(p+=s/1e6*(l.cacheReadPer1M??l.inputPer1M)),o>0&&(p+=o/1e6*(l.cacheWritePer1M??l.inputPer1M)),p}function aa(e,t){return e==="codex"||e==="openai-codex"||e==="kortix"&&!!t?.startsWith("codex/")}function bS(e,t,n,r){if(aa(t,n))return 0;let s=e.cost||0;if(s>0)return s;if(!r||!t||!n)return 0;let o=r(t,n);return o?_S(e.tokens,o):0}function SS(e){if(e.role!=="assistant")return{};let t=e;return{providerID:t.providerID,modelID:t.modelID}}function ca(e,t){let n=0,r=0,s=0,o=0,i=0,a=0,l=!1;for(let{part:p,message:d}of e)if(p.type==="step-finish"){l=!0;let g=p,{providerID:m,modelID:f}=SS(d.info);n+=bS(g,m,f,t),r+=g.tokens?.input||0,s+=g.tokens?.output||0,o+=g.tokens?.reasoning||0,i+=g.tokens?.cache?.read||0,a+=g.tokens?.cache?.write||0}if(!l){let p=new Set;for(let{message:d}of e){if(d.info.role!=="assistant")continue;let g=d.info;if(p.has(g.id))continue;p.add(g.id);let m=xS(g,t),f=g.tokens&&aa(g.providerID,g.modelID);if(m<=0&&!f)continue;l=!0,n+=m;let h=g.tokens;h&&(r+=h.input??0,s+=h.output??0,o+=h.reasoning??0,i+=h.cache?.read??0,a+=h.cache?.write??0)}}if(l)return{cost:n*hS,tokens:{input:r,output:s,reasoning:o,cacheRead:i,cacheWrite:a}}}function xS(e,t){if(aa(e.providerID,e.modelID)||!t||!e.providerID||!e.modelID||!e.tokens)return 0;let n=t(e.providerID,e.modelID);return n?_S({input:e.tokens.input,output:e.tokens.output,reasoning:e.tokens.reasoning,cache:e.tokens.cache},n):0}function KV(e,t){let n=0;for(let r of e){if(r.info?.role!=="assistant")continue;let s=r.info,{providerID:o,modelID:i}=SS(s),a=0,l=!1;for(let p of r.parts)p.type==="step-finish"&&(l=!0,a+=bS(p,o,i,t));l||(a+=xS(s,t)),n+=a}return n*hS}function qV(e){return e===0?"$0.00":e<.001?`$${e.toFixed(4)}`:e<.01?`$${e.toFixed(3)}`:`$${e.toFixed(2)}`}function GV(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function WV(e){if(!e||e.type!=="retry")return;let t=e,n=_e(t.message);return{attempt:t.attempt,message:n.length>60?`${n.slice(0,60)}...`:n,next:t.next,details:Pe(t.message)}}function HV(e){if(!(!e||e.type!=="retry"))return _e(e.message)}function VV(e){return(e.info.summary?.diffs?.length??0)>0}function PS(e){if(e.kind==="show-group")return!0;if(e.kind!=="standalone")return!1;let t=he(e.part.tool);return t==="show"||t==="show_user"}function ST(e){return e.kind==="text"&&!e.part.text?.trim()}function wS(e,t){if(t.working)return null;let n=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if(!(PS(o)||ST(o))){o.kind==="text"&&(n=s);break}}let r={work:[],hoisted:[],final:[]};return e.forEach((s,o)=>{o===n?r.final.push(s):PS(s)?r.hoisted.push(s):r.work.push(s)}),r.work.length>0?r:null}function QV(e){let t=e==null?"":yS(e);return t?`Worked for ${t}`:"Worked"}function xT(e){let t=e.userMessage.parts;if(t.length===0||!t.every(o=>Je(o)&&o.synthetic)||e.assistantMessages.length!==1)return!1;let r=e.assistantMessages[0].parts;if(r.length!==1)return!1;let s=r[0];return te(s)&&s.tool==="bash"}function ez(e){if(xT(e))return e.assistantMessages[0].parts[0]}function rz(e){if(!e)return"";let t=e;return t=t.replace(/^##\s*Worker Result\s*\n/i,""),t=t.replace(/^\*\*Agent:\*\*.*\n?/m,""),t=t.replace(/^\*\*Task:\*\*.*\n?/m,""),t=t.replace(/^\*\*Status:\*\*.*\n?/m,""),t=t.replace(/^\*\*Session:\*\*.*\n?/m,""),t=t.replace(/^\*\*Duration:\*\*.*\n?/m,""),t=bb(t,"kortix_goal_system"),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created and started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* created:.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* started\..*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* failed to start.*$/gm,""),t=t.replace(/^Message sent to task.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* approved.*$/gm,""),t=t.replace(/^Task \*\*task-[a-z0-9]+\*\* cancelled.*$/gm,""),t=t.replace(/Worker session: ses_[a-zA-Z0-9]+/g,""),t=t.replace(/^---\s*\n/gm,""),t=t.trim(),t||""}function sz(e){return e?e.split(`
|
|
84
|
+
`).filter(n=>n.trim()).length<=3:!1}function oz(e){if(!e)return null;let n=e.split(`
|
|
85
|
+
`).filter(r=>r.trim()&&!r.startsWith("#"))[0]?.replace(/^\*\*.*?\*\*\s*/,"").trim();return n?n.length>120?n.slice(0,120).trim()+"\u2026":n:null}function iz(e){if(!e)return[];let t=[],n=e.split(`
|
|
86
|
+
`).filter(r=>r.trim());for(let r of n){let s=wb(r);if(s){let o=r.match(/\bses_[a-zA-Z0-9]+/);t.push({...s,sessionId:o?.[0]})}}return t}var xt={write:{verb:"Wrote",running:"Writing",failed:"Couldn't write"},edit:{verb:"Edited",running:"Editing",failed:"Couldn't update"},delete:{verb:"Deleted",running:"Deleting",failed:"Couldn't delete"},rename:{verb:"Renamed",running:"Renaming",failed:"Couldn't rename"},change:{verb:"Changed",running:"Changing",failed:"Couldn't apply"},read:{verb:"Read",running:"Reading",failed:"Couldn't read"},list:{verb:"Listed",running:"Listing",failed:"Couldn't list"}};function cz(e,t){let n=xt[e];return t==="running"?n.running:t==="failed"?n.failed:n.verb}function lz(e,t){return t?"failed":e?"running":"done"}var dz={view:"View",create:"Create",str_replace:"Edit",insert:"Insert",delete:"Delete",rename:"Rename"};function gz(e){return e?e.replace(/^\.\//,"").replace(/^(?:\.kortix\/)?memory(?:\/|$)/,"").replace(/\/$/,"")||"memory":""}function mz(e,t){if(!e)return null;let n=e.indexOf(`
|
|
87
|
+
`),r=n===-1?e:e.slice(0,n),s=n===-1?"":e.slice(n+1);if(xb(r,"content of "," with line numbers"))return{type:"file",content:s.split(`
|
|
88
88
|
`).map(i=>i.replace(/^\s*\d+(\t|$)/,"")).join(`
|
|
89
|
-
`)};if(/files and directories/i.test(r)){let
|
|
90
|
-
`)){if(!a.trim())continue;let l=a.indexOf(" ");if(l===-1)continue;let p=a.slice(0,l).trim(),d=a.slice(l+1).trim();d!==
|
|
89
|
+
`)};if(/files and directories/i.test(r)){let o=t.replace(/\/$/,""),i=[];for(let a of s.split(`
|
|
90
|
+
`)){if(!a.trim())continue;let l=a.indexOf(" ");if(l===-1)continue;let p=a.slice(0,l).trim(),d=a.slice(l+1).trim();d!==o&&i.push({size:p,path:d,isDir:!/\.\w+$/.test(d)})}return{type:"dir",entries:i}}return null}var PT={add:{...xt.write,icon:"create"},delete:{...xt.delete,icon:"delete"},move:{...xt.rename,icon:"edit"},update:{...xt.edit,icon:"edit"}},kS={...xt.change,icon:"edit"};function hz(e){if(e.length===0)return kS;let t=vS(e[0]);for(let n=1;n<e.length;n++)if(vS(e[n])!==t)return kS;return PT[t]}function vS(e){return e==="add"||e==="delete"||e==="move"?e:"update"}function bz(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.startsWith("Error:")?{success:!1,action:"unknown",error:e.replace(/^Error:\s*/,"")}:null}}function AS(e,t){if(!e)return null;let n=/"([^"]*)"="([^"]*)"/g,r=[],s;for(;(s=n.exec(e))!==null;)r.push(s[2]);return r.length===0?null:Array.from({length:Math.max(t,r.length)},(o,i)=>r[i]?[r[i]]:[])}function wz(e){if(!e)return null;let t=Nn(e,"<path>","</path>"),n=t!==null?t.trim():void 0,r=qi(e,"content");if(r!==null){let o=r.split(`
|
|
91
91
|
`).map(i=>i.replace(/^\s*\d+:\s?/,"")).join(`
|
|
92
|
-
`);return{path:n,type:"file",content:
|
|
93
|
-
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:
|
|
94
|
-
\u2026`:e}function
|
|
92
|
+
`);return{path:n,type:"file",content:o}}let s=qi(e,"entries");if(s!==null){let o=s.split(`
|
|
93
|
+
`).map(i=>i.trim()).filter(i=>i&&!/^\(\d+\s+entr/i.test(i));return{path:n,type:"directory",entries:o}}return null}function Az(e){let t=_b(e,"skill_content");return t!==null?t.trim():e}function wT(e){let t=Nn(e,"<skill_files>","</skill_files>");return t===null?[]:Sb(t,"<file>","</file>").map(n=>n.trim())}function kT(e){let t=hb(e,"skill_content");if(t===null)return"";for(let n of["dir","directory","path","base","baseDir","base_dir"]){let r=t.match(new RegExp(`\\b${n}\\s*=\\s*["']([^"']+)["']`,"i"));if(r?.[1]?.trim())return r[1].trim()}return""}function vT(e){return Pb(e,["Base directory","Directory","Skill directory"])?.trim()??""}function AT(e){return Ye(kT(e)||vT(e))}function Rz(e){for(let t of["dir","directory","path","skillPath","location"]){let n=e[t];if(typeof n=="string"&&n.trim())return Ye(n.trim())}return""}var RT="skills";function CT(e){let t=yb(e?.trim()??"");if(!t||t.toLowerCase()==="skill")return"";let n=t.split("/").map(s=>s.trim());if(n.some(s=>s===".."||s==="."))return"";let r=n.at(-1)??"";return r?`${RT}/${r}`:""}function Cz(e,t,n){let s=Ye(t?.trim()??"")||AT(e)||CT(n),o=wT(e).find(i=>/(^|\/)SKILL\.md$/i.test(i));if(o){if(o.startsWith("/"))return o;if(s)return`${s}/${o}`}return s?`${s}/SKILL.md`:null}var TT=4e3;function Jn(e,t=TT){return e.length>t?`${e.slice(0,t)}
|
|
94
|
+
\u2026`:e}function RS(e){if(e!==void 0)try{return Jn(JSON.stringify(e,null,2))}catch{return}}function ne(...e){for(let t of e)if(typeof t=="string"&&t.length>0)return t}function Yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function IT(e){let t=ne(e.input?.query)??"";if(e.status==="error")return{kind:"web-search",query:t,error:e.error??"Search failed"};let n=Yt(e.outputParsed);if(!n)return{kind:"web-search",query:t};let s=(Array.isArray(n.results)?n.results:Array.isArray(n.images)?n.images:[]).slice(0,50).map(o=>{let i=Yt(o)??{};return{title:ne(i.title)??"",url:ne(i.url,i.link)??"",snippet:ne(i.snippet,i.description,i.source)}});return{kind:"web-search",query:ne(n.query)??t,results:s.length>0?s:void 0,answer:ne(n.answer)}}var ET=/<exit_code>\s*(-?\d+)\s*<\/exit_code>/;function TS(e){let t=e.match(ET);return t?Number(t[1]):void 0}function MT(e,t,n){let r="",s=0;for(;;){let o=e.indexOf(t,s);if(o===-1)return r+e.slice(s);let i=e.indexOf(n,o+t.length);if(i===-1)return r+e.slice(s);r+=e.slice(s,o),s=i+n.length}}var OT=["<system_info>","</system_info>","<exit_code>","</exit_code>","<stderr_note>","</stderr_note>"];function DT(e){let t=-1;for(let n of OT){let r=e.indexOf(n);r!==-1&&(t===-1||r<t)&&(t=r)}return t===-1?e:e.slice(0,t)}function jT(e){let t=ne(e.input?.command)??"",n=e.output??"",r=TS(n),o=Ib(DT(MT(n,"<bash_metadata>","</bash_metadata>"))).trim()||(e.status==="error"?e.error:void 0);return{kind:"shell",command:t,stdout:o||void 0,exitCode:r}}function ua(e){return ne(e.input?.filePath,e.input?.file_path,e.input?.path)??""}function LT(e){let t=e.status==="error"?e.error:e.output&&Jn(e.output)||void 0;return{kind:"file-read",path:ua(e),preview:t}}function $T(e){let t=ne(e.input?.content),n=e.status==="error"?e.error:Jn(t??e.output??"")||void 0;return{kind:"file-write",path:ua(e),preview:n}}var UT=256*1024;function FT(e,t){if(e.length+t.length>UT)return;let n=e.split(`
|
|
95
95
|
`),r=t.split(`
|
|
96
|
-
`),
|
|
97
|
-
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function UT(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=TP.test(e.output.trim())?jT(e.output):$T(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function FT(e){let t=ne(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=ne(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function la(e){let t=Yt(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function NT(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(la)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(la)};let n=Yt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(la)}:{kind:"todo",items:[]}}function BT(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let o=Yt(r)??{},i=(Array.isArray(o.options)?o.options:[]).flatMap(a=>{let l=Yt(a),p=l&&ne(l.label);return p?[{label:p,description:l?ne(l.description):void 0}]:[]});return{question:ne(o.question)??"",header:ne(o.header),options:i}})}}function KT(e){let n=e.input&&Object.keys(e.input).length>0?AP(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Yn(e.outputParsed):AP(e.outputParsed):e.outputText!==void 0?r=Yn(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function qT(e){switch(ce(e.name)){case"web_search":return kT(e);case"bash":return TT(e);case"read":return IT(e);case"write":return ET(e);case"edit":return DT(e);case"grep":case"glob":return UT(e);case"task":return FT(e);case"todowrite":return NT(e);case"question":return BT(e);default:return KT(e)}}var GT=new Set(["AbortError","MessageAbortedError"]),WT=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],HT=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function IP(e){let t=e.toLowerCase();return HT.some(n=>t.includes(n))?!1:WT.some(n=>t.includes(n))}function VT(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 Bo(e){if(typeof e=="string")return IP(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&>.has(n))return!0;let r=VT(t);return typeof r=="string"?IP(r):!1}var zT=["user","runtime-disposed","orphan-finalized","wake"],Cz=["orphan-finalized","wake"];function Tz(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 zT.includes(n)?n:void 0}var Ko="kortix-active-instance",YT=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function JT(e){return YT.some(t=>e===t||e.startsWith(`${t}/`))}function Jn(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 Ez(e){let t=Jn(e);return!!t&&t.innerPath===""}function Mz(e){let t=Jn(e);return!t||!t.innerPath?e:t.innerPath}function QT(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=Jn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return JT(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function XT(e){return e?Jn(e)?.instanceId??null:null}function Oz(){return typeof window>"u"?null:XT(window.location.pathname)||ZT()}function ZT(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Ko}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function Dz(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Ko}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Ko}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Ko}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function Lz(e,t){return t?QT(t,e):e}function jz(e){let t=Jn(e);return t?t.innerPath||"/dashboard":e}function Qn(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 EP(e){let t=Qn(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let o of n)if(o)try{return JSON.parse(o)}catch{}return null}var Uz=EP;function pa(e){let t=EP(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var Fz=pa;function eI(e){return pa(e)!==null}var Nz=eI,tI=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],Bz=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],nI=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function rI(e){return nI.test(Qn(e))}function Xn(e){let t=Qn(e);return t?rI(t)||tI.some(n=>n.test(t)):!1}var oI=/server url not ready|sandbox is still loading/i;function Kz(e){return oI.test(Qn(e))||Xn(e)}var qo=class extends Error{constructor(t){let n=t?.trim();super(n&&Xn(n)?n:n?`sandbox not ready: ${n}`:"sandbox not ready"),this.name="SandboxNotReadyError"}};function sI(e){let t=pa(e);if(t){let o=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),s=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${o} is preventing OpenCode from loading. ${a}`,detail:s?`${i?`${i}: `:""}${s}`:void 0}}let n=Qn(e);return Xn(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var qz=sI;function MP(e){if(!e.external_id){if(e.base_url)return e.base_url;throw new Error(`Cannot build sandbox URL: missing external_id for ${e.provider} sandbox "${e.sandbox_id}"`)}return`${nt()}/p/${e.external_id}/${tt.KORTIX_MASTER}`}function Vz(e,t){return e.external_id?`${nt()}/p/${e.external_id}/${t}`:null}async function Xz(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function iI(e){let t=await mn();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Rt())[0];if(!r)throw new Error("Create a project before starting a sandbox");let o=await Lt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),s=(await mt(r.project_id,o.session_id))?.sandbox??null;return{sandbox:Hr(r,o,s),created:!0}}async function Zz(){return(await mn().catch(()=>null))?.sandbox??null}async function eY(e){return{sandbox:(await iI(e)).sandbox}}async function tY(e){let t=gn(e);if(!t)return null;try{let n=await Hs(t);return n?Hr(await Ct(n.project_id),n,null):(await mn(t))?.sandbox??null}catch{return null}}async function nY(e,t){throw await Vr(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function rY(e){let t=gn(e);return(await Ws().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function oY(){return null}async function sY(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await Vr(e);if(!t)throw new Error("Project session sandbox not found");await $r(t.projectId,t.sessionId)}async function iY(e){if(!e)throw new Error("No sandbox selected to stop");let t=await Vr(e);if(!t)throw new Error("Project session sandbox not found");await Ur(t.projectId,t.sessionId)}async function aY(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function cY(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function da(e,t,n){let r=MP(e),o=await $(`${ue(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!o.ok){let s=await o.text().catch(()=>"");throw new Error(s||`Request failed (${o.status})`)}return await o.json()}async function gY(e,t){return da(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function mY(e,t,n,r="member"){await da(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function fY(e,t,n){await da(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var ga="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function _Y(e){throw F("getInvite",ga)}async function bY(e){throw F("acceptInvite",ga)}async function PY(e){throw F("declineInvite",ga)}async function xY(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function wY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function kY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function vY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function RY(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function CY(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var aI=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function MY(e){return aI.includes(e)}async function OY(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 DY(e){let t=e?`?channel=${e}`:"",r=await(await Oe(`${nt()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let o=await cI(e||"stable");r.changelog=o.find(s=>s.version===r.version)??o[0]??null}catch{r.changelog=null}return r}async function cI(e){let t=e?`?channel=${e}`:"";return(await(await Oe(`${nt()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function LY(){return(await Oe(`${nt()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function jY(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function $Y(e){}async function UY(e){}async function BY(e){return{serverTypes:[],location:e||"hel1"}}async function KY(e){throw new Error("Retired instance provisioning is unavailable. Create a project session on platinum (or the legacy daytona fallback).")}async function qY(e){throw F("deleteInstance")}async function GY(e,t){}async function WY(){throw F("claimComputer")}async function HY(e){return null}function VY(e,t){throw F("getSandboxProvisionStreamUrl")}var Go=class extends Error{constructor(n,r,o){super(n);this.status=r;this.body=o;this.name="HostBoundaryError"}status;body};function OP(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 DP(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function LP(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function X(e,t,n){let r=n?.body!==void 0,o=await fetch(`${Ne(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:OP(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),s=await DP(o);if(!o.ok)throw new Go(LP(o,s),o.status,s);return s}function lI(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 XY(e,t){return X(`/marketplace/items${lI(t)}`,e)}function ZY(e){return X("/marketplace/marketplaces",e)}function e2(e,t){return X(`/marketplace/items/${encodeURIComponent(e)}`,t)}function t2(e,t,n){return X(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function n2(e,t){return X("/access/check-email",t,{method:"POST",body:{email:e}})}function r2(e,t){return X("/access/request-access",t,{method:"POST",body:e})}function o2(e){return X("/auth/logout",e,{method:"POST",body:{}})}function s2(e,t){return X(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function i2(e,t){return X("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function a2(e,t){return X(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function c2(e,t){return X(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function l2(e,t,n={}){return X(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function u2(e,t){return X(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function p2(e,t,n,r){return X(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function d2(e,t){return X(`/p/public-share/${encodeURIComponent(e)}`,t)}function g2(e,t,n){return X(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function m2(e){return X("/system/maintenance",e)}function f2(e,t){return X("/system/maintenance",t,{method:"PUT",body:e})}function y2(e){return X("/user-roles",e)}function h2(e,t){return X("/system/demo-request",t,{method:"POST",body:e})}async function _2(e,t,n){let r=await fetch(`${Ne(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${$t(t)}`,{headers:OP(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let o=await DP(r);throw new Go(LP(r,o),r.status,o)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function b2(e,t){throw F("openStressTestStream")}function P2(e,t){throw F("buildPublicTemplateUrl")}async function S2(e,t,n){throw F("getPublicTemplate")}var uI="kortix:connect-link:";function ma(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let o=e.charCodeAt(r);t=Math.imul(t^o,16777619)>>>0,n=Math.imul(n^o,1540483477)>>>0}return`${uI}${t.toString(36)}${n.toString(36)}`}function w2(e,{storage:t}={}){let n=new Map,r=new Map,o=i=>{if(t)try{let a=t.getItem(ma(i));if(!a)return;let l=JSON.parse(a);if(Date.parse(l.expires_at)<=Date.now()){t.removeItem(ma(i));return}return l}catch{return}},s=(i,a)=>{if(t)try{t.setItem(ma(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let l=o(i);return l&&r.set(i,l),l},load(i){let a=n.get(i);if(a)return a;let l=e(i).then(p=>(r.set(i,p),s(i,p),p),p=>{throw n.delete(i),p});return n.set(i,l),l}}}var jP="Could not start the connect flow.";async function k2(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:jP}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:jP};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var pI=3e3,dI=5e3,gI=5*6e4;function v2(e,t){let n=e===0?pI:dI;return t+n>gI?null:n}function A2(e){let t=e.project_name?.trim();return{app:e.name?.trim()||e.app?.trim()||e.slug,project:t&&t!=="this project"?t:null}}async function T2(){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 I2(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 E2(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 M2(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 O2(){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 L2="1";var mI="kortix.query-cache";function UP(e){return!!e&&typeof e.then=="function"}function $P(e){return UP(e)?e:Promise.resolve()}function j2(e){if(e[0]!=="kx")return!1;let t=e[1];if(t==="accounts")return e.length===3&&typeof e[2]=="string"&&e[2]!=="anonymous";if(t==="projects")return e.length===3;if(t!=="project"||typeof e[2]!="string")return!1;let n=e[3];if(e.length===4)return n==="summary"||n==="detail";if(n!=="sessions")return!1;if(e.length===6)return e[4]==="list-paged";if(e.length===7&&e[4]==="list-paged"){let r=e[6];return typeof r=="object"&&r!==null&&!r.q}return e.length===7&&e[4]==="list-children"?e[6]==="":e.length===5&&e[4]!=="list"&&e[4]!=="list-paged"}function $2(e){let{storage:t,userId:n,shouldPersist:r,version:o="1",maxAgeMs:s=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:l=mI,now:p=()=>Date.now()}=e,d=`${l}:${n}`,g=null,m=!1,f=null,_=Promise.resolve(),y=()=>{try{return $P(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},k=(P,v)=>{if(!v)return 0;let T;try{T=JSON.parse(v)}catch{return y(),0}if(!T||T.v!==o||T.user!==n||!Array.isArray(T.queries)||p()-T.at>s)return y(),0;let L=0;for(let w of T.queries){if(!w||!Array.isArray(w.k)||w.d===void 0||typeof w.t!="number"||p()-w.t>s||!r(w.k))continue;let D=P.getQueryState(w.k);D&&D.data!==void 0&&D.dataUpdatedAt>=w.t||(P.setQueryData(w.k,w.d,{updatedAt:w.t}),P.invalidateQueries?.({queryKey:w.k,exact:!0,refetchType:"none"}),L+=1)}return L},R=P=>P.getQueryCache().getAll().filter(v=>v.state.data!==void 0&&r(v.queryKey)).map(v=>({k:v.queryKey,d:v.state.data,t:v.state.dataUpdatedAt})).sort((v,T)=>T.t-v.t),I=(P,v)=>{let T=[],L=0;for(let w of P){let D=JSON.stringify(w).length+1;L+D>v||(T.push(w),L+=D)}return T},b=async P=>{let v=I(R(P),i);for(;;){let T={v:o,user:n,at:p(),queries:v};try{await $P(t.setItem(d,JSON.stringify(T)));return}catch{if(v.length===0)return;v=v.slice(0,Math.floor(v.length/2))}}},M=()=>{f!==null&&(clearTimeout(f),f=null)},h=()=>{M();let P=g;return!P||!m||(m=!1,_=_.then(()=>b(P)).catch(()=>{})),_},x=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,h()},a))};return{storageKey:d,restore(P){let v;try{v=t.getItem(d)}catch{return 0}return UP(v)?v.then(T=>k(P,T)).catch(()=>0):k(P,v)},persist(P){g=P,m=!0;let v=P.getQueryCache().subscribe(T=>{T.type!=="updated"&&T.type!=="removed"&&T.type!=="added"||r(T.query.queryKey)&&x()});return()=>{v(),g===P&&(g=null,M())}},flush(){return h()},async clear(){M(),g=null,m=!1,await _,await y()}}}function U2(){let e;try{e=globalThis.localStorage}catch{e=void 0}if(!e)return null;let t=e;return{getItem:n=>{try{return t.getItem(n)}catch{return null}},setItem:(n,r)=>t.setItem(n,r),removeItem:n=>{try{t.removeItem(n)}catch{}}}}var fI="/kortix/part/";function yI(e){return typeof e=="string"&&e.startsWith(fI)}async function K2(e){if(!yI(e))throw new Error(`not an attachment part reference: ${e}`);let t=Ge();if(!t)throw new Error("runtime url not bound");let n=await $(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function FP(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 hI(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let s=new Set;if(t)try{s.add(new URL(t).origin)}catch{}return typeof window<"u"&&s.add(window.location.origin),s.has(n.origin)}catch{return!1}}function NP(e,t){return hI(e,t)?(t?FP(t):null)??FP(e):null}function Wo(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 G2(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var _I=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function bI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function PI(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let o=(t.slice(n+3).split("/")[0]??"").toLowerCase(),s=`${r}://${o}`.split("{port}").map(i=>i.split("{sandbox}").map(bI).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${s}$`).test(e)}function SI(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function BP(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function xI(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:_I.test(n.hostname)?t.backendUrls.some(r=>{let o=SI(r);return o!==null&&BP(o)===BP(n)}):t.templates.some(r=>PI(n.origin,r))}async function KP(e,t={}){if(!Wo(e))return!1;let n=C().backendUrl;n&&await ft(n).catch(()=>null);let r=[n,t.serverUrl].filter(o=>typeof o=="string"&&o.length>0);return xI(e,{templates:Jy(),backendUrls:r})}async function wI(e,t={}){let n=NP(e,t.serverUrl||C().backendUrl||void 0);if(!n)return!1;let r=await on();if(!r)return!1;try{return(await fetch(n,{method:"POST",credentials:"include",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).ok}catch{return!1}}async function tJ(e,t={}){if(Wo(e)){if(!await KP(e,t)||!await on())return e;let r=await c.post("/p/ticket",{preview_url:e}),o=r.data;if(!r.success||!o||typeof o.ticket!="string"||!o.ticket)throw new Error("Preview authorization failed");let s=new URL(e);return s.searchParams.delete("token"),s.searchParams.set("preview_ticket",o.ticket),s.toString()}return await wI(e,t),e}var rJ=3e3;function kI(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 oJ(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let o=setTimeout(r,t?.timeoutMs??3e3);try{let s=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return kI(s.status)}catch{return"unknown"}finally{clearTimeout(o),t?.signal?.removeEventListener("abort",r)}}function vI(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function aJ(e,t){throw F("buildPresentationTemplatePdfUrl")}function cJ(e,t){throw F("buildPresentationTemplateImageUrl")}function AI(e,t){return`${vI(e)}/presentation/convert-to-${t}`}async function lJ(e,t,n,r){let o=AI(t,e),s=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),l=!1;for(;;){let p=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let _=await p.blob();if(_.size===0)throw new Error("Downloaded file is empty");return _}if(p.status===202){if(l||(l=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((_,y)=>{let k=setTimeout(_,s);r?.signal?.addEventListener("abort",()=>{clearTimeout(k),y(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let _=JSON.parse(m);f=String(_.error||_.detail||_.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function dJ(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 gJ(e){return e==="unreachable"}function mJ(e){return!e||e.status===0?"unknown":e.ok&&n_(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var RI=1e4,fJ={connection:"unknown",faultSinceMs:null};function yJ(e,t,n,r=RI){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let o=e.faultSinceMs??n;return n-o>=r?{connection:t,faultSinceMs:o}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:o}}function qP({optimistic:e,abort:t,inbox:n,server:r,stream:o,activity:s,nowMs:i}){let a=!!e&&i-e.atMs<fa,l=!!t&&i-t.atMs<_a;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:l,abortFloor:l?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=ya,streamFresh:!!o&&i-o.atMs<=Zn,inboxFresh:!!n&&i-n.atMs<=ha,activityFresh:!!s&&i-s.atMs<=Zn}}function Jt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function ba(e,t,n){if(!t)return!1;let r=Jt(e.started_at);if(r===null||r>=t.atMs)return!1;let o=n?.lastEnded,s=Jt(o?.ended_at);return!(o&&s!==null&&Math.abs(s-t.atMs)<=1e3&&o.turn_token!==e.turn_token)}function CI(e,t,n,r){let{activity:o,server:s}=e,{serverFresh:i,abortFloor:a,activityFresh:l}=t;return l&&(!n||o.atMs>n.atMs)&&o.atMs>=a?{state:"working",source:"stream",turnId:i?s.turns.find(d=>d.state==="active"&&!ba(d,n,s))?.message_id??null:null,since:o.atMs,serverOpenTurnToken:r}:null}function TI(e,t,n,r){let{server:o,stream:s}=e,{serverFresh:i,abortFloor:a}=t,l=i?o.turns.filter(g=>!ba(g,n,o)):[],p=l.find(g=>g.state==="active")??l[0],d=!!s&&!(s.type==="idle"&&s.origin==="local");return p&&o.atMs>=a&&(!d||o.atMs>=s.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:Jt(p.started_at)??o.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function II(e,t,n){let{inbox:r,server:o,stream:s}=e,{inboxFresh:i,abortFloor:a,streamFresh:l,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...l&&s.type!=="idle"&&(!p||s.atMs>o.atMs)&&s.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&o.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function EI(e,t,n,r){let{server:o,stream:s,optimistic:i,nowMs:a}=e,{serverFresh:l,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:_}=t,y=l&&!n&&o.atMs>=p,k=d&&s.atMs>=g&&(s.type==="idle"||s.atMs>=m);if(y&&(!s||o.atMs>=s.atMs))return{state:"idle",source:"server",turnId:null,since:Jt(o.lastEnded?.ended_at)??o.atMs,serverOpenTurnToken:r};if(k)return{state:s.type==="idle"?"idle":"working",source:"stream",turnId:null,since:s.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:_,since:i.atMs,serverOpenTurnToken:r};let R=o&&s?o.atMs>=s.atMs?{source:"server",atMs:o.atMs}:{source:"stream",atMs:s.atMs}:o?{source:"server",atMs:o.atMs}:s?{source:"stream",atMs:s.atMs}:{source:"server",atMs:a};return{state:"idle",source:R.source,turnId:null,since:R.atMs,serverOpenTurnToken:r}}function GP(e){let t=qP(e),{server:n,stream:r}=e,o=r&&r.type==="idle"&&r.origin!=="local"?r:null,s=n?.turns[0]?.turn_token??null,i=CI(e,t,o,s);if(i)return i;let{result:a,openTurn:l}=TI(e,t,o,s);return a??II(e,t,s)??EI(e,t,l,s)}var fa=6e4,ya=45e3,Zn=45e3,ha=1e4,RJ=3e3,_a=15e3;function CJ(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function TJ(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 EJ(e){return GP(e)}function MJ(e){let{optimistic:t,abort:n,inbox:r,server:o,stream:s,activity:i,nowMs:a}=e,l=[null,t?t.atMs+fa:null,n?n.atMs+_a:null,r?r.atMs+ha:null,o?o.atMs+ya:null,s?s.atMs+Zn:null,i?i.atMs+Zn:null],p=null;for(let d of l)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function MI(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(s=>s.message_id===t),r=e.last_ended,o=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!o?.message||Bo({name:o.name??void 0,message:o.message})?null:o}var OI="SandboxMemoryGuard";function jJ(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=MI(e,t);if(r?.message){if(r.name!==OI)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],l=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:l}}let o=e.recent_failures?.find(a=>a.message_id===t);if(!o)return null;let s=o.ended_at?Date.parse(o.ended_at):Number.NaN;return Number.isFinite(s)&&typeof e.atMs=="number"&&e.atMs-s<2500?null:{kind:"unexplained"}}var UJ=6e4;function FJ(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function NJ(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var DI=9e4;function BJ(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+DI}var qJ=75e3,GJ=2,WJ=2e4;function WP(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function HJ(e){return e.filter(t=>t!=null).join("|")}function LI(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function VJ(e,t,n={}){let r=n.noProgressMs??75e3,o=n.maxRestarts??2,s=n.cooldownMs??2e4;if(t.runtimeReachable)return{...WP(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...WP(),settled:!0};let i=e.lastProgressAtMs,a=i===null,l=t.progress!==e.fingerprint,p=i===null||l?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!l&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<s)return g;let f=LI(e.attempts,o);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var jI={"retry-start":"retrying",restart:"restarting"};function zJ(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${jI[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function $I(e){return e===1?"once":e===2?"twice":`${e} times`}function YJ(e){if(e.status!=="exhausted")return null;let t=e.attempts.filter(o=>o.step==="restart").length,n=e.attempts.some(o=>o.step==="retry-start");if(!n&&t===0)return null;let r=[];return n&&r.push("re-issuing the wake"),t>0&&r.push(`restarting the session ${$I(t)}`),`Tried: ${r.join(", then ")}.`}var QJ={"needs-you":{label:"Needs you",tone:"actionable",description:"Waiting for your review"},starting:{label:"Starting",tone:"progress",description:"Its computer is starting"},running:{label:"Running",tone:"live",description:"Its computer is up"},done:{label:"Done",tone:"muted",description:"Finished"},stopped:{label:"Stopped",tone:"muted",description:"Asleep. Opening it wakes its computer"},failed:{label:"Failed",tone:"danger",description:"Its computer didn't start"},legacy:{label:"Legacy",tone:"muted",description:"Imported. Open it to restore"}};function UI(e){return!!(e.metadata??{}).legacy_migration}function XJ(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return e.working?.state==="idle"?"done":"running";case"completed":case"stopped":return UI(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function ZJ(e){switch(e){case"waking":return{label:"Waking computer",tone:"progress"};case"connecting":return{label:"Connecting",tone:"progress"};case"unreachable":return{label:"Can't reach computer",tone:"danger"};default:return null}}var e4={unreachable:"Lost contact with this session's computer. Messages you send are queued until it reconnects.",unreachableMidTurn:"Lost contact with this session's computer while a turn is still open. Messages you send stay queued until it answers.",stalled:"Waking this session's computer is taking longer than usual. Messages you send are queued.",starting:"Starting this session's computer. Your message sends automatically.",idle:"This session's computer is asleep. Your next message wakes it up and is delivered.",waking:"Waking this session's computer. Messages you send are queued and go out automatically."};function t4(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function Pa(e){return e.runtime_sessions??e.opencode_sessions??[]}function FI(e){let t=Pa(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function r4(e){let t=FI(e);return t?Pa(e).filter(n=>(n.parent_id===t.id||!n.parent_id&&n.fork_source_id)&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function o4(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>Pa(r).some(o=>o.id===t))??null)}var NI=new Set;function BI(e){for(let t of[...NI])try{t(e)}catch{}}var JP={schema:le,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var QP=e=>Object.values(e.ext??{}).find(t=>t.version===Te),XP=e=>!!e&&QP(e)!==void 0,ZP=e=>{let t=QP(e);return t?t.native_id??null:e.thread_id};function eS(e){let t=e&&Object.values(e.threads).find(r=>r.parent_thread_id===null);if(!e||!t)return null;let n=(e.messages[t.thread_id]?.length??0)>0;return{runtimeSessionId:ZP(t),hasMessages:n,empty:!n&&e.older[t.thread_id]===!1}}var HP=new WeakMap;function tS(e,t){let n=ZP(e),r=HP.get(t);if(r&&r.native===n)return r.rows;let{rows:o}=so({...JP,threads:[{...e,messages:[t]}]}),s=o.map(i=>({info:i.info,parts:i.parts}));return HP.set(t,{native:n,rows:s}),s}var Sa=e=>e.info.time?.created;var KI=(e,t)=>(Sa(e)??-1/0)-(Sa(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var VP=new WeakMap,zP=new WeakMap,nS=e=>typeof e=="object"&&e!==null,qI=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,GI=e=>e.info.role==="user"&&e.parts.some(t=>nS(t)&&t.type==="compaction"),WI=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},YP=new WeakMap;function HI(e,t,n){let r=t.info,o=`${e}|${String(r.id)}|${String(r.time?.created)}`,s=!1,i=n.blocks.map((a,l)=>{let p=t.parts[l];if(!nS(p)||a.type==="compaction")return a;let d=`${o}|${l}|${a.id}`,g=YP.get(p);return g&&g.key===d?(s=!0,g.block):(YP.set(p,{key:d,block:a}),a)});return s?{...n,blocks:i}:n}function VI(e){let t=new Map,n=new Set;for(let r of e){if(!GI(r))continue;let o=e.find(s=>!n.has(s)&&WI(s,r));o&&(t.set(r,o),n.add(o))}return{paired:t,used:n}}function zI(e,t,n,r,o){let s=VP.get(n);if(s&&s.sessionId===e&&s.native===t&&s.sum===r&&s.seq===o)return s;let a=io({session_id:e,root_id:t,rows:(r?[n,r]:[n]).map(d=>({runtime_session_id:t,info:d.info,parts:d.parts}))},{live:!0}),l=HI(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:o,message:{...l,seq:o},lost:a.grade_counts};return VP.set(n,p),p}function YI(e,t,n){let r=zP.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let o=[...n].sort(KI),{paired:s,used:i}=VI(o),a={tool_input:0,cut_point:0,attachment:0},l=[];for(let m of o){if(i.has(m))continue;let f=zI(e,t,m,s.get(m),l.length+1);for(let _ of["tool_input","cut_point","attachment"])a[_]+=f.lost[_];l.push(f.message)}let p=qI(o.map(Sa).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=l.filter(m=>m.role==="user"&&m.kind==="turn"),g={...JP,session_id:e,created_at:p,restore_grade:a.tool_input+a.cut_point+a.attachment>0?"partial":"converted",grade_counts:a,harness:{current:"opencode",history:[]},selection:{agent:d.at(-1)?.agent??null,model:d.at(-1)?.model??null},threads:[{schema:le,v:1,thread_id:t,parent_thread_id:null,spawned_by:null,agent:d[0]?.agent??null,title:null,created_at:l[0]?.created_at||p,messages:l,ext:{opencode:{version:Te,native_id:t}}}]};return zP.set(n,{sessionId:e,native:t,log:g}),g}var xa=new WeakMap,Qt=new WeakMap,rS=new WeakMap;function Ho(e){let t,n=Qt.get(e);return n&&(t=JI(n).get(e.id)),t?(xa.set(t,e),t):(e.type!=="harness"?t=Zs(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=rS.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},rS.set(e,t)),t&&xa.set(t,e),t)}var er=e=>xa.get(e),xt=e=>e.flatMap(t=>Ho(t)??[]),oS=new WeakMap;function JI(e){let t=oS.get(e);return t||oS.set(e,t=new Map(at(e)[0]?.parts.map(n=>[n.id,n]))),t}var sS=new Map;function at(e){let t=sS.get(e.thread_id);return t||(t={schema:le,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},sS.set(e.thread_id,t)),tS(t,e)}var QI="kortix-v1-import",wa={schema:le,v:1};function Vo(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var ka=e=>e.type==="tool_call",XI=e=>e.status==="pending"||e.status==="running",va=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function ZI(e,t){let n=va(e);return!XI(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var iS=new WeakMap;function eE(e,t){let n=iS.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),o={...wa,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"kortix-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return iS.set(e,o),o}var aS=new WeakMap;function tE(e){let t=aS.get(e);return t||(t={...wa,message_id:e.reply_to,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},aS.set(e,t)),t}var cS=new WeakMap;function nE(e){let t=cS.get(e);return t||(t={...wa,message_id:`${e.message_id}:continued`,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},cS.set(e,t)),t}var rE=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function oE(e,t){let n=[],r=new Map;for(let g of e){if(g.role!=="user"||g.kind==="context"||r.has(g.message_id))continue;let m={user:g,assistant:[],partial:!1};r.set(g.message_id,m),n.push(m)}let o=[],s=[],i=new Map,a=new Map,l=null,p=null;for(let g of e){if(g.role==="user"){let y=r.get(g.message_id);y&&!t.has(g.message_id)&&(l=y,i.has(y)||i.set(y,i.size),y.user.kind==="compaction"&&(p=y));continue}if(g.role!=="assistant"||rE(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??l;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let y=a.get(p);y||(y={user:nE(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,y)),f=y}if(f){f.assistant.push(g);continue}if(!g.reply_to){s.push(g);continue}let _=o[o.length-1];_&&_.user.message_id===g.reply_to?_.assistant.push(g):o.push({user:tE(g),assistant:[g],partial:!0})}if(s.length){let g=n[0]??o[0];g?g.assistant.unshift(...s):n.push({user:s[0],assistant:s.slice(1),partial:!1})}let d=n.filter(g=>!t.has(g.user.message_id)).flatMap(g=>{let m=a.get(g);return m?[g,m]:[g]});return[...o,...d,...[...t].flatMap(g=>r.get(g)??[])]}function sE(e,t){if(!t)return t;let n=t;for(let r of e){let o=r.continues;o&&(n===o.marker||n===o.prompt||t===o.prompt)&&(n=r.user.message_id)}return n}function pS(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=at(n)[0]?.info?.error??n.error.message,o=xe(r),s=Ro(r);return{code:n.error.code,message:o?.message||he(r),...o&&{details:o},...s!==void 0&&{raw:s}}}function iE(e,t,n){return e.length&&e.every(t)?ca(e.flatMap(r=>at(r).flatMap(o=>o.parts.map(s=>({part:s,message:o})))),n)??null:Aa(e,n)}function Aa(e,t){let n=e.flatMap(r=>{let o=r.usage;if(!o)return[];let s={type:"step-finish",cost:o.cost??0,tokens:{input:o.input,output:o.output,reasoning:o.reasoning??0,cache:{read:o.cache_read,write:o.cache_write}}};return[{part:s,message:{info:{id:r.message_id,role:"assistant",providerID:r.model?.provider,modelID:r.model?.model},parts:[s]}}]});return ca(n,t)??null}function aE(e){if(e.kind!=="compaction")return null;let t=e.blocks.find(n=>n.type==="compaction")??null;return{block:t,hasContent:!!t?.summary?.trim(),inFlight:e.status==="streaming"}}function cE(e){let t=e.user.blocks;if(!t.length||!t.every(r=>r.type==="text"&&r.synthetic))return null;let n=e.assistant.length===1&&e.assistant[0].blocks.length===1?e.assistant[0].blocks[0]:null;return n&&ka(n)&&n.name==="bash"?n:null}function lE(e,t,n,r){if(!n.length)return[];let o=new Set(e.assistant.map(i=>i.message_id)),s=new Set;for(let i of n)i.spawned_by&&o.has(i.spawned_by.message_id)&&s.add(i.thread_id);for(let i of t){let a=i.type==="subtask"?i.thread_id:ka(i)?Eo(i):void 0;a&&r.has(a)&&s.add(a)}return[...s]}var uE=e=>e.assistant.some(t=>t.blocks.some(n=>ka(n)&&ce(n.name)==="todowrite"&&Kn(n))),pE=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function dE(e,t){let n=e.map(o=>pS(o)!==null),r=e.map((o,s)=>n[s]===!0&&t[s+1]===!0);return e.map((o,s)=>{if(r[s])return{continued:!0,retries:0};if(!n[s])return;let i=0;for(let a=s-1;a>=0&&r[a];a--)i+=1;return i>0?{continued:!1,retries:i}:void 0})}var lS=new WeakMap,gE=[];function dS(e){let t=Vo(e.messages,n=>n.role==="assistant");return!!t&&Bb(at(t))}var uS=new WeakMap;function mE(e){let t=uS.get(e);if(!t){let n=e.messages.filter(r=>r.in_context||r.status==="streaming");t=n.length===e.messages.length?e:{...e,messages:n},uS.set(e,t)}return t}function Ra(e,t={}){let n=t.hideOutOfContext?mE(e):e,r=new Set(t.held??gE),o=oE(n.messages,r),s=Vo(n.messages,y=>y.role==="assistant"),i=dS(n),a=dP({turns:o.map(y=>({userMessage:{info:{id:y.user.message_id}},assistantMessages:y.assistant.map(k=>({info:{time:k.status==="streaming"?{}:{completed:1},error:k.error??void 0}}))})),hintMessageId:sE(o,t.liveMessageId),unrunTurnIds:r}),l=Vo(o,uE)??o[o.length-1],p=o.map(y=>!y.partial&&pE(y.user)),d=dE(o,p),g=XP(n),m=y=>g||y.producer.harness===QI,f=t.threads??[],_=new Set(f.map(y=>y.thread_id));return o.map((y,k)=>{let R=t.busy===!0&&a.workingTurnId===y.user.message_id,I=a.pendingTurnIds.includes(y.user.message_id),b=i&&y.assistant.includes(s),M=d[k],h=`${y.partial}|${R}|${I}|${y===l}|${b}|${M?(M.continued?"c":"")+M.retries:"-"}`,x=lS.get(y.user);if(x&&x.key===h&&x.pricing===t.pricing&&x.heads===t.threads&&x.assistant.length===y.assistant.length&&x.assistant.every((w,D)=>w===y.assistant[D]))return x.turn;let P=y.assistant.flatMap(w=>w.blocks);for(let w of y.assistant)for(let D of w.blocks)Qt.set(D,w);let v=lE(y,P,f,_),T=y.assistant[y.assistant.length-1],L={internal:p[k],autoRetry:M,id:y.user.message_id,user:y.user,assistant:y.assistant,partial:y.partial,continues:y.continues??null,blocks:P,status:b?"streaming":T?T.status:y.user.kind==="compaction"?y.user.status:"pending",error:pS(y),cost:iE([y.user,...y.assistant],m,t.pricing),compaction:aE(y.user),threads:v,plan:y===l,shell:cE(y),response:Vo(P,w=>w.type==="text"&&!!w.text.trim())??null,attachments:y.user.blocks.filter(w=>w.type==="attachment"&&(w.mime.startsWith("image/")||w.mime==="application/pdf")),live:R,queued:I,retrying:b};return lS.set(y.user,{assistant:y.assistant,key:h,pricing:t.pricing,heads:t.threads,turn:L}),L})}var Ca=e=>er(e);function fE(e,t={}){return cP(iP(xt(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(er)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Ca)}:n.kind==="text"?{kind:n.kind,block:er(n.part)}:{kind:n.kind,block:Ca(n.part)})}var yE=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:xt(e.blocks)}:{kind:e.kind,part:Ho(e.block)};function hE(e,t){let n=new Map(e.map(s=>[yE(s),s])),r=xP([...n.keys()],t);if(!r)return null;let o=s=>s.map(i=>n.get(i));return{work:o(r.work),hoisted:o(r.hoisted),final:o(r.final)}}function _E(e){if(!te(e)||!jy(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=Db(e);return(n.answers??vP(n.outputText??"",t.length)??[]).length>0}function bE(e){return eP(xt(e),n=>Vn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(_E)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:er(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Ca),family:n.step.family,label:n.step.label,status:n.step.status,durationMs:n.step.durationMs};let r=e.find(s=>s.id===n.key.slice(8)),o=r&&Qt.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!o||o.status==="streaming"),durationMs:n.durationMs}})}function PE(e,t){return mP(xt(e.blocks).map(n=>({part:n})),t?.flatMap(at))}function SE(e){return sa(xt(e))}function xE(e){return Qb(xt(e))}function wE(e,t){return t.working?t.trailing?!0:e.some(n=>{if(n.type==="tool_call")return n.status==="pending"||n.status==="running";if(n.type!=="reasoning")return!1;let r=Ho(n),o=Qt.get(n);return!!r&&we(r)&&ia(r)&&(!o||o.status==="streaming")}):!1}var gS=new WeakMap;function kE(e){if(!va(e))return e;let t=gS.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},gS.set(e,t)}return t}function vE(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function AE(e){let t=e.map(oe),n=t[0],r=t.some(s=>s.state.status==="running"||s.state.status==="pending"),o=lP(t).map(vE);return ao({...n,state:{...n.state,status:r?"running":"completed",input:{items:o}}})}function RE(e,t,n){let r=oe(e),o=r.state;return ao({...r,state:{...o,status:"completed",...n!==void 0&&{input:n},metadata:{...o.metadata??{},answers:t}}})}function CE(e){let t=at(e).map(r=>Yi(r)),n=t.find(r=>r.error)?.error;return{parts:t.flatMap(r=>r.parts),error:n,isEmpty:t.every(r=>r.isEmpty)&&!n}}var mS=Object.freeze([]),fS=new WeakMap;function TE(e){if(!e)return mS;let t=fS.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(o=>o.type==="tool_call"&&Kn(o)):[]);t=n.length?n:mS,fS.set(e,t)}return t}function IE(e,t={}){let n={cost:0,messages:{all:0,user:0,assistant:0},tokens:{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},context:null};for(let r of Ra(e)){let o=Aa([r.user,...r.assistant],t.pricing);if(o){n.cost+=o.cost;for(let s of Object.keys(n.tokens))n.tokens[s]+=o.tokens[s]}}for(let r of e.messages){r.role==="user"?n.messages.user++:r.role==="assistant"&&n.messages.assistant++,r.kind==="compaction"&&r.status!=="streaming"&&n.messages.assistant++;let o=r.usage;(r.role==="assistant"||r.kind==="compaction")&&o&&o.input+o.output+(o.reasoning??0)+o.cache_read+o.cache_write>0&&(n.context=r)}return n.messages.all=n.messages.user+n.messages.assistant,n}var EE="prt_kortix_restore_g";function ME(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(EE))}function OE(e,t){let n=new Map,r=[...e??[]].sort((o,s)=>o.from_seq-s.from_seq);for(let o=1;o<r.length;o++){let s=r[o],i=r[o-1].harness;if(s.harness===i)continue;let a=t.findIndex(l=>l.user.seq>=s.from_seq);a<0||a===0&&t[0].user.seq!==s.from_seq||n.set(t[a].id,{harness:s.harness,previous:i,version:s.version,at:s.at})}return n}var Ta=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qe=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,DE=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function LE(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=Ta(t)?t.restore:void 0;if(!Ta(n))return null;let r=Ta(n.dropped)?n.dropped:{},o=e.grade_counts,s=[{kind:"message",count:Qe(r.message)},{kind:"attachment",count:Qe(o?.attachment)},{kind:"text",count:Qe(r.text)+Qe(n.truncated)},{kind:"tool_input",count:Qe(o?.tool_input)},{kind:"tool_result",count:Qe(r.tool_result)},{kind:"cut_point",count:Qe(o?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,l])=>DE.has(a)?i:i+Qe(l),0)}];return{generation:Qe(n.generation),missing:s.filter(i=>i.count>0)}}var hS=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function jE(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let o of hS(r))o.ref&&o.bytes!==void 0&&!t.has(o.ref)&&t.set(o.ref,o.bytes);return[...t].map(([n,r])=>({ref:n,bytes:r}))}var _S=(e,t)=>{let n=e.ref===void 0?void 0:t.get(e.ref);if(n===void 0)return e;let{ref:r,bytes:o,...s}=e;return{...s,text:n}},$E=(e,t)=>e.map(n=>n.type==="text"?_S(n,t):n),yS=new WeakMap;function UE(e,t){let n=yS.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(o=>hS(o).some(s=>s.ref!==void 0&&t.has(s.ref)))?{...e,blocks:e.blocks.map(o=>o.type==="text"?_S(o,t):o.type==="tool_call"&&o.result?{...o,result:{...o.result,content:$E(o.result.content,t)}}:o)}:e;return yS.set(e,{texts:t,out:r}),r}var Ia=1024*1024;function FE(e){return e.reduce((t,n)=>t+n.bytes,0)>Ia?"download":"inline"}function NE(e){let t=new Set,n=0;for(let r of[...e].sort((o,s)=>o.bytes-s.bytes)){if(n+r.bytes>Ia)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function BE(e,t){if(t.size===0)return e;let n=e.messages.map(r=>UE(r,t));return n.every((r,o)=>r===e.messages[o])?e:{...e,messages:n}}function KE(e){return e==="TIMEOUT"||e==="request_deadline"}function qE(e){let t=PS(e)?e.code:void 0;return typeof t=="string"?t:void 0}var PS=e=>typeof e=="object"&&e!==null;function bS(e){let t=e?.metadata;return!!PS(t)&&t.warm===!0}var GE=5,WE=2e3,HE=e=>new Promise(t=>setTimeout(t,e));async function VE(e,{attempts:t=GE,delayMs:n=WE,sleep:r=HE}={}){for(let o=0;o<t;o++){o>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function fQ(e,t){let n=new Map,r=new Set,o=new Set,s=new Set,i=0,a=(l,p,d)=>{if(r.has(l)||n.has(l))return Promise.resolve();r.add(l);let g=i,m=(async()=>{let f=null;try{let _=await e.ensure(l,p);if(g!==i)return;o.has(_.sessionId)?f=_.sessionId:n.set(l,_)}catch{}finally{g===i&&r.delete(l)}f&&d>0&&await a(l,f,d-1)})();return s.add(m),m.finally(()=>s.delete(m)),m};return{ensure:(l,p)=>a(l,p?.excludeSessionId,1),take:(l,p,{replenish:d})=>{let g=n.get(l);return g?(n.delete(l),o.add(g.sessionId),d&&a(l,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(l,p,d)=>{try{return await e.claim(l,d),!0}catch(g){return KE(qE(g))?VE(async()=>!bS(await e.read(l,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:l=>{for(let[p,d]of n)if(d.sessionId===l)return n.delete(p),o.add(l),p;return null},revalidate:async l=>{let p=n.get(l);if(!p)return!1;try{if(bS(await e.read(l,p.sessionId)))return!1}catch{return!1}return n.get(l)?.sessionId!==p.sessionId?!1:(n.delete(l),o.add(p.sessionId),!0)},held:l=>n.get(l)??null,reset:()=>{i+=1,n.clear(),r.clear(),o.clear()},settled:async()=>{for(;s.size>0;)await Promise.all([...s])}}}var zE=12e4,zo=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},YE=1e3,JE=15e3,SS=100,QE=50,XE=10;function xS(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:o},s)=>{let i=new URLSearchParams({limit:String(r)});o&&i.set("before",o);let a=await e.getToken?.(),l=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...s?{signal:s}:{}});if(!l.ok)throw l.status===503?new qo(`session ${l.status}`):new S(`Session synchronization failed: ${l.status}`,{status:l.status});return{messages:await l.json(),nextCursor:l.headers.get("x-next-cursor")||void 0}}}function ZE(e){return tM(xS(e))}function eM(e){return new Ea({...e,loadPage:xS(e)})}async function tM(e){let t=[],n=new Set,r;do{let i=await e({limit:SS,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let o=[],s=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])s.has(a.info.id)||(s.add(a.info.id),o.push(a));return o}var nM={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Ea=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??nM,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??zE,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed||t==="visible"&&this.streamReliable&&this.snapshot.freshness==="fresh"?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":this.snapshot.freshness}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof zo;if(!r&&Bo(n))return;if(r||this.update({freshness:Xn(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(YE*2**this.retryAttempt,JE);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let o=this.scheduler.now();try{let s=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?QE:SS,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:s.messages.length,succeeded:!0}),s}catch(s){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-o,messageCount:0,succeeded:!1}),s}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,o=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",o,{once:!0});let s,i=new Promise((l,p)=>{s=this.startTimer(()=>{let d=new zo(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(l){a=Promise.reject(l)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(s),n.removeEventListener("abort",o)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,o,s){let i=[...t.messages],a=new Set(this.knownUserMessageIds),l=new Set(o?[o]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<XE&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(l.has(p))throw new Error(`Session history cursor repeated: ${p}`);l.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw s?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,s?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let o,s=!1,i=()=>{s||(s=!0,this.cancelTimer(o),r())};o=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};var rM=5e3,kS=40,SQ=5*6e4,oM=16,tr=new Map;function vS(e,t,n,r=Date.now()){let o=AS(e,t);for(tr.delete(o),tr.set(o,{envelope:n,atMs:r});tr.size>oM;){let s=tr.keys().next().value;if(s===void 0)break;tr.delete(s)}}var wS=new Map;function AS(e,t){return`${e}/${t}`}function sM(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=rM}function RS(e,t,n=Date.now()){if(!e||!t)return null;let r=AS(e,t),o=wS.get(r);return o?sM(o,n)?o.promise:(wS.delete(r),null):null}function CS(e){let t=e.transcript;if(!t||t.known!==!0||t.requested!==!0)return null;let{known:n,requested:r,...o}=t;if(!o.available)return o;let s=e.session?.runtime_session_id??e.session?.opencode_session_id,i=o.runtime_session_id??o.opencode_session_id;return s&&i===s?o:null}var TS=Object.freeze({generation:0,session:{},threads:{},messages:{},revs:{},older:{}});function iM(e,t){let n=(e[t.thread_id]??[]).filter(o=>o.message_id!==t.message_id),r=n.length;for(;r>0&&n[r-1].seq>t.seq;)r--;return n.splice(r,0,t),{...e,[t.thread_id]:n}}function IS(e,t,n){let r=e.messages,o=e.older,s=t.thread_id,i=s===null?void 0:r[s];if(s!==null){let p=t.messages[0]?.seq;(n!==void 0||!i?.length||!t.has_more||p!==void 0&&p<=i[0].seq)&&e.older[s]!==t.has_more&&(o={...o,[s]:t.has_more})}if(s!==null&&i){let p=t.has_more?t.messages[0]?.seq??1/0:-1/0,d=n??1/0,g=new Set(t.messages.map(f=>f.message_id)),m=i.filter(f=>f.seq<p||f.seq>=d||g.has(f.message_id)||e.revs[f.message_id]!==void 0);m.length!==i.length&&(r={...r,[s]:m})}for(let p of t.messages)!Rs(p)||e.revs[p.message_id]!==void 0||(r=iM(r,p));let a={...e.threads};for(let p of t.threads)Cs(p)&&(a[p.thread_id]=p);let l=t.generation>e.generation;return{...e,generation:Math.max(t.generation,e.generation),session:l?{...e.session,...t.session}:{...t.session,...e.session},threads:a,messages:r,older:o}}var aM=2e3;async function cM(e,t,n){let r=RS(e,t),o,s=r?await Promise.race([r,new Promise(i=>{o=setTimeout(i,n.snapshotWaitMs??aM,null)})]).finally(()=>clearTimeout(o)):null;return(s&&CS(s))??Dr(e,t,{limit:kS,history:!0,signal:n.signal})}async function lM(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};if(e.sessionLog){let s=pn?await Ip(pn,t,n):null,i=s&&eS(IS(TS,s));return{envelope:null,empty:!!i?.empty&&i.runtimeSessionId===r&&await ES(t,n,r),log:s}}let o;try{o=await cM(t,n,{})}catch{return{envelope:null,empty:!1}}return vS(t,n,o),MS(o)!==r?{envelope:o,empty:!1}:{envelope:o,empty:await ES(t,n,r)}}async function ES(e,t,n){try{let r=await Lr(e,t);return OS({savedEmptyRoot:n,rootSessionId:n,turnRead:!0,hasEndedTurn:r.last_ended!=null,hasOpenOrQueuedTurn:r.turns.length>0})}catch{return!1}}function MS(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function OS(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function OQ(e){throw F("buildTunnelEventStreamUrl")}function DQ(e){let{url:t,token:n,method:r="GET",body:o,onEvent:s,onOpen:i,onError:a,onClose:l,signal:p}=e,d=new Map,g=null,m=!1,f="";function _(b,M){s?.(b,M);let h=d.get(b);if(h)for(let x of h)try{x(M)}catch{}}async function y(){if(m)return;let b=new AbortController;g=b,p&&(p.aborted?b.abort():p.addEventListener("abort",()=>b.abort(),{once:!0}));let M=b.signal;try{let h={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&o!==void 0&&(h["Content-Type"]="application/json"),f&&(h["Last-Event-ID"]=f);let x=await fetch(t,{method:r,headers:h,body:r!=="GET"&&o!==void 0?JSON.stringify(o):void 0,signal:M,credentials:"include"});if(!x.ok)throw new Error(`SSE connection failed: ${x.status} ${x.statusText}`);if(!x.body)throw new Error("SSE response has no body");i?.();let P=x.body.getReader(),v=new TextDecoder,T="",L="message",w=[],D=N=>{if(N===""){w.length>0&&_(L,w.join(`
|
|
98
|
-
`)),L="message",w=[];return}if(N.startsWith(":"))return;let z=N.indexOf(":"),G=z===-1?N:N.slice(0,z),K=z===-1?"":N.slice(z+1);K.startsWith(" ")&&(K=K.slice(1)),G==="event"?L=K.trim()||"message":G==="data"?w.push(K):G==="id"&&!K.includes("\0")&&(f=K)},be=N=>{let z="";!N&&T.endsWith("\r")&&(z="\r",T=T.slice(0,-1));let G=T.split(/\r\n|\n|\r/);T=(G.pop()??"")+z;for(let K of G)D(K)};for(;!m;){let{done:N,value:z}=await P.read();if(N)break;T+=v.decode(z,{stream:!0}),be(!1)}m||(T+=v.decode(),be(!0),l?.())}catch(h){if(m||h instanceof DOMException&&h.name==="AbortError")return;a?.(h instanceof Error?h:new Error(String(h)))}}function k(){m=!0,g?.abort(),g=null,d.clear()}function R(b,M){let h=d.get(b)??new Set;h.add(M),d.set(b,h)}function I(b,M){d.get(b)?.delete(M)}return{connect:y,close:k,addEventListener:R,removeEventListener:I}}function LQ(e,t){throw F("createTunnelEventStream")}var DS="/_kortix/viewer",Yo=6e4,Xt=new Map;function uM(){Xt.clear(),nr.clear()}async function pM(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 LS(e={}){let t=e.path??DS,n=e.fetch??((s,i)=>fetch(s,i)),r=Xt.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let o=pM(t,n).then(s=>{let i=s?.expires_at?Date.parse(s.expires_at):Number.NaN,a=Number.isFinite(i)?i-Yo:Date.now()+Yo;return Xt.set(t,{session:s,expiresAt:a}),s});return Xt.set(t,{session:r?.session??null,expiresAt:0,inflight:o}),o}function dM(e={}){let t=e.path??DS;return Object.assign(async()=>(await LS(e))?.access_token??null,{invalidate:n=>{let r=Xt.get(t);r&&!r.inflight&&r.session?.access_token===n&&Xt.delete(t)}})}var nr=new Map;async function gM(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let s=await n.json().catch(()=>null);s?.error==="app_not_linked"&&console.warn(`[kortix] ${String(s.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let o=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return nr.set(e,{token:r.token,refreshAt:Number.isFinite(o)?o-Yo:Date.now()+Yo}),r.token}catch{return null}}function jS(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((o,s)=>fetch(o,s));return async(o={})=>{let s=nr.get(n);if(s instanceof Promise)return s;if(s&&!o.forceRefreshToken&&s.refreshAt>Date.now())return s.token;let i=gM(n,r).then(a=>(a===null&&nr.delete(n),a));return nr.set(n,i),i}}function mM(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("kortixBinding needs the App origin: pass { origin } outside a browser.");return{url:`${ue(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:jS({audience:e,fetch:t.fetch})}}var wt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},_e=e=>typeof e=="string"&&e.length>0?e:null;function $S(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Oa(e){if(!e||typeof e!="object")return null;let t=e,n=_e(t.sub)??_e(t.subject)??_e(t.user_id)??_e(t.userId);return n?{userId:n,email:_e(t.email),name:_e(t.name),picture:_e(t.picture)??_e(t.pictureUrl),groups:$S(t.groups),groupIds:$S(t.group_ids??t.groupIds),role:_e(t.role),accountId:_e(t.account_id)??_e(t.accountId),projectId:_e(t.project_id)??_e(t.projectId)}:null}function fM(e,t={}){let n=Oa(e);if(!n)throw new wt("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:o}=t;if(r&&!r.some(s=>n.groups.includes(s)||n.groupIds.includes(s)))throw new wt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(o&&!o.some(s=>n.role===s))throw new wt("forbidden",`Only ${o.join(" or ")||"no role"} members may do this.`);return n}var yM=60,Ma=new Map;function FS(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function US(e){return JSON.parse(new TextDecoder().decode(FS(e)))}async function hM(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),o=e.slice(n+1),s=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(o),i=>i.charCodeAt(0))):decodeURIComponent(o);return JSON.parse(s)}if(/^https?:\/\//.test(e)){let n=Ma.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>Ma.delete(e)),Ma.set(e,n)),n}return JSON.parse(e)}async function _M(e,t={}){let n=b=>{throw new wt("unauthenticated",`Kortix sign-in token refused: ${b}.`)},r=t.jwks??et("KORTIX_AUTH_JWKS"),o=t.issuer??et("KORTIX_AUTH_ISSUER"),s=t.audience??et("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(s!==!1&&!s)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,l,p]=i,d,g;try{d=US(a),g=US(l)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await hM(r,t.fetch??((b,M)=>fetch(b,M)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(b=>b.kty==="EC"&&(d.kid===void 0||b.kid===d.kid));if(f.length===0)return n("unknown key");let _=new TextEncoder().encode(`${a}.${l}`),y;try{y=FS(p)}catch{return n("malformed")}let k=!1;for(let b of f)try{let{kid:M,alg:h,use:x,key_ops:P,...v}=b,T=await crypto.subtle.importKey("jwk",v,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},T,y,_)){k=!0;break}}catch{}if(!k)return n("bad signature");let R=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+yM<R)return n("expired");if(o&&g.iss!==o)return n("wrong issuer");if(s){let b=g.aud;if(!(b===s||Array.isArray(b)&&b.includes(s)))return n("wrong audience")}let I=Oa(g);return I||n("no subject")}function NS(e){let t=e.agents.map(bM),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,o)=>r.name===n?-1:o.name===n?1:0):t}function bM(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.hidden===!0||e.enabled===!1}}function BS(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>si(n?{...r,mode:null}:r))}function PM(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let s=e.selectedAgent?.trim();return s?{selected:s,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=BS(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(s=>s.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let o=e.defaultAgent?.trim();return o&&n.some(s=>s.name===o)?{selected:o,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var SM=NS;function KS(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Da(e){return{providerID:"kortix",modelID:e}}function rr(e,t){return Da(e.startsWith("kortix/")?e.slice(7):e)}var La=[{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"bee",env:["BEE_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"infer",env:["INFER_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"inferx",env:["INFERX_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY","PRIVATEMODE_ENDPOINT"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]}];function ja(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function wM(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function qS(e,t){let n=new Map;for(let r of e){let o=t(r),s=n.get(o);s?s.push(r):n.set(o,[r])}return n}function or(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function GS(e){return e.reduce((t,n)=>{let r=ja(n)??0,o=ja(t)??0;return r!==o?r>o?n:t:or(n.id)>or(t.id)?n:t})}function $a(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,o=new Set;for(let[,s]of qS(e,wM)){let a=[...qS(s,p=>p.family||p.id).values()].map(GS),l=a.filter(p=>{let d=ja(p);return d!==null&&Math.abs(n-d)<r});for(let p of l.length>0?l:[GS(a)])o.add(p.id)}return o}function Ua(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>or(r.id)>0)?n.filter(r=>or(r.id)>0):n}var kM={"amazon-bedrock":{methods:[{label:"Bearer token",envVars:["AWS_BEARER_TOKEN_BEDROCK","AWS_REGION"]}]},google:{methods:[{envVars:["GOOGLE_GENERATIVE_AI_API_KEY"]},{envVars:["GOOGLE_API_KEY"]},{envVars:["GEMINI_API_KEY"]}]}};function HS(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var vM=(()=>{let e=new Map;for(let{id:n,env:r}of La)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let o=[...r].sort((s,i)=>s.length-i.length||s.localeCompare(i));t.set(n,r.find(s=>HS(s)===n)??o[0])}return t})();function VS(e){let t=kM[e.id];if(t)return t;let n=e.env??[],r=n.length===1?vM.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[HS(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}var AM=["low","medium","high"];function zS(e){if(!e)return{temperature:!1,topP:!1};let t=e.reasoning_options?.find(a=>a.type==="effort"),n=e.reasoning_options?.find(a=>a.type==="budget_tokens"),r=t?.values?.length?{values:t.values}:n?{values:[...AM]}:void 0,o=e.temperature===!0,s=e.limit?.output,i=typeof s=="number"&&s>0?{ceiling:s}:void 0;return{reasoningEffort:r,temperature:o,topP:o,maxOutputTokens:i}}var YS=La;var WS={allow_fallbacks:!0,zdr:!0,data_collection:"deny"};var Jo=[{id:"deepseek-v4.1-flash",name:"DeepSeek V4.1 Flash",upstreamModelId:"deepseek/deepseek-v4.1-flash-1017",transport:"openrouter",morphModelId:"morph-dsv41flash-1017",morphPricing:{inputPerMillion:.15,cachedInputPerMillion:.003,outputPerMillion:.6},pricingRef:"openrouter/deepseek/deepseek-v4.1-flash",pricing:{inputPerMillion:.2,cachedInputPerMillion:.03,outputPerMillion:.65},openrouterEndpointPricing:{"deepinfra/fp8":{inputPerMillion:.098,cachedInputPerMillion:.00294,outputPerMillion:.294},"deepinfra/fp8/priority":{inputPerMillion:.147,cachedInputPerMillion:.00441,outputPerMillion:.441},"inference-net/fp8":{inputPerMillion:.08,cachedInputPerMillion:.008,outputPerMillion:.5},"wafer/mxfp4":{inputPerMillion:.1,cachedInputPerMillion:.003,outputPerMillion:.5},cloudflare:{inputPerMillion:.1,cachedInputPerMillion:.003,outputPerMillion:.6}},tier:"balanced",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["none","low","high","max"]}],openrouterProvider:{only:["deepinfra/fp8","deepinfra/fp8/priority","inference-net/fp8","wafer/mxfp4","cloudflare"],...WS,max_price:{prompt:.3,completion:1.2}}},{id:"glm-5.3-flash",name:"GLM 5.3 Flash",upstreamModelId:"z-ai/glm-5.3-flash",transport:"openrouter",morphModelId:"morph-glm53flash",morphPricing:{inputPerMillion:.1,cachedInputPerMillion:.02,outputPerMillion:.35},pricingRef:"openrouter/z-ai/glm-5.3-flash",pricing:{inputPerMillion:.15,cachedInputPerMillion:.05,outputPerMillion:.5},openrouterEndpointPricing:{fireworks:{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"deepinfra/fp4":{inputPerMillion:.075,cachedInputPerMillion:.015,outputPerMillion:.25},together:{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"parasail/fp4":{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"modal/nvfp4":{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"crusoe/fp4":{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"inference-net/fp4":{inputPerMillion:.12,cachedInputPerMillion:.032,outputPerMillion:.388},makora:{inputPerMillion:.14,cachedInputPerMillion:.024,outputPerMillion:.47},"near-ai/fp8":{inputPerMillion:.08,cachedInputPerMillion:.012,outputPerMillion:.5},"open-inference/fp4":{inputPerMillion:.048,cachedInputPerMillion:.006,outputPerMillion:.16},primeintellect:{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},"siliconflow/fp8":{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5},venice:{inputPerMillion:.15,cachedInputPerMillion:.03,outputPerMillion:.5}},tier:"fast",vision:!0,limit:{context:1e6,output:65536},reasoningOptions:[{type:"effort",values:["low","high","max"]}],openrouterProvider:{only:["fireworks","deepinfra/fp4","together","parasail/fp4","modal/nvfp4","crusoe/fp4","inference-net/fp4","makora","near-ai/fp8","open-inference/fp4","primeintellect","siliconflow/fp8","venice"],...WS,max_price:{prompt:.15,completion:.5}}}],YQ=new Map(Jo.map(e=>[e.id,e]));var JS=Jo.map(e=>e.id),QS=(Jo.find(e=>e.tier==="flagship")??Jo[0]).id;var eX=YS.map(e=>({id:e.id,authRequirement:VS(e)})),XS=new Set(["kortix"]);function RM(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,o])=>{if(o.variants&&Object.keys(o.variants).length>0)return[r,o];let s=zS({id:r,name:o.name,reasoning:o.reasoning,reasoning_options:o.reasoning_options}).reasoningEffort?.values;return s?.length?[r,{...o,variants:Object.fromEntries(s.map(i=>[i,{}]))}]:[r,o]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function CM(e){return e.modelPicker?RM(e.modelPicker):void 0}function TM(e){return"capabilities"in e&&e.capabilities!=null}function Fa(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1}function IM(e,t){if(!e)return[];let n=Array.isArray(e.all)?e.all:[],r=Array.isArray(e.connected)?e.connected:[],o=[];for(let s of n)if(r.includes(s.id)&&XS.has(s.id))for(let[i,a]of Object.entries(s.models)){if(i==="auto"||i==="kortix/auto")continue;let l;if(TM(a)){let p=a.capabilities;l={reasoning:p.reasoning??!1,vision:p.input?p.input.image??!1:void 0,toolcall:p.toolcall??!1}}else{let p=a.modalities?.input;l={reasoning:a.reasoning??!1,vision:p?p.includes("image"):a.attachment,toolcall:a.tool_call??!1}}o.push({id:KS({providerID:s.id,modelID:i}),providerID:s.id,providerName:a.provider_name??s.name,modelID:i,modelName:(a.name||i).replace("(latest)","").trim(),variants:a.variants,capabilities:l,contextWindow:a.limit?.context,releaseDate:a.release_date,family:a.family,cost:a.cost?{input:a.cost.input??0,output:a.cost.output??0}:void 0,providerSource:s.source,provider:a.provider,reasoningOptions:a.reasoning_options,description:a.description,openWeights:a.open_weights,lastUpdated:a.last_updated,enabled:a.enabled,free:a.free===!0})}return o}function ZS(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var EM=new Set([QS]),MM="kortix",ex="codex",OM=new Set(JS);function DM(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Zt(e){return EM.has(e.modelID)}function LM(e){return $a(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function jM(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=LM(e.catalogModels),o=ZS(e.catalogModels),s=new Map;for(let i of e.pins??[])s.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,l=s.get(a);if(l==="hide")return!1;if(i.providerID===MM){let d=DM(i.modelID,i.provider),g=d===ex?t?.has(ex)??!1:t?.has(d)??!1;if(OM.has(i.modelID))return!n;if(!g)return!1;if(l==="show"||r.has(a))return!0;let m=o.get(a);if(!m?.releaseDate)return Zt(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Zt(i)}catch{return Zt(i)}return!1}if(l==="show"||r.has(a))return!0;let p=o.get(a);if(!p?.releaseDate)return Zt(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Zt(i)}catch{return Zt(i)}return!1}}function $M(e,t){return t.search.trim().length>0||e.providerID==="kortix"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function UM(e,t){let n=(t?e?.agentDefaults?.[t]:void 0)??e?.projectDefault??e?.accountDefault??(e?.freeTier?void 0:e?.platformDefault);return n?Da(n):void 0}function FM(e){for(let t=(e?.length??0)-1;t>=0;t--){let n=e[t],{provider:r,model:o}=n.model??{};if(n.role==="user"&&r&&o)return{providerID:r,modelID:o}}}var NM=new Set(["explicit","repointed","fallback"]);function BM(e){let t=e?.metadata;if(t?.opencode_model_source!=="fallback")return;let{opencode_model:n,opencode_model_fallback_from:r,opencode_model_fallback_at:o}=t;if(typeof n!="string"||typeof r!="string"||typeof o!="number")return;let s=t.opencode_model_fallback_reason;return{model:rr(n),from:rr(r),reason:typeof s=="string"?s:"other",atMs:o}}function KM(e,t){return!t||(e??-1)>=t.atMs}function qM(e){let t=e.session?Fr(e.session):null,n=t?rr(t):void 0,r=e.session?.metadata;return(NM.has(String(r?.opencode_model_source))||r?.opencode_model_restored===!0?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(i=>!!i)}function GM(e){let{models:t,providers:n}=e,r=l=>Fa(t,l),o=l=>l.find(p=>!!p&&r(p)),s=(()=>{if(e.configModel){let l=e.configModel.split("/");if(l.length>=2){let[p,...d]=l,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let l of e.recent??[])if(r(l))return l;if(n){let l=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=l[m.id];if(f){let _={providerID:m.id,modelID:f};if(r(_))return _}for(let _ of Ua(Object.keys(m.models).map(y=>({id:y})))){let y={providerID:m.id,modelID:_.id};if(r(y))return y}}}})(),i=o(e.picks??[]);return{model:i??o([e.serverDefault,e.globalDefault,e.agentModel,s]),explicit:i,fallback:s}}export{zT as ABORT_REASONS,Cz as ABORT_REASONS_NOT_YET_EMITTED,ec as ACCOUNTS_LIST_UNAVAILABLE_CODE,Ko as ACTIVE_INSTANCE_COOKIE,Za as ANALYTICS_UNAVAILABLE_CODE,fI as ATTACHMENT_PART_REF_PREFIX,S as ApiError,ie as AuthError,ut as BillingError,R1 as CAPTURE_DEVICE_DEFAULTS,w1 as CAPTURE_EXCLUSION_GROUPS,v1 as CAPTURE_FRAME_INTERVALS_MS,x1 as CAPTURE_LAYERS,A1 as CAPTURE_MAX_HEIGHTS,k1 as CAPTURE_RETENTION_LIMITS,RI as CONNECTION_FAULT_GRACE_MS,pI as CONNECTOR_POLL_FIRST_DELAY_MS,dI as CONNECTOR_POLL_INTERVAL_MS,gI as CONNECTOR_POLL_WINDOW_MS,RR as CONTEXT_TOOLS,yP as COST_MARKUP,Ss as ConnectorApprovalPendingError,kr as ConnectorCallError,xs as ConnectorPageLimitError,CR as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,kN as DEFAULT_NOTIFICATION_PREFERENCES,ib as DEFAULT_TRANSCRIPT_OPTIONS,aI as DESTRUCTIVE_PHASES,en as FEATURE_DISABLED_CODE,DO as FEATURE_FLAG_KEYS,Ya as FEATURE_NOT_SUPPORTED_CODE,St as FILE_VERBS,In as FileExistsError,hn as HeadlessAuthError,Go as HostBoundaryError,hx as IMPERSONATION_HEADER,wN as INBOX_NOTIFICATION_KINDS,ha as INBOX_OBSERVATION_MAX_MS,fJ as INITIAL_SETTLED_CONNECTION,YT as INSTANCE_SCOPED_ROUTES,mw as KNOWN_TOOL_KINDS,Te as KORTIX_TRANSCRIPT_SCHEMA,wt as KortixMemberError,ew as MAX_PROMPT_ATTACHMENTS_BYTES,ks as MAX_PROMPT_ATTACHMENT_BYTES,Wu as MAX_PROMPT_ATTACHMENT_FILES,iz as MEMORY_VERBS,Ja as MODEL_NOT_SERVABLE_CODE,Nk as NO_GROUP_ACTIVITY_TOOLS,_a as OPTIMISTIC_ABORT_MAX_MS,UJ as OPTIMISTIC_COMPACTION_MAX_MS,fa as OPTIMISTIC_RECEIPT_MAX_MS,L2 as PERSISTED_QUERY_CACHE_VERSION,HC as PLUMBING_TOOLS,rJ as PREVIEW_PROBE_TIMEOUT_MS,Z as PROJECT_ACTIONS,QL as PROJECT_SESSION_NAME_LOOKUP_LIMIT,JL as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,Dw as PROJECT_SESSION_PAGE_MAX_LIMIT,Qa as PROVISION_IN_FLIGHT_CODE,Ux as PROVISION_STREAM_UNTERMINATED_CODE,js as PublicSessionShareError,cr as REPOSITORY_DISCONNECTED_CODE,j$ as REVIEW_CONTROL_ACTIONS,Bz as RUNTIME_NOT_READY_MARKERS,jN as RUNTIME_PERMISSION_CAPABILITIES,LN as RUNTIME_PERMISSION_REPLIES,kt as RequestTooLargeError,vn as RuntimeNotReadyError,Di as SANDBOX_FS_ROOTS,tt as SANDBOX_PORTS,Xa as SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE,DI as SERVER_COMPACTION_REVALIDATE_MS,ya as SERVER_OBSERVATION_MAX_MS,QJ as SESSION_LIST_STATUS,Ia as SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES,Pe as SESSION_LOG_MINOR,le as SESSION_LOG_SCHEMA,e4 as SESSION_NOTICE,Bk as STANDALONE_TOOLS,Zn as STREAM_OBSERVATION_MAX_MS,qo as SandboxNotReadyError,Bt as SessionNotReadyError,Is as SessionStartError,D$ as TRIGGER_CONTROL_ACTIONS,RJ as TURN_END_LEDGER_LAG_MS,dk as TURN_ERROR_CODES,WJ as WAKE_ESCALATION_COOLDOWN_MS,GJ as WAKE_MAX_RESTARTS,qJ as WAKE_NO_PROGRESS_MS,wi as WIRE_ID_BACKDATE_MS,yt as WIRE_ID_CLOCK_TOLERANCE,ot as WIRE_ID_TIME_MASK,xn as WIRE_ID_TIME_SCALE,cv as WIRE_MESSAGE_ID,HM as __getConfigResolver,WM as __setConfigResolver,Tz as abortErrorReason,ls as acceptAccountInvite,kc as acceptAccountInviteAndLand,cg as acceptEnterpriseOffer,bY as acceptInvite,$x as accountInviteLanding,Em as actReviewItem,Ql as activateConnection,eu as addComputerToProject,rm as addGroupMembers,Af as addMarketplaceSource,Zm as addRoomPerson,Qm as addRoomSession,VJ as advanceWakeEscalation,lC as allDescendantIds,G2 as appendPreviewToken,Y_ as approveCaptureDeviceGrant,$_ as approveCaptureEnrollment,ol as approveProjectAccessRequest,DK as approveTask,Sr as archiveProject,KK as assignTicket,ml as attachGroupToProject,hi as authMfa,mi as authUser,$ as authenticatedFetch,Ar as authenticatedRequest,tJ as authorizePreviewUrl,c as backendApi,i$ as bindSlackIdentity,a$ as bindTeamsIdentity,Al as brokerProjectSecretRequest,U2 as browserKeyValueStorage,QT as buildInstancePath,cJ as buildPresentationTemplateImageUrl,aJ as buildPresentationTemplatePdfUrl,NP as buildPreviewAuthEndpoint,P2 as buildPublicTemplateUrl,AI as buildRuntimePresentationConversionUrl,$u as buildSandboxTemplate,_C as buildScrapeFailureResults,vG as buildStaticFileHealthPreviewUrl,kG as buildStaticFileLocalUrl,wG as buildStaticFilePreviewUrl,CA as buildStaticFileServicePath,OQ as buildTunnelEventStreamUrl,IG as buildWebProxyUrl,Mm as bulkActReviewItems,i0 as bulkDeletePolicies,a0 as bulkImportPolicies,sa as burstSummary,JC as burstSummaryLabel,Qb as burstWorkLabel,It as callConnector,Kw as canManageBilling,Kj as canOfferTopup,IU as cancelAccountDeletion,Pc as cancelAccountInvite,aY as cancelSandbox,UY as cancelSandboxUpdate,tg as cancelScheduledChange,Xd as cancelSubscription,O1 as captureHealthBucket,tk as changeRequestControlsFrom,n2 as checkAccessEmail,BD as checkMcpServerSignIn,oH as childMapByParent,WY as claimComputer,WA as claimNext,Vj as claimPerSeatBilling,Gp as claimWarmProjectSession,Lb as classifyPart,kI as classifyPreviewProbeStatus,fv as classifyPtyClose,CE as classifySessionLogMessage,Yi as classifyTurn,bH as cleanErrorMessage,vH as cleanResultSnippet,QV as cleanWorkerOutput,nc as clearImpersonationSession,uM as clearKortixAppViewerCache,Dd as clearModelDefault,vL as clearSessionFresh,lp as closeChangeRequest,yq as closeMilestone,uH as collectTurnParts,GK as commentTicket,dp as commitSessionChanges,NJ as compactionExpiryAtMs,ZH as compactionTurnInfo,Xi as compareForDisplayAt,rH as compareMessagesForDisplay,F1 as compareSemver,HA as completeInFlight,bg as completeSlackInstall,Pg as completeTeamsInstall,BS as composerSelectableAgents,gP as computeStatusFromPart,sg as configureAutoTopup,Zo as configureKortix,Jd as confirmCheckoutSession,Rg as connectEmail,yg as connectSlack,p$ as connectTelegram,mJ as connectionFromHealth,gJ as connectionIsFaulted,RD as connectionSharedWithEveryone,zx as connectorConnect,Yx as connectorFinalize,A2 as connectorHeadline,lg as contactEnterpriseSales,NH as contextLabelForTool,_W as contextToolSummary,bW as contextToolTrigger,HU as convertPresentationToGoogleSlides,lJ as convertRuntimePresentation,bo as copyFile,pg as costExportUrl,TJ as countLiveInboxPrompts,T$ as countReviewItemsBySegment,lc as createAccount,ff as createAccountAuditWebhook,Dl as createAccountSecretResource,rf as createAccountToken,Tf as createApp,$f as createAppAccessSession,Ff as createAppDeployment,Mf as createAppToken,ty as createAppVolume,sy as createAppVolumeSnapshot,BH as createArtifactKind,wm as createAssignment,sU as createAuditWebhook,wY as createBackup,D_ as createCaptureEnrollmentToken,Yd as createCheckoutSession,mu as createConnector,w2 as createConnectorLinkInfoCache,_o as createFile,Wg as createGatewayKey,Zg as createGroup,eM as createHttpSessionSyncController,KY as createInstance,BA as createKortix,Sh as createKortixPty,bi as createKortixSession,AF as createMarketplaceInstallSession,mq as createMilestone,jM as createModelVisibility,_m as createOAuthClient,Hj as createPerSeatCheckout,$2 as createPersistedQueryCache,r0 as createPolicy,Qd as createPortalSession,Lc as createProject,eq as createProjectAgent,lf as createProjectCliToken,jc as createProjectRepo,_l as createProjectResourceGrant,Lt as createProjectSession,Kc as createProjectSkill,gd as createProjectTrigger,P_ as createPromptAttachmentController,um as createRole,Wm as createRoom,DQ as createSSEStream,eY as createSandbox,Dm as createSandboxShare,Du as createSandboxTemplate,LL as createSavedCopyStore,h0 as createScimToken,Q0 as createServiceAccountApi,jr as createSessionPrompt,Bp as createSessionPublicShare,qA as createSessionQueue,Fm as createSessionReminder,j0 as createSsoGroupMapping,EK as createTask,FK as createTicket,LQ as createTunnelEventStream,fQ as createWarmSessionPool,Rp as currentSavedCopyStore,vc as declineAccountInvite,PY as declineInvite,EU as deleteAccountImmediately,$l as deleteAccountSecretResource,Ef as deleteApp,Wf as deleteAppDeployment,aU as deleteAuditWebhook,vY as deleteBackup,_u as deleteConnector,ku as deleteConnectorCredential,wq as deleteCredential,Xr as deleteCustomLlmProvider,oN as deleteDriveFile,bh as deleteEnv,Wt as deleteFile,qg as deleteGatewayBudget,el as deleteGitHubInstallation,tm as deleteGroup,qY as deleteInstance,lq as deleteKortixProject,_q as deleteMilestone,Sm as deleteOAuthClient,El as deletePersonalProjectSecret,s0 as deletePolicy,nq as deleteProjectAgent,Cl as deleteProjectProviderOAuth,bl as deleteProjectResourceGrant,xr as deleteProjectSecret,td as deleteProjectSession,fd as deleteProjectTrigger,ln as deletePromptAttachment,gm as deleteRole,ju as deleteSandboxTemplate,Z0 as deleteServiceAccountApi,Yp as deleteSessionPrompt,Us as deleteSessionReminder,Km as deleteSessionReminders,$0 as deleteSsoGroupMapping,D0 as deleteSsoProvider,LK as deleteTask,WK as deleteTicket,J_ as denyCaptureDeviceGrant,U_ as denyCaptureEnrollment,wc as describeAccountInvite,ys as describeConnectorTool,Qf as destroyAppMachine,ry as destroyAppVolume,yl as detachGroupFromProject,kA as detectLocalhostUrls,r4 as directSubsessions,X0 as disableServiceAccountApi,Cg as disconnectEmail,O2 as disconnectGitHubApp,xg as disconnectSlack,g$ as disconnectTelegram,ED as discoverConnectionOAuth2,MD as discoverConnectionOAuth2Resource,fu as discoverConnectorAuth,oY as discoverLocalSandbox,QF as dismissDriveConflict,_2 as downloadAccountAudit,ZF as downloadDriveFile,$q as dropClientForUrl,Nq as dropPublicClientForUrl,JA as editQueued,Jp as editSessionPrompt,GA as enqueue,XK as ensurePmSession,wI as ensurePreviewSessionCookie,CD as ensureProjectConnectorConnection,iI as ensureSandbox,qp as ensureWarmProjectSession,gv as env,pi as exchangeCode,Zf as execInApp,gf as exportAccountAudit,xe as extractGatewayErrorDetails,Jn as extractInstanceRoute,PT as extractSkillBaseDir,Pz as extractSkillContent,hT as extractSkillFiles,ZV as extractWorkerPreview,VA as failInFlight,xV as fallbackBusyRowAfterTurnId,Hn as familyForTool,qa as featureDisabledKey,qy as featureFlags,qj as fetchAccountStateWithToken,TO as fetchAccountsWithToken,K2 as fetchAttachmentPart,n$ as fetchCostExportCsv,LS as fetchKortixAppViewer,qu as fetchProjectArchive,pL as fetchProjectFileRaw,qO as fetchProjectsForAccountWithToken,By as fetchSessionAttachment,Jv as fileDownloadRequest,rz as filePhase,nz as fileVerb,lA as files,qs as finalizeAppArtifact,l2 as finalizeConnectorSetupLink,ZL as findActiveTranscriptShare,yo as findFiles,pH as findLastTextPart,rB as findSessionAttachments,ho as findText,_d as fireProjectTrigger,Ou as fixSandboxWithAgent,IM as flattenModels,aV as flattenThought,ay as forkAppVolume,Wa as formatBillingErrorForUI,$V as formatCost,fP as formatDuration,PH as formatJsonFailureOutput,uV as formatMessageDay,pV as formatMessageExact,qz as formatOpenCodeRuntimeError,kH as formatRawOutput,sI as formatRuntimeError,UV as formatTokens,rR as formatTranscript,AV as freshSendHint,KA as generateSessionId,uc as getAccount,ij as getAccountAutomations,dc as getAccountBranding,CU as getAccountDeletionStatus,Kd as getAccountState,qd as getAccountStateMinimal,ZT as getActiveInstanceIdFromCookie,FU as getAdminProviderAnalytics,jU as getAdminProviderDistribution,BU as getAdminProviderFallback,MU as getAdminRole,jR as getAgentCardLabel,Dj as getAgentConfig,rq as getAgentPersona,LY as getAllVersions,gH as getAnsweredQuestionParts,Bs as getApp,Df as getAppAccess,Of as getAppAuthEnv,Bf as getAppDeployment,Kf as getAppDeploymentLogs,xF as getApprovalLink,on as getAuthToken,PD as getAuthTokenWithRetry,og as getAutoTopupSettings,Wj as getAutoTopupSetupStatus,Hd as getBillingCreditBreakdown,zd as getBillingTierConfigurations,Wd as getBillingTransactionsSummary,Vd as getBillingUsageHistory,V_ as getCaptureAssetUrl,H_ as getCaptureChunkMedia,q_ as getCaptureDays,z_ as getCaptureDeviceGrant,W_ as getCaptureFrame,F_ as getCapturePolicy,B_ as getCaptureTimeline,K_ as getCaptureTimelineItems,Q_ as getCaptureWorkspace,op as getChangeRequest,sp as getChangeRequestDiff,ip as getChangeRequestMergePreview,LW as getChildSessionError,Eo as getChildSessionId,jW as getChildSessionToolParts,ht as getClient,He as getClientForUrl,xu as getConnectStatus,ID as getConnectionOAuth2Application,$D as getConnectionOAuth2Status,UD as getConnectionPolicies,sn as getConnectorCatalog,pu as getConnectorConfig,lu as getConnectorPolicies,a2 as getConnectorSetupLink,t$ as getCostSummary,XT as getCurrentInstanceIdFromPathname,Oz as getCurrentInstanceIdFromWindow,Jh as getCurrentProject,Fd as getDefaultAccountState,FW as getDiagnostics,LR as getDirectory,Ps as getDiscoverConnector,WD as getDiscoverIntegration,cy as getDriveFileUrl,vg as getEmailInstallation,Ag as getEmailMode,fU as getEnterpriseDemo,fo as getFileStatus,Rb as getFileWithDir,DR as getFilename,HF as getFolderAccess,cI as getFullChangelog,Ug as getGatewayBreakdown,Bg as getGatewayBudgets,Ng as getGatewayErrors,Gg as getGatewayKeys,Lg as getGatewayLog,jg as getGatewayOverview,Ig as getGatewayRoutingPolicy,$g as getGatewaySeries,Fg as getGatewaySessions,T2 as getGitHubAppStatus,Hc as getGitHubInstallation,WU as getGoogleAuthUrl,Xg as getGroup,OW as getHiddenToolParts,Px as getImpersonationSession,_Y as getInvite,BY as getJustavpsServerTypes,iq as getKortixProject,aq as getKortixProjectBySession,kh as getKortixPtyWebSocketUrl,DY as getLatestSandboxVersion,m2 as getMaintenanceConfig,tl as getManagedGitBackend,FO as getManagedGitStatus,wf as getMarketplaceCatalogItem,kf as getMarketplaceCatalogItemFile,x0 as getMfaRequired,dq as getMilestone,rb as getMobileClientPolicy,Md as getModelDefaults,tb as getMyCaptureFrame,eb as getMyCaptureTimeline,my as getNotificationPreferences,hm as getOAuthClient,s2 as getOAuthConsentRequest,Fz as getOpenCodeConfigInvalidError,IW as getPartText,W0 as getPatPolicy,NW as getPermissionForTool,Ct as getProject,oq as getProjectActivity,Zu as getProjectCommit,ep as getProjectCommitDiff,hr as getProjectDetail,WF as getProjectDrive,tp as getProjectFileHistory,QO as getProjectGitConnectionState,Dc as getProjectGitToken,_r as getProjectLlmCatalog,jO as getProjectLlmCatalogProviders,zr as getProjectModelAccess,br as getProjectModelPicker,UO as getProjectQuota,vr as getProjectSandboxHealth,NO as getProjectSandboxProviderTransition,Or as getProjectSession,od as getProjectSessionConfigState,ad as getProjectSessionScope,ng as getProrationPreview,Xz as getProviders,AG as getProxyBaseUrl,Fq as getPublicClientForUrl,e2 as getPublicMarketplaceItem,t2 as getPublicMarketplaceItemFile,tF as getPublicSessionShare,nF as getPublicSessionShareMessages,d2 as getPublicShareByToken,S2 as getPublicTemplate,BW as getQuestionForTool,x$ as getReferralCode,v$ as getReferralStats,FV as getRetryInfo,NV as getRetryMessage,Tm as getReviewItem,Cm as getReviewSummary,cm as getRolePermissions,lm as getRoleUsage,Hm as getRoom,pa as getRuntimeConfigInvalidError,CY as getSSHConnection,Zz as getSandbox,tY as getSandboxById,Vz as getSandboxPortUrl,HY as getSandboxProvisionStatus,VY as getSandboxProvisionStreamUrl,OY as getSandboxUpdateStatus,MP as getSandboxUrl,Fe as getSandboxUrlForExternalId,u2 as getSecretSetupLink,Li as getServerHealth,Aq as getServiceLogs,Wp as getSessionAudit,jV as getSessionCost,Wr as getSessionCostRecord,lk as getSessionDrives,r_ as getSessionHealth,Vp as getSessionLogPage,ud as getSessionMessageAuthors,pd as getSessionModelUsage,ej as getSessionOpenBundle,v0 as getSessionOversight,Dp as getSessionParticipants,B0 as getSessionPolicy,Fp as getSessionPreviewCandidates,Bl as getSessionProviderSecretPool,Hp as getSessionTranscript,Dr as getSessionTranscriptSync,Lr as getSessionTurn,Lp as getSessionWatch,zV as getShellModePart,wg as getSlackChannelFile,fg as getSlackInstallation,Sg as getSlackManifest,hg as getSlackMode,I0 as getSsoProvider,TA as getStaticFileHealthPath,gs as getSupabaseAccessToken,qx as getSupabaseAccessTokenWithRetry,CK as getTask,IK as getTaskStatus,u$ as getTelegramInstallation,TF as getTemplate,$K as getTicket,$W as getToolInfo,Hi as getToolPrimaryArg,oR as getTranscriptFilename,ca as getTurnCost,OV as getTurnError,LV as getTurnErrorDetails,DV as getTurnErrorRawText,mP as getTurnStatus,ug as getUsageRollup,y2 as getUserRolesWithToken,np as getVersionDiff,yy as getWebPushPublicKey,EV as getWorkingState,Ul as grantAccountSecretResource,mY as grantSandboxProjectAccess,jj as grantSecretToAgent,lH as groupMessagesIntoTurns,cP as groupShowSegments,Zb as groupSteps,BV as hasDiffs,xG as hasLocalhostUrls,RA as hasPreviewTarget,Bb as hasRetryingAssistantTurn,Uv as heartbeatGapEvent,Zp as holdSessionPrompts,Jg as humanizeReviewActionPath,Co as humanizeSearchQuery,Mb as humanizeToolName,rc as impersonationHeaders,M0 as importSsoProviderFromMetadata,CJ as inboxObservationSupersedes,WP as initialWakeEscalationState,Ie as inputPath,IF as installTemplate,Qp as interruptSessionPrompt,ms as invalidateTokenCache,_c as inviteAccountMember,ll as inviteProjectMember,Mc as inviteRepoCollaborator,Bo as isAbortError,kx as isAdminBypassEnabled,vW as isAgentPart,SA as isAppRouteUrl,EW as isAttachment,yI as isAttachmentPartRef,tn as isAuthFailure,Ga as isBillingError,AW as isCompactionPart,es as isConfigured,hW as isContextTool,MY as isDestructivePhase,OS as isEmptyConversation,ei as isEmptyShowPart,_H as isErrorOutput,OG as isExternalUrl,Ka as isFeatureDisabledError,Cb as isFilePart,_x as isImpersonationSessionLive,Ez as isInstanceDetailPath,JT as isInstanceScopedAppPath,TG as isInternalLocalhostUrl,Uy as isInvisibleActivityPart,sD as isInviteSent,IV as isLastUserMessage,UI as isLegacyMigratedSession,LO as isManagedGithubProject,$y as isNoGroupActivityTool,Fa as isOfferedModel,Nz as isOpenCodeConfigInvalidError,xw as isPaintableSavedCopy,CW as isPatchPart,j2 as isPersistableQueryKey,CG as isPreviewUrl,IA as isProxiableLocalhostUrl,jy as isQuestionTool,we as isReasoningPart,ax as isRepositoryDisconnectedError,dC as isRetryableTurnError,eI as isRuntimeConfigInvalidError,rI as isRuntimeNotReadyResponse,n_ as isRuntimeReady,Kz as isRuntimeStartingError,Xn as isSandboxNotReadyError,si as isSelectableAgent,Qh as isServerReachable,nB as isSessionAttachmentRef,mp as isSessionFresh,ME as isSessionLogRestoreNote,yj as isSessionStartError,VN as isShellActivityTool,fT as isShellMode,XV as isShortOutput,ON as isShowContentUnavailable,Zr as isShowPayloadEmpty,RW as isSnapshotPart,Fy as isStandaloneActivityTool,TW as isStepPart,Wo as isSubdomainPreviewUrl,Je as isTextPart,te as isToolPart,DW as isToolPartHidden,Sy as isTurnErrorCode,Nh as isUnderSandboxRoot,MG as isWebProxyUrl,uv as isWireIdAheadOf,dM as kortixAppViewerToken,mM as kortixBinding,bv as kortixPty,jS as kortixToken,FM as latestPromptModel,Cc as leaveAccount,M_ as linkCaptureDevice,Xc as linkGitHubInstallation,Gc as linkRepository,pf as listAccountAudit,mf as listAccountAuditWebhooks,bc as listAccountInvites,hc as listAccountMembers,Q$ as listAccountResourceGrants,Ol as listAccountSecretResources,q0 as listAccountSessions,nf as listAccountTokens,cc as listAccounts,p0 as listActions,$U as listAdminSandboxes,im as listAgentIdentities,Hl as listAllConnections,Lf as listAppAgents,Nf as listAppDeployments,Vf as listAppMachines,oy as listAppVolumeSnapshots,ey as listAppVolumes,Cf as listApps,xm as listAssignments,cU as listAuditEvents,oU as listAuditWebhooks,xY as listBackups,Gd as listBillingTransactions,I_ as listCaptureDevices,O_ as listCaptureEnrollmentTokens,j_ as listCaptureEnrollments,rp as listChangeRequests,m$ as listChannelBindings,HK as listColumns,qD as listConnectSections,KD as listConnectToolkits,Wl as listConnections,hs as listConnectorAccounts,yu as listConnectorMoves,fs as listConnectorTools,ou as listConnectors,e$ as listCostByProject,Pq as listCredentialEvents,bq as listCredentials,Jr as listCustomLlmProviders,bs as listDiscoverConnectors,GD as listDiscoverIntegrations,Su as listDiscoverSections,JF as listDriveConflicts,XF as listDriveFiles,ik as listDriveFolder,sN as listDriveVersions,hh as listEnv,xf as listFeaturedMarketplaces,zK as listFields,On as listFiles,YF as listFolderPrincipals,Dg as listGatewayLogs,Vc as listGitHubInstallations,Yc as listGitHubRepositories,Jc as listGitHubRepositoryBranches,nm as listGroupMembers,G$ as listGroupProjectGrants,Qg as listGroups,cq as listKortixProjectSessions,sq as listKortixProjects,Ph as listKortixPty,zc as listLinkableGitHubInstallations,nl as listManagedGitRepositories,Pf as listMarketplaceCatalogItems,vf as listMarketplaceSources,Sf as listMarketplaces,W$ as listMemberGroups,H$ as listMemberProjectAccess,gq as listMilestoneEvents,pq as listMilestones,xc as listMyAccountInvites,dy as listNotifications,ym as listOAuthClients,sf as listOAuthGrants,Pl as listPendingApprovals,ul as listPendingProjectInvites,vm as listPermissions,bu as listPipedreamApps,Pu as listPipedreamSections,n0 as listPolicies,il as listProjectAccess,rl as listProjectAccessRequests,am as listProjectAgentIdentities,ZK as listProjectAgents,df as listProjectAudit,Qu as listProjectBranches,cf as listProjectCliTokens,Xu as listProjectCommits,Nu as listProjectDirectory,Fu as listProjectFiles,gl as listProjectGroupGrants,Cu as listProjectPolicies,Rl as listProjectProviderOAuth,qm as listProjectReminders,hl as listProjectResourceGrants,Iu as listProjectSandboxTemplates,Uu as listProjectSandboxes,wl as listProjectSecrets,Dt as listProjectSessions,Mp as listProjectSessionsPage,Eu as listProjectSnapshots,wd as listProjectTriggerEventApps,xd as listProjectTriggerEventTypes,Pd as listProjectTriggerRuns,dd as listProjectTriggers,Rt as listProjects,Ec as listProjectsForAccount,XY as listPublicMarketplaceItems,ZY as listPublicMarketplaces,A$ as listReferrals,Rm as listReviewItems,sm as listRoles,zm as listRoomMessages,tf as listRoomPeople,Gm as listRooms,gY as listSandboxProjectMembers,Om as listSandboxShares,rY as listSandboxes,y0 as listScimTokens,J0 as listServiceAccountsApi,vq as listServiceTemplates,kq as listServices,ND as listSessionConnectRequests,dg as listSessionCosts,aN as listSessionDrives,zp as listSessionPrompts,Kl as listSessionProviderSecretPools,Np as listSessionPublicShares,Um as listSessionReminders,Sl as listSessionsNeedingInput,dF as listSignedInDevices,L0 as listSsoGroupMappings,TK as listTaskEvents,RK as listTasks,JK as listTemplates,UK as listTicketEvents,jK as listTickets,bd as listTriggerRuns,ZE as loadHttpSessionHistory,ft as loadPreviewUrlTemplate,qb as looksLikeError,MH as looksLikeHtml,wH as looksLikeJsonPayload,nN as makeDriveFolder,E$ as mapApiReviewItem,GY as markInstanceError,gy as markNotificationsRead,Jm as markRoomRead,Er as markSessionFresh,dh as maxWireIdClock,az as memoryRelPath,eP as mergeBurstSteps,cp as mergeChangeRequest,lV as messageCreatedAt,tT as messageTime,NU as migrateAdminSandboxProvider,ki as mintWireMessageId,mh as mintWireMessageIdAbove,$n as mkdir,$M as modelInDefaultView,rr as modelRefToKey,hu as moveConnector,rN as moveDriveFile,Jb as narrateFailedStep,Uo as narrateStep,$o as narrationToolName,Fv as narrowChatEvent,pv as newestWireIdClock,v2 as nextConnectorPollDelay,ye as normalizeActivityToolName,jz as normalizeAppPathname,T1 as normalizeCaptureAppId,C1 as normalizeCaptureDomain,DG as normalizeExternalInput,ee as normalizeName,Eb as normalizeToolName,BI as notifyHostSignal,ap as openChangeRequest,Ti as openEventStream,b2 as openStressTestStream,Ru as paginateConnector,lr as parseBillingError,AH as parseEmbeddedFailure,aB as parseFlagOverride,Gb as parseJsonFailure,wo as parseLocalhostUrl,cz as parseMemoryView,Uz as parseOpenCodeErrorPayload,gz as parsePresentationOutput,t_ as parseProxyHop,vP as parseQuestionAnswersFromOutput,hz as parseReadOutput,EP as parseRuntimeErrorPayload,hC as parseScrapeInputUrls,bC as parseScrapeOutput,d_ as parseSubdomainUrl,ez as parseTaskRows,EG as parseWebProxyUrl,Hb as parseWebSearchOutput,ea as partOutcome,uq as patchKortixProject,pz as patchVerb,CM as pickerProviderList,gu as pipedreamConnect,nu as pipedreamConnectConnection,vu as pipedreamFinalize,ru as pipedreamFinalizeConnection,C as platformConfig,jD as pollConnectionOAuth2DeviceAuthorization,ps as pollProjectProviderOAuth,Ym as postRoomMessage,ig as previewBillingPlan,Og as previewGatewayRoute,w0 as previewMfaRequired,c$ as previewSlackIdentity,l$ as previewTeamsIdentity,mm as probeEffectivePermission,fm as probeEffectivePermissions,oJ as probePreviewPort,Gu as projectArchiveRequest,FJ as projectCompacting,SM as projectConfigAgentsToOpenCodeAgents,NS as projectConfigAgentsToRuntimeAgents,dJ as projectSessionConnection,o4 as projectSessionForRuntimeId,Cd as projectSessionStartSeed,EJ as projectWorking,$c as provisionProject,$O as provisionProjectStream,GO as provisionProjectWithToken,u_ as proxyLocalhostUrl,RG as proxyUrlToInternal,rg as purchaseCredits,TD as putConnectionOAuth2Application,Qr as putCustomLlmProvider,Ro as rawErrorText,cY as reactivateSandbox,Zd as reactivateSubscription,Ln as readBlob,eN as readDriveFile,Dn as readFile,Oa as readKortixMember,Ku as readProjectFile,lM as readSavedSessionCopy,ia as reasoningIsRunning,Mu as rebuildProjectSnapshot,Vl as reconcileConnection,zl as reconcileMemberConnection,Cq as reconcileServices,o2 as recordPlatformLogout,ta as recoverLinkResults,nd as recoverProjectSession,w$ as refreshReferralCode,_n as refreshSession,Ks as registerAppArtifact,OD as registerConnectionOAuth2Client,ly as registerDeviceToken,Tq as registerService,hy as registerWebPushSubscription,sl as rejectProjectAccessRequest,UW as relativizePath,py as releaseDeviceToken,sd as reloadProjectSessionConfig,id as reloadProjectSessionConfigStream,hf as removeAccountAuditWebhook,fc as removeAccountBrandingAsset,Ac as removeAccountMember,om as removeGroupMember,wh as removeKortixPty,Rf as removeMarketplaceSource,qc as removeProjectSkill,YA as removeQueued,ef as removeRoomPerson,Xm as removeRoomSession,Zl as renameConnection,So as renameFile,nY as renameSandbox,up as reopenChangeRequest,hq as reopenMilestone,QA as reorderQueued,VK as replaceColumns,YK as replaceFields,Wc as replaceProjectRepository,QK as replaceTemplates,Sd as replayTriggerRun,cx as repositoryDisconnectedReason,TU as requestAccountDeletion,pp as requestChangesOnChangeRequest,oD as requestProjectAccess,bf as requestProjectConnector,_f as requestProjectSecret,Gj as requestTopUp,fM as requireKortixMember,Sc as resendAccountInvite,dl as resendPendingProjectInvite,yc as resetAccountBranding,Uq as resetClient,Mg as resetGatewayRoutingPolicy,di as resetPassword,Bq as resetPublicClient,$Y as resetSandboxUpdateStatus,xl as resolveApproval,PM as resolveComposerAgent,GM as resolveComposerModel,k2 as resolveConnectorStart,UM as resolveModelDefault,XL as resolvePublicShareUrl,OH as resolveScrapeResults,dP as resolveWorkingTurn,Bj as resolvedPlan,Jf as restartAppMachine,$r as restartProjectSession,sY as restartSandbox,iy as restoreAppVolume,kY as restoreBackup,iN as restoreDriveVersion,rd as restoreProjectSession,jl as retryAccountSecretResource,zA as retryFailed,Xp as retrySessionPrompt,xq as revealCredential,Yg as reviewItemTarget,Ww as reviewSegmentForStatus,$$ as reviewVerdictAllowed,I$ as reviewVerdictForStatus,Fl as revokeAccountSecretResourceGrant,G0 as revokeAccountSession,of as revokeAccountToken,km as revokeAssignment,E_ as revokeCaptureDevice,L_ as revokeCaptureEnrollmentToken,Jl as revokeConnection,Hg as revokeGatewayKey,af as revokeOAuthGrant,pl as revokePendingProjectInvite,cl as revokeProjectAccess,uf as revokeProjectCliToken,fY as revokeSandboxProjectAccess,Lm as revokeSandboxShare,_0 as revokeScimToken,Kp as revokeSessionPublicShare,bt as rewriteLocalhostUrl,Hf as rollbackApp,FI as rootRuntimeSession,Ll as rotateAccountSecretResource,Pm as rotateOAuthClientSecret,ws as runConnector,Vg as runGatewayPlayground,lD as runProjectProviderOAuthFlow,Pa as runtimeSessionsOf,pA as runtimeSupports,_v as sanitizePtyChunk,Qc as saveGitHubInstallation,MS as savedCopyEmptyRoot,Xf as scaleApp,eg as scheduleDowngrade,G_ as searchCapture,Gl as searchConnectorTools,Z_ as searchMyCapture,Bu as searchProjectFiles,iP as segmentTurn,uB as selectableProjectAgents,ci as sendMagicLink,R$ as sendReferralEmails,BJ as serverCompactionRevalidateAtMs,Rq as serviceAction,ZJ as sessionConnectionLabel,XJ as sessionListStatus,PE as sessionLogActivityText,RE as sessionLogAnsweredQuestionCall,wE as sessionLogBurstRunning,bE as sessionLogBurstSteps,SE as sessionLogBurstSummary,xE as sessionLogBurstWorkLabel,ZI as sessionLogCallStatus,FE as sessionLogFullTextAction,NE as sessionLogFullTextPlan,OE as sessionLogHarnessSwitches,YI as sessionLogOfV1Rows,kE as sessionLogOpenCall,eE as sessionLogPromptMessage,jE as sessionLogReferencedTexts,LE as sessionLogRestoreNotice,dS as sessionLogRetrying,AE as sessionLogShowGroupCall,IE as sessionLogThreadMetrics,fE as sessionLogTurnSegments,Ra as sessionLogTurns,BE as sessionLogWithFullTexts,qM as sessionModelCandidates,BM as sessionModelFallback,Fr as sessionModelPin,YL as sessionParentId,KM as sessionPickStands,nj as sessionPromptActions,hj as sessionStartKey,aj as setAccountAutomationsPaused,Nl as setAccountSecretResourceAccess,Dz as setActiveInstanceCookie,wx as setAdminBypass,UU as setAdminProviderDistribution,KU as setAdminProviderFallback,jd as setAgentScope,ag as setBillingPlan,bD as setBootstrapAuthToken,_D as setCachedAuthToken,X_ as setCaptureEnabled,N_ as setCapturePolicy,FD as setConnectionPolicies,au as setConnectorAuthorizationStrategy,wu as setConnectorCredential,iu as setConnectorCredentialMode,du as setConnectorName,uu as setConnectorPolicies,HD as setConnectorSecretBinding,cu as setConnectorSensitive,Xl as setDefaultConnection,yU as setEnterpriseDemo,_h as setEnv,Kg as setGatewayBudget,Eg as setGatewayRoutingPolicy,E2 as setGitHubAppFromExisting,M2 as setGitHubAppPat,nO as setImpersonationSession,f2 as setMaintenanceConfig,d0 as setMemberSuperAdmin,k0 as setMfaRequired,Od as setModelDefault,Il as setPersonalProjectSecret,Yr as setProjectModelAccess,kj as setProjectModelEnablement,Bc as setProjectOnboardingComplete,KO as setProjectOnboardingProfile,Tu as setProjectPolicies,vl as setProjectSecretStrategy,ld as setProjectSessionModel,cd as setProjectSessionScope,Op as setProjectSessionSharing,yd as setProjectTriggersActivation,jL as setSavedCopyStore,Up as setSessionArchived,A0 as setSessionOversight,$p as setSessionPinned,ql as setSessionProviderSecretPool,jp as setSessionWatch,d$ as setTelegramAllowedUsers,yJ as settleSessionConnection,RY as setupSSH,tu as shareConnection,VF as shareFolder,zN as shellActivityGroupLabel,CP as shellExitCode,xx as shouldAttachImpersonation,MV as shouldHideResponsePart,Kn as shouldShowToolPart,SV as shouldSuppressWorkingTurnBusy,lP as showGroupItems,uP as showTurnBusyIndicator,ai as signInWithPassword,ui as signInWithProvider,yi as signInWithSso,_i as signOut,gF as signOutDevice,ii as signUp,xz as skillDocumentPath,Sz as skillInputDir,sH as sortSessions,hE as splitSessionLogTurnWork,xP as splitTurnWork,MW as splitUserParts,qf as startApp,zf as startAppMachine,DD as startConnectionOAuth2Authorization,LD as startConnectionOAuth2DeviceAuthorization,c2 as startConnectorSetupLink,I2 as startGitHubAppManifest,us as startProjectProviderOAuth,mt as startProjectSession,Id as startProjectSessionOrThrow,g2 as startSessionWithToken,OK as startTask,Vn as stepLabel,Gf as stopApp,Yf as stopAppMachine,Ur as stopProjectSession,iY as stopSandbox,Zc as storeGitHubUserToken,Tb as stripAnsi,Mz as stripInstancePrefix,ue as stripTrailingSlashes,TE as subAgentCalls,r2 as submitAccessRequest,h2 as submitDemoRequest,i2 as submitOAuthConsent,Im as submitReviewItem,p2 as submitSecretSetupLink,rO as subscribeToImpersonation,xO as supabaseClient,su as syncConnectors,zj as syncSubscription,Kq as systemReload,_t as toDaemonPath,Lz as toInstanceAwarePath,EA as toInternalUrl,Mn as toSandboxAbsolutePath,Db as toToolView,Bh as toWorkspaceRelative,ao as toolCallBlock,Fk as toolCallError,jk as toolCallMetadata,Uk as toolCallRawOutput,$k as toolCallStatus,Vi as toolInfo,ce as toolKind,qT as toolViewModel,L$ as triggerControlsFrom,jY as triggerSandboxUpdate,mv as triggersRequest,MI as turnEndCause,jJ as turnEndNotice,dH as turnHasSteps,wV as turnIsConfirmedActive,kV as turnRendersQueued,t4 as turnRetryLabel,qK as unassignTicket,uy as unregisterDeviceToken,_y as unregisterWebPushSubscription,zF as unshareFolder,Nb as untimedAnchorOf,he as unwrapError,yf as updateAccountAuditWebhook,gc as updateAccountBranding,Rc as updateAccountMemberRole,pc as updateAccountName,Lj as updateAgentConfig,If as updateApp,jf as updateAppAccess,ny as updateAppVolume,iU as updateAuditWebhook,gp as updateChangeRequest,f$ as updateChannelBinding,Yl as updateConnectionCredential,Tg as updateEmailPolicy,Fc as updateExperimentalFeature,Uc as updateFeatureFlag,em as updateGroup,xh as updateKortixPty,fq as updateMilestone,fy as updateNotificationPreferences,bm as updateOAuthClient,gi as updatePassword,H0 as updatePatPolicy,o0 as updatePolicy,Pr as updateProject,al as updateProjectAccess,tq as updateProjectAgent,$d as updateProjectDefaultAgent,fl as updateProjectGroupGrant,Nc as updateProjectSandboxProvider,ed as updateProjectSession,md as updateProjectTrigger,pm as updateRole,dm as updateRolePermissions,Vm as updateRoom,Lu as updateSandboxTemplate,K0 as updateSessionPolicy,$s as updateSessionReminder,Bm as updateSessionReminders,MK as updateTask,BO as updateTemplateWarmPool,NK as updateTicket,BK as updateTicketStatus,fi as updateUserMetadata,mc as uploadAccountBrandingAsset,Uf as uploadAppArtifactArchive,_s as uploadConnectorAttachment,tN as uploadDriveFile,jn as uploadFile,oA as uploadNativeFile,Ir as uploadPromptAttachment,Ny as uploadSessionAttachment,kg as uploadSlackChannelFile,Cn as uploadTimeoutMsForBytes,Sq as upsertCredential,Tl as upsertProjectGitCredential,kl as upsertProjectSecret,E0 as upsertSsoProvider,Oc as validateProjectManifest,k$ as validateReferralCode,Tc as validateToken,b$ as verifyGatewayProvider,_M as verifyKortixToken,li as verifyOtp,O0 as verifySsoDomain,YJ as wakeEscalationAttemptSummary,zJ as wakeEscalationNote,HJ as wakeProgressFingerprint,Kt as wireIdClock,wn as wireIdClockAt,qt as wireIdClockDelta,WV as workedForLabel,MJ as workingExpiryAtMs,vV as workingTurnDrawsBusyRow,YN as writeActivityGroupLabel,Po as writeFile,na as wsDomain,EH as wsFavicon,IH as wsRootDomain};
|
|
96
|
+
`),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s++;let o=n.length,i=r.length;for(;o>s&&i>s&&n[o-1]===r[i-1];)o--,i--;let a=[];for(let l=0;l<s;l++)a.push({type:"unchanged",text:n[l]});for(let l=s;l<o;l++)a.push({type:"removed",text:n[l]});for(let l=s;l<i;l++)a.push({type:"added",text:r[l]});for(let l=o;l<n.length;l++)a.push({type:"unchanged",text:n[l]});return a}function NT(e){let t=Ms(e.input),n=t.map(([s,o])=>FT(s,o)),r=t.length&&n.every(Boolean)?n.flatMap(s=>s??[]):void 0;return{kind:"file-edit",path:ua(e),diff:r}}var IS=/^Found\s+(\d+)\s+match/i,BT=/^(\/[^:]+?):\s*/,CS=/Line\s+(\d+):/g;function KT(e){let t=e.trim(),n=t.match(IS),r=n?t.slice(n[0].length).trim():t;if(!r)return[];let s=[];for(let o of r.split(/\n\n+/)){let i=o.trim();if(!i)continue;let a=i.match(BT);if(!a)continue;let l=a[1],p=i.slice(a[0].length),d=[],g;for(CS.lastIndex=0;(g=CS.exec(p))!==null;)d.push({line:Number(g[1]),contentStart:g.index+g[0].length,headerStart:g.index});for(let m=0;m<d.length;m++){let f=m+1<d.length?d[m+1].headerStart:p.length,h=p.slice(d[m].contentStart,f).trim();s.push({path:l,line:d[m].line,content:h.endsWith(";")?h.slice(0,-1):h})}}return s}function qT(e){return e.trim().split(`
|
|
97
|
+
`).map(t=>t.trim()).filter(t=>t.startsWith("/")||t.startsWith("./")||t.startsWith("~")).map(t=>({path:t}))}function GT(e){let t=ne(e.input?.pattern,e.input?.query)??"";if(e.status==="error"||!e.output)return{kind:"search",pattern:t};let n=IS.test(e.output.trim())?KT(e.output):qT(e.output);return{kind:"search",pattern:t,matches:n.length>0?n.slice(0,200):void 0}}function WT(e){let t=ne(e.input?.description,e.input?.title,e.input?.prompt)??e.title,n=ne(e.input?.subagent_type,e.input?.agent);return{kind:"task",description:t,agent:n}}function la(e){let t=Yt(e)??{};return{content:ne(t.content)??"",status:ne(t.status)??"pending",priority:ne(t.priority)}}function HT(e){let t=e.input?.todos;if(Array.isArray(t))return{kind:"todo",items:t.map(la)};if(Array.isArray(e.outputParsed))return{kind:"todo",items:e.outputParsed.map(la)};let n=Yt(e.outputParsed);return n&&Array.isArray(n.todos)?{kind:"todo",items:n.todos.map(la)}:{kind:"todo",items:[]}}function VT(e){return{kind:"question",questions:(Array.isArray(e.input?.questions)?e.input.questions:[]).map(r=>{let s=Yt(r)??{},i=(Array.isArray(s.options)?s.options:[]).flatMap(a=>{let l=Yt(a),p=l&&ne(l.label);return p?[{label:p,description:l?ne(l.description):void 0}]:[]});return{question:ne(s.question)??"",header:ne(s.header),options:i}})}}function zT(e){let n=e.input&&Object.keys(e.input).length>0?RS(e.input):void 0,r;return e.outputParsed!==void 0?r=typeof e.outputParsed=="string"?Jn(e.outputParsed):RS(e.outputParsed):e.outputText!==void 0?r=Jn(e.outputText):r=e.error,{kind:"generic",label:e.title,inputPretty:n,outputPretty:r}}function YT(e){switch(ce(e.name)){case"web_search":return IT(e);case"bash":return jT(e);case"read":return LT(e);case"write":return $T(e);case"edit":return NT(e);case"grep":case"glob":return GT(e);case"task":return WT(e);case"todowrite":return HT(e);case"question":return VT(e);default:return zT(e)}}var JT=new Set(["AbortError","MessageAbortedError"]),QT=["operation was aborted","aborted by user","interrupted by user","cancelled by user","canceled by user","request was cancelled","request was canceled","aborterror"],XT=["unreachable","upstream","econnreset","econnrefused","socket hang up","network","fetch failed","timed out","timeout","gateway","502","503","504"];function ES(e){let t=e.toLowerCase();return XT.some(n=>t.includes(n))?!1:QT.some(n=>t.includes(n))}function ZT(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 Bs(e){if(typeof e=="string")return ES(e);if(!e||typeof e!="object")return!1;let t=e,n=t.name;if(typeof n=="string"&&JT.has(n))return!0;let r=ZT(t);return typeof r=="string"?ES(r):!1}var eI=["user","runtime-disposed","orphan-finalized","wake"],Dz=["orphan-finalized","wake"];function jz(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 eI.includes(n)?n:void 0}var Ks="kortix-active-instance",tI=["/dashboard","/agents","/p","/workspace","/settings","/browser","/desktop","/services","/sessions","/terminal","/files","/scheduled-tasks","/commands","/tools","/configuration","/changelog","/legacy","/credits-explained"];function nI(e){return tI.some(t=>e===t||e.startsWith(`${t}/`))}function Qn(e){let t=e.match(/^\/instances\/([^/]+)(?:\/(.*))?$/);if(!t)return null;let n=decodeURIComponent(t[1]),r=t[2]??"";return{instanceId:n,innerPath:r?`/${r}`:""}}function $z(e){let t=Qn(e);return!!t&&t.innerPath===""}function Uz(e){let t=Qn(e);return!t||!t.innerPath?e:t.innerPath}function rI(e,t){if(!e)return t;if(t.startsWith("/")||(t=`/${t}`),t.startsWith("/instances/")){let n=Qn(t);return n?`/instances/${encodeURIComponent(e)}${n.innerPath}`:t}return nI(t)?`/instances/${encodeURIComponent(e)}${t}`:t}function sI(e){return e?Qn(e)?.instanceId??null:null}function Fz(){return typeof window>"u"?null:sI(window.location.pathname)||oI()}function oI(){if(typeof document>"u")return null;let e=document.cookie.match(new RegExp(`(?:^|; )${Ks}=([^;]+)`));return e?decodeURIComponent(e[1]):null}function Nz(e){if(typeof document>"u")return;let t=n=>{document.cookie=n};if(typeof window<"u"&&window.location.pathname.startsWith("/projects")){t(`${Ks}=; Max-Age=0; Path=/; SameSite=Lax`);return}if(!e){t(`${Ks}=; Max-Age=0; Path=/; SameSite=Lax`);return}t(`${Ks}=${encodeURIComponent(e)}; Path=/; SameSite=Lax`)}function Bz(e,t){return t?rI(t,e):e}function Kz(e){let t=Qn(e);return t?t.innerPath||"/dashboard":e}function Xn(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e&&typeof e=="object")try{return JSON.stringify(e)}catch{return String(e)}return String(e??"")}function MS(e){let t=Xn(e).trim();if(!t)return null;let n=[t,t.replace(/^Failed to perform action:\s*/i,"").trim()],r=t.indexOf("{");r>=0&&n.push(t.slice(r));for(let s of n)if(s)try{return JSON.parse(s)}catch{}return null}var Gz=MS;function pa(e){let t=MS(e);if(!t||typeof t!="object")return null;let n=t;return n.name==="ConfigInvalidError"?n:null}var Wz=pa;function iI(e){return pa(e)!==null}var Hz=iI,aI=[/sandbox not ready/i,/sandbox is not (?:ready|running)/i,/opencode (?:session )?(?:is )?not ready/i,/\bsandbox_not_ready\b/,/\bsandbox_lifecycle_unavailable\b/],Vz=["runtime_not_ready","sandbox runtime not ready","opencode not ready"],cI=/\bruntime_not_ready\b|sandbox runtime not ready|opencode not ready/i;function lI(e){return cI.test(Xn(e))}function Zn(e){let t=Xn(e);return t?lI(t)||aI.some(n=>n.test(t)):!1}var uI=/server url not ready|sandbox is still loading/i;function zz(e){return uI.test(Xn(e))||Zn(e)}var qs=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 pI(e){let t=pa(e);if(t){let s=(t.data?.path??"OpenCode config").replace(/^\/workspace\//,""),o=t.data?.issues?.[0]?.message,i=t.data?.issues?.[0]?.path?.join("."),a=i?.startsWith("permission")?"Remove the invalid permission frontmatter entry or replace it with valid OpenCode permission config.":"Fix the invalid config entry, then restart this session.";return{title:"OpenCode config is invalid",message:`${s} is preventing OpenCode from loading. ${a}`,detail:o?`${i?`${i}: `:""}${o}`:void 0}}let n=Xn(e);return Zn(n)?{title:"Session is waking up",message:"This session slept to save compute. Your conversation is safe \u2014 sending a message wakes it back up."}:{title:"The session runtime failed to load",message:n||"The sandbox is running, but its runtime returned an error."}}var Yz=pI;function OS(e){if(!e.external_id){if(e.base_url)return e.base_url;throw new Error(`Cannot build sandbox URL: missing external_id for ${e.provider} sandbox "${e.sandbox_id}"`)}return`${nt()}/p/${e.external_id}/${tt.KORTIX_MASTER}`}function Zz(e,t){return e.external_id?`${nt()}/p/${e.external_id}/${t}`:null}async function sY(){let e=await c.get("/setup/sandbox-providers");if(e.error)throw e.error;return e.data}async function dI(e){let t=await mn();if(t)return{sandbox:t.sandbox,created:!1};let r=(await Rt())[0];if(!r)throw new Error("Create a project before starting a sandbox");let s=await jt(r.project_id,{...e?.provider?{provider:e.provider}:{}}),o=(await mt(r.project_id,s.session_id))?.sandbox??null;return{sandbox:Vr(r,s,o),created:!0}}async function oY(){return(await mn().catch(()=>null))?.sandbox??null}async function iY(e){return{sandbox:(await dI(e)).sandbox}}async function aY(e){let t=gn(e);if(!t)return null;try{let n=await Ho(t);return n?Vr(await Ct(n.project_id),n,null):(await mn(t))?.sandbox??null}catch{return null}}async function cY(e,t){throw await zr(e)?new Error("Renaming project-session sandboxes is not exposed by the current API"):new Error("Project session sandbox not found")}async function lY(e){let t=gn(e);return(await Wo().catch(()=>[])).map(r=>r.sandbox).filter(r=>!t||r.sandbox_id===t||r.external_id===t)}async function uY(){return null}async function pY(e){if(!e)throw new Error("No sandbox selected for workload restart");let t=await zr(e);if(!t)throw new Error("Project session sandbox not found");await Ur(t.projectId,t.sessionId)}async function dY(e){if(!e)throw new Error("No sandbox selected to stop");let t=await zr(e);if(!t)throw new Error("Project session sandbox not found");await Fr(t.projectId,t.sessionId)}async function gY(e){throw new Error("Cancellation is not exposed for project-session sandboxes")}async function mY(e){throw new Error("Reactivation is not exposed for project-session sandboxes")}async function da(e,t,n){let r=OS(e),s=await U(`${pe(r)}${t}`,{signal:AbortSignal.timeout(8e3),headers:{"Content-Type":"application/json"},...n});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(o||`Request failed (${s.status})`)}return await s.json()}async function bY(e,t){return da(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"GET"})}async function SY(e,t,n,r="member"){await da(e,`/kortix/projects/${encodeURIComponent(t)}/members`,{method:"POST",body:JSON.stringify({user_id:n,role:r})})}async function xY(e,t,n){await da(e,`/kortix/projects/${encodeURIComponent(t)}/members/${encodeURIComponent(n)}`,{method:"DELETE"})}var ga="Use the account invite functions (acceptAccountInvite, declineAccountInvite).";async function kY(e){throw N("getInvite",ga)}async function vY(e){throw N("acceptInvite",ga)}async function AY(e){throw N("declineInvite",ga)}async function CY(e){throw new Error("Backups are not exposed for project-session sandboxes")}async function TY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function IY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function EY(e,t){throw new Error("Backups are not exposed for project-session sandboxes")}async function OY(e){throw new Error("SSH setup is not exposed for project-session sandboxes")}async function DY(e){throw new Error("SSH connection details are not exposed for project-session sandboxes")}var gI=["pulling","patching","stopping","removing","recreating","restarting","verifying","starting","health_check"];function UY(e){return gI.includes(e)}async function FY(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 NY(e){let t=e?`?channel=${e}`:"",r=await(await Oe(`${nt()}/platform/sandbox/version/latest${t}`,{headers:{Accept:"application/json"}},{},"Version check failed")).json();try{let s=await mI(e||"stable");r.changelog=s.find(o=>o.version===r.version)??s[0]??null}catch{r.changelog=null}return r}async function mI(e){let t=e?`?channel=${e}`:"";return(await(await Oe(`${nt()}/platform/sandbox/version/changelog${t}`,{headers:{Accept:"application/json"}},{},"Changelog fetch failed")).json()).changelog}async function BY(){return(await Oe(`${nt()}/platform/sandbox/version/all`,{headers:{Accept:"application/json"}},{},"All versions fetch failed")).json()}async function KY(e,t){throw new Error("Sandbox image updates are managed by project-session provisioning")}async function qY(e){}async function GY(e){}async function VY(e){return{serverTypes:[],location:e||"hel1"}}async function zY(e){throw new Error("Retired instance provisioning is unavailable. Create a project session on platinum (or the legacy daytona fallback).")}async function YY(e){throw N("deleteInstance")}async function JY(e,t){}async function QY(){throw N("claimComputer")}async function XY(e){return null}function ZY(e,t){throw N("getSandboxProvisionStreamUrl")}var Gs=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="HostBoundaryError"}status;body};function DS(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 jS(e){let t=await e.text().catch(()=>"");if(!t)return null;try{return JSON.parse(t)}catch{return t}}function LS(e,t){if(t&&typeof t=="object"){let n=t;for(let r of["error_description","error","message"])if(typeof n[r]=="string"&&n[r])return n[r]}return typeof t=="string"&&t?t:e.statusText||`HTTP ${e.status}`}async function X(e,t,n){let r=n?.body!==void 0,s=await fetch(`${Ne(t.backendUrl)}${e}`,{method:n?.method??"GET",headers:DS(t,r),...r?{body:JSON.stringify(n.body)}:{},...t.signal?{signal:t.signal}:{},...t.cache?{cache:t.cache}:{},...t.next?{next:t.next}:{}}),o=await jS(s);if(!s.ok)throw new Gs(LS(s,o),s.status,o);return o}function fI(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 s2(e,t){return X(`/marketplace/items${fI(t)}`,e)}function o2(e){return X("/marketplace/marketplaces",e)}function i2(e,t){return X(`/marketplace/items/${encodeURIComponent(e)}`,t)}function a2(e,t,n){return X(`/marketplace/items/${encodeURIComponent(e)}/file?path=${encodeURIComponent(t)}`,n)}function c2(e,t){return X("/access/check-email",t,{method:"POST",body:{email:e}})}function l2(e,t){return X("/access/request-access",t,{method:"POST",body:e})}function u2(e){return X("/auth/logout",e,{method:"POST",body:{}})}function p2(e,t){return X(`/oauth/authorize/consent/${encodeURIComponent(e)}`,t)}function d2(e,t){return X("/oauth/authorize/consent",t,{method:"POST",body:{request_id:e.requestId,approved:e.approved}})}function g2(e,t){return X(`/setup-links/connectors/${encodeURIComponent(e)}`,t)}function m2(e,t){return X(`/setup-links/connectors/${encodeURIComponent(e)}/start`,t,{method:"POST",body:{}})}function f2(e,t,n={}){return X(`/setup-links/connectors/${encodeURIComponent(e)}/finalize`,t,{method:"POST",body:n.connectionId?{connection_id:n.connectionId}:{}})}function y2(e,t){return X(`/setup-links/secret/${encodeURIComponent(e)}`,t)}function h2(e,t,n,r){return X(`/setup-links/secret/${encodeURIComponent(e)}`,n,{method:"POST",body:{values:t,...r?.only_requester?{only_requester:!0}:{}}})}function _2(e,t){return X(`/p/public-share/${encodeURIComponent(e)}`,t)}function b2(e,t,n){return X(`/projects/${encodeURIComponent(e)}/sessions/${encodeURIComponent(t)}/start`,n,{method:"POST",body:{}})}function S2(e){return X("/system/maintenance",e)}function x2(e,t){return X("/system/maintenance",t,{method:"PUT",body:e})}function P2(e){return X("/user-roles",e)}function w2(e,t){return X("/system/demo-request",t,{method:"POST",body:e})}async function k2(e,t,n){let r=await fetch(`${Ne(n.backendUrl)}/accounts/${encodeURIComponent(e)}/audit/export?${$t(t)}`,{headers:DS(n,!1),...n.signal?{signal:n.signal}:{}});if(!r.ok){let s=await jS(r);throw new Gs(LS(r,s),r.status,s)}return{blob:await r.blob(),filename:r.headers.get("content-disposition")?.match(/filename="([^"]+)"/)?.[1]??null,capped:r.headers.get("x-audit-capped")==="true",rowCount:r.headers.get("x-audit-row-count"),complete:r.headers.get("x-audit-complete")!=="false",nextCursor:r.headers.get("x-audit-next-cursor")||null}}async function v2(e,t){throw N("openStressTestStream")}function A2(e,t){throw N("buildPublicTemplateUrl")}async function R2(e,t,n){throw N("getPublicTemplate")}var yI="kortix:connect-link:";function ma(e){let t=2166136261,n=16777619^e.length;for(let r=0;r<e.length;r+=1){let s=e.charCodeAt(r);t=Math.imul(t^s,16777619)>>>0,n=Math.imul(n^s,1540483477)>>>0}return`${yI}${t.toString(36)}${n.toString(36)}`}function T2(e,{storage:t}={}){let n=new Map,r=new Map,s=i=>{if(t)try{let a=t.getItem(ma(i));if(!a)return;let l=JSON.parse(a);if(Date.parse(l.expires_at)<=Date.now()){t.removeItem(ma(i));return}return l}catch{return}},o=(i,a)=>{if(t)try{t.setItem(ma(i),JSON.stringify(a))}catch{}};return{peek(i){let a=r.get(i);if(a)return a;let l=s(i);return l&&r.set(i,l),l},load(i){let a=n.get(i);if(a)return a;let l=e(i).then(p=>(r.set(i,p),o(i,p),p),p=>{throw n.delete(i),p});return n.set(i,l),l}}}var $S="Could not start the connect flow.";async function I2(e){let t;try{t=await e.start()}catch(r){return{kind:"error",message:r instanceof Error?r.message:$S}}if(t.connect_url)return{kind:"popup",url:t.connect_url};if(!t.connected)return{kind:"error",message:$S};let n=null;try{n=(await e.finalize()).connected_as??null}catch{}return{kind:"connected",alreadyConnected:t.already_connected===!0,connectedAs:n}}var hI=3e3,_I=5e3,bI=5*6e4;function E2(e,t){let n=e===0?hI:_I;return t+n>bI?null:n}function M2(e){let t=e.project_name?.trim();return{app:e.name?.trim()||e.app?.trim()||e.slug,project:t&&t!=="this project"?t:null}}async function j2(){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 L2(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 $2(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 U2(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 F2(){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 B2="1";var SI="kortix.query-cache";function FS(e){return!!e&&typeof e.then=="function"}function US(e){return FS(e)?e:Promise.resolve()}function K2(e){if(e[0]!=="kx")return!1;let t=e[1];if(t==="accounts")return e.length===3&&typeof e[2]=="string"&&e[2]!=="anonymous";if(t==="projects")return e.length===3;if(t!=="project"||typeof e[2]!="string")return!1;let n=e[3];if(e.length===4)return n==="summary"||n==="detail";if(n!=="sessions")return!1;if(e.length===6)return e[4]==="list-paged";if(e.length===7&&e[4]==="list-paged"){let r=e[6];return typeof r=="object"&&r!==null&&!r.q}return e.length===7&&e[4]==="list-children"?e[6]==="":e.length===5&&e[4]!=="list"&&e[4]!=="list-paged"}function q2(e){let{storage:t,userId:n,shouldPersist:r,version:s="1",maxAgeMs:o=6048e5,maxBytes:i=1e6,throttleMs:a=1e3,namespace:l=SI,now:p=()=>Date.now()}=e,d=`${l}:${n}`,g=null,m=!1,f=null,h=Promise.resolve(),S=()=>{try{return US(t.removeItem(d)).catch(()=>{})}catch{return Promise.resolve()}},v=(x,k)=>{if(!k)return 0;let C;try{C=JSON.parse(k)}catch{return S(),0}if(!C||C.v!==s||C.user!==n||!Array.isArray(C.queries)||p()-C.at>o)return S(),0;let j=0;for(let R of C.queries){if(!R||!Array.isArray(R.k)||R.d===void 0||typeof R.t!="number"||p()-R.t>o||!r(R.k))continue;let L=x.getQueryState(R.k);L&&L.data!==void 0&&L.dataUpdatedAt>=R.t||(x.setQueryData(R.k,R.d,{updatedAt:R.t}),x.invalidateQueries?.({queryKey:R.k,exact:!0,refetchType:"none"}),j+=1)}return j},T=x=>x.getQueryCache().getAll().filter(k=>k.state.data!==void 0&&r(k.queryKey)).map(k=>({k:k.queryKey,d:k.state.data,t:k.state.dataUpdatedAt})).sort((k,C)=>C.t-k.t),_=(x,k)=>{let C=[],j=0;for(let R of x){let L=JSON.stringify(R).length+1;j+L>k||(C.push(R),j+=L)}return C},b=async x=>{let k=_(T(x),i);for(;;){let C={v:s,user:n,at:p(),queries:k};try{await US(t.setItem(d,JSON.stringify(C)));return}catch{if(k.length===0)return;k=k.slice(0,Math.floor(k.length/2))}}},O=()=>{f!==null&&(clearTimeout(f),f=null)},y=()=>{O();let x=g;return!x||!m||(m=!1,h=h.then(()=>b(x)).catch(()=>{})),h},w=()=>{m=!0,f===null&&(f=setTimeout(()=>{f=null,y()},a))};return{storageKey:d,restore(x){let k;try{k=t.getItem(d)}catch{return 0}return FS(k)?k.then(C=>v(x,C)).catch(()=>0):v(x,k)},persist(x){g=x,m=!0;let k=x.getQueryCache().subscribe(C=>{C.type!=="updated"&&C.type!=="removed"&&C.type!=="added"||r(C.query.queryKey)&&w()});return()=>{k(),g===x&&(g=null,O())}},flush(){return y()},async clear(){O(),g=null,m=!1,await h,await S()}}}function G2(){let e;try{e=globalThis.localStorage}catch{e=void 0}if(!e)return null;let t=e;return{getItem:n=>{try{return t.getItem(n)}catch{return null}},setItem:(n,r)=>t.setItem(n,r),removeItem:n=>{try{t.removeItem(n)}catch{}}}}var xI="/kortix/part/";function PI(e){return typeof e=="string"&&e.startsWith(xI)}async function z2(e){if(!PI(e))throw new Error(`not an attachment part reference: ${e}`);let t=Ge();if(!t)throw new Error("runtime url not bound");let n=await U(`${t}${e}`);if(!n.ok)throw new Error(`attachment part fetch failed: ${n.status}`);return n.blob()}function NS(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 wI(e,t){try{let n=new URL(e),r=n.pathname;if(!(/^\/v1\/p\/[^/]+\/\d+(?:\/|$)/.test(r)||/^\/proxy\/\d+(?:\/|$)/.test(r)))return!1;let o=new Set;if(t)try{o.add(new URL(t).origin)}catch{}return typeof window<"u"&&o.add(window.location.origin),o.has(n.origin)}catch{return!1}}function BS(e,t){return wI(e,t)?(t?NS(t):null)??NS(e):null}function Ws(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 J2(e,t){try{let n=new URL(e);return n.searchParams.set("token",t),n.toString()}catch{return e}}var kI=/^p\d{1,5}-[a-z0-9-]+\.localhost$/;function vI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function AI(e,t){if(!t.includes("{port}")||!t.includes("{sandbox}"))return!1;let n=t.indexOf("://");if(n<=0)return!1;let r=t.slice(0,n).toLowerCase();if(r!=="https"&&r!=="http")return!1;let s=(t.slice(n+3).split("/")[0]??"").toLowerCase(),o=`${r}://${s}`.split("{port}").map(i=>i.split("{sandbox}").map(vI).join("[a-z0-9-]+")).join("\\d{1,5}");return new RegExp(`^${o}$`).test(e)}function RI(e){try{let t=new URL(e);return t.hostname==="localhost"||t.hostname==="127.0.0.1"?t:null}catch{return null}}function KS(e){return e.port?e.port:e.protocol==="https:"?"443":"80"}function CI(e,t){let n;try{n=new URL(e)}catch{return!1}return n.protocol!=="https:"&&n.protocol!=="http:"?!1:kI.test(n.hostname)?t.backendUrls.some(r=>{let s=RI(r);return s!==null&&KS(s)===KS(n)}):t.templates.some(r=>AI(n.origin,r))}async function qS(e,t={}){if(!Ws(e))return!1;let n=I().backendUrl;n&&await ft(n).catch(()=>null);let r=[n,t.serverUrl].filter(s=>typeof s=="string"&&s.length>0);return CI(e,{templates:Jy(),backendUrls:r})}async function TI(e,t={}){let n=BS(e,t.serverUrl||I().backendUrl||void 0);if(!n)return!1;let r=await sn();if(!r)return!1;try{return(await fetch(n,{method:"POST",credentials:"include",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}})).ok}catch{return!1}}async function aJ(e,t={}){if(Ws(e)){if(!await qS(e,t)||!await sn())return e;let r=await c.post("/p/ticket",{preview_url:e}),s=r.data;if(!r.success||!s||typeof s.ticket!="string"||!s.ticket)throw new Error("Preview authorization failed");let o=new URL(e);return o.searchParams.delete("token"),o.searchParams.set("preview_ticket",s.ticket),o.toString()}return await TI(e,t),e}var lJ=3e3;function II(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 uJ(e,t){if(!e||t?.signal?.aborted)return"unknown";let n=new AbortController,r=()=>n.abort();t?.signal?.addEventListener("abort",r);let s=setTimeout(r,t?.timeoutMs??3e3);try{let o=await fetch(e,{method:"HEAD",credentials:"include",cache:"no-store",signal:n.signal});return II(o.status)}catch{return"unknown"}finally{clearTimeout(s),t?.signal?.removeEventListener("abort",r)}}function EI(e){let t=e;for(;t.endsWith("/");)t=t.slice(0,-1);return t}function gJ(e,t){throw N("buildPresentationTemplatePdfUrl")}function mJ(e,t){throw N("buildPresentationTemplateImageUrl")}function MI(e,t){return`${EI(e)}/presentation/convert-to-${t}`}async function fJ(e,t,n,r){let s=MI(t,e),o=r?.pollIntervalMs??2500,i=r?.timeoutMs??4*6e4,a=Date.now(),l=!1;for(;;){let p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({presentation_path:n,download:!0}),...r?.signal?{signal:r.signal}:{}}),d=p.headers.get("content-type")||"";if(p.ok&&(d.includes("pdf")||d.includes("presentation")||d.includes("octet-stream"))){let h=await p.blob();if(h.size===0)throw new Error("Downloaded file is empty");return h}if(p.status===202){if(l||(l=!0,r?.onGenerating?.()),Date.now()-a>i)throw new Error(`Timed out waiting for the ${e.toUpperCase()} to generate`);await new Promise((h,S)=>{let v=setTimeout(h,o);r?.signal?.addEventListener("abort",()=>{clearTimeout(v),S(r.signal?.reason??new DOMException("Aborted","AbortError"))},{once:!0})});continue}let m=await p.text().catch(()=>""),f=p.statusText;try{let h=JSON.parse(m);f=String(h.error||h.detail||h.message||f)}catch{m&&(f=m)}throw new Error(`Failed to download ${e.toUpperCase()}: ${f} (HTTP ${p.status})`)}}function _J(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 bJ(e){return e==="unreachable"}function SJ(e){return!e||e.status===0?"unknown":e.ok&&n_(e.health)?"live":e.hop==="control_plane"?"waking":e.ok||e.health?.status==="starting"?"connecting":"unreachable"}var OI=1e4,xJ={connection:"unknown",faultSinceMs:null};function PJ(e,t,n,r=OI){if(t==="unknown")return e;if(t==="live"||t==="waking")return{connection:t,faultSinceMs:null};let s=e.faultSinceMs??n;return n-s>=r?{connection:t,faultSinceMs:s}:{connection:e.connection==="unknown"?"connecting":e.connection,faultSinceMs:s}}function GS({optimistic:e,abort:t,inbox:n,server:r,stream:s,activity:o,nowMs:i}){let a=!!e&&i-e.atMs<fa,l=!!t&&i-t.atMs<_a;return{receiptLive:a,receiptTurnId:e?e.turnId===void 0?e.messageId:e.turnId:null,serverFloor:a?e?.acceptedAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,streamFloor:a?e?.atMs:Number.NEGATIVE_INFINITY,abortLive:l,abortFloor:l?t?.settledAtMs??Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,serverFresh:!!r&&i-r.atMs<=ya,streamFresh:!!s&&i-s.atMs<=er,inboxFresh:!!n&&i-n.atMs<=ha,activityFresh:!!o&&i-o.atMs<=er}}function Jt(e){if(!e)return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function ba(e,t,n){if(!t)return!1;let r=Jt(e.started_at);if(r===null||r>=t.atMs)return!1;let s=n?.lastEnded,o=Jt(s?.ended_at);return!(s&&o!==null&&Math.abs(o-t.atMs)<=1e3&&s.turn_token!==e.turn_token)}function DI(e,t,n,r){let{activity:s,server:o}=e,{serverFresh:i,abortFloor:a,activityFresh:l}=t;return l&&(!n||s.atMs>n.atMs)&&s.atMs>=a?{state:"working",source:"stream",turnId:i?o.turns.find(d=>d.state==="active"&&!ba(d,n,o))?.message_id??null:null,since:s.atMs,serverOpenTurnToken:r}:null}function jI(e,t,n,r){let{server:s,stream:o}=e,{serverFresh:i,abortFloor:a}=t,l=i?s.turns.filter(g=>!ba(g,n,s)):[],p=l.find(g=>g.state==="active")??l[0],d=!!o&&!(o.type==="idle"&&o.origin==="local");return p&&s.atMs>=a&&(!d||s.atMs>=o.atMs)?{result:{...p.state==="delivering"?{pendingDelivery:!0}:{},state:"working",source:"server",turnId:p.message_id,since:Jt(p.started_at)??s.atMs,serverOpenTurnToken:r},openTurn:p}:{result:null,openTurn:p}}function LI(e,t,n){let{inbox:r,server:s,stream:o}=e,{inboxFresh:i,abortFloor:a,streamFresh:l,serverFresh:p,receiptLive:d,receiptTurnId:g,abortLive:m}=t;if(i&&r.pending>0&&r.atMs>=a)return{...l&&o.type!=="idle"&&(!p||o.atMs>s.atMs)&&o.atMs>=a?{}:{pendingDelivery:!0},state:"working",source:"server",turnId:d?g:null,since:r.atMs,serverOpenTurnToken:n};let f=r?.drainedAtMs;return i&&r.pending===0&&f!=null&&!m&&!(p&&s.atMs>=f)?{pendingDelivery:!0,state:"working",source:"server",turnId:null,since:f,serverOpenTurnToken:n}:null}function $I(e,t,n,r){let{server:s,stream:o,optimistic:i,nowMs:a}=e,{serverFresh:l,serverFloor:p,streamFresh:d,streamFloor:g,abortFloor:m,receiptLive:f,receiptTurnId:h}=t,S=l&&!n&&s.atMs>=p,v=d&&o.atMs>=g&&(o.type==="idle"||o.atMs>=m);if(S&&(!o||s.atMs>=o.atMs))return{state:"idle",source:"server",turnId:null,since:Jt(s.lastEnded?.ended_at)??s.atMs,serverOpenTurnToken:r};if(v)return{state:o.type==="idle"?"idle":"working",source:"stream",turnId:null,since:o.atMs,serverOpenTurnToken:r};if(f)return{pendingDelivery:!0,state:"working",source:"optimistic",turnId:h,since:i.atMs,serverOpenTurnToken:r};let T=s&&o?s.atMs>=o.atMs?{source:"server",atMs:s.atMs}:{source:"stream",atMs:o.atMs}:s?{source:"server",atMs:s.atMs}:o?{source:"stream",atMs:o.atMs}:{source:"server",atMs:a};return{state:"idle",source:T.source,turnId:null,since:T.atMs,serverOpenTurnToken:r}}function WS(e){let t=GS(e),{server:n,stream:r}=e,s=r&&r.type==="idle"&&r.origin!=="local"?r:null,o=n?.turns[0]?.turn_token??null,i=DI(e,t,s,o);if(i)return i;let{result:a,openTurn:l}=jI(e,t,s,o);return a??LI(e,t,o)??$I(e,t,l,o)}var fa=6e4,ya=45e3,er=45e3,ha=1e4,OJ=3e3,_a=15e3;function DJ(e,t){return t?t.serverAtMs!=null&&e.serverAtMs!=null?e.serverAtMs>=t.serverAtMs:e.atMs>=t.atMs:!0}function jJ(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 $J(e){return WS(e)}function UJ(e){let{optimistic:t,abort:n,inbox:r,server:s,stream:o,activity:i,nowMs:a}=e,l=[null,t?t.atMs+fa:null,n?n.atMs+_a:null,r?r.atMs+ha:null,s?s.atMs+ya:null,o?o.atMs+er:null,i?i.atMs+er:null],p=null;for(let d of l)d===null||d<=a||(p===null||d<p)&&(p=d);return p}function UI(e,t){if(!e||!t)return null;let n=e.recent_failures?.find(o=>o.message_id===t),r=e.last_ended,s=n?.error??(r?.message_id===t&&r.end_reason==="failed"?r.error:void 0);return!s?.message||Bs({name:s.name??void 0,message:s.message})?null:s}var FI="SandboxMemoryGuard";function KJ(e,t,n){if(!e||!t||n.hasError&&!n.isAbort)return null;let r=UI(e,t);if(r?.message){if(r.name!==FI)return{kind:"cause",name:r.name,message:r.message};let a=r.message.match(/(\d{1,3})%/)?.[1],l=r.message.split(":")[0]?.trim()||null;return{kind:"sandbox-memory",usedPct:a?Number(a):null,detail:l}}let s=e.recent_failures?.find(a=>a.message_id===t);if(!s)return null;let o=s.ended_at?Date.parse(s.ended_at):Number.NaN;return Number.isFinite(o)&&typeof e.atMs=="number"&&e.atMs-o<2500?null:{kind:"unexplained"}}var GJ=6e4;function WJ(e){return e.serverCompactingAtMs!==null?!0:e.optimisticAtMs===null?!1:e.nowMs-e.optimisticAtMs<6e4}function HJ(e){if(e.serverCompactingAtMs!==null||e.optimisticAtMs===null)return null;let t=e.optimisticAtMs+6e4;return t>e.nowMs?t:null}var NI=9e4;function VJ(e){return e.serverCompactingAtMs===null?null:e.serverCompactingAtMs+NI}var YJ=75e3,JJ=2,QJ=2e4;function HS(){return{status:"idle",dispatch:"none",fingerprint:null,lastProgressAtMs:null,lastDispatchAtMs:null,attempts:[],msSinceProgress:0,settled:!1}}function XJ(e){return e.filter(t=>t!=null).join("|")}function BI(e,t){return e.length===0?"retry-start":e.filter(r=>r.step==="restart").length<t?"restart":null}function ZJ(e,t,n={}){let r=n.noProgressMs??75e3,s=n.maxRestarts??2,o=n.cooldownMs??2e4;if(t.runtimeReachable)return{...HS(),settled:!0};if(!t.waking)return{...e,dispatch:"none",fingerprint:null,lastProgressAtMs:null,msSinceProgress:0};if(e.settled)return{...HS(),settled:!0};let i=e.lastProgressAtMs,a=i===null,l=t.progress!==e.fingerprint,p=i===null||l?t.nowMs:i,d=Math.max(0,t.nowMs-p),g={...e,dispatch:"none",fingerprint:t.progress,lastProgressAtMs:p,msSinceProgress:d,status:e.attempts.length>0?"escalating":"waking"};if(e.status==="exhausted")return{...g,status:"exhausted"};let m=!a&&!l&&d>=r;if(!t.serverGaveUp&&!m||e.lastDispatchAtMs!==null&&t.nowMs-e.lastDispatchAtMs<o)return g;let f=BI(e.attempts,s);return f?{...g,status:"escalating",dispatch:f,attempts:[...e.attempts,{step:f,atMs:t.nowMs}],lastDispatchAtMs:t.nowMs,lastProgressAtMs:t.nowMs,msSinceProgress:0}:{...g,status:"exhausted"}}var KI={"retry-start":"retrying",restart:"restarting"};function eQ(e){if(e.status!=="escalating")return null;let t=e.attempts[e.attempts.length-1];return t?`Still waking \u2014 ${KI[t.step]} the runtime (attempt ${e.attempts.length+1})`:null}function qI(e){return e===1?"once":e===2?"twice":`${e} times`}function tQ(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 ${qI(t)}`),`Tried: ${r.join(", then ")}.`}var rQ={"needs-you":{label:"Needs you",tone:"actionable",description:"Waiting for your review"},starting:{label:"Starting",tone:"progress",description:"Its computer is starting"},running:{label:"Running",tone:"live",description:"Its computer is up"},done:{label:"Done",tone:"muted",description:"Finished"},stopped:{label:"Stopped",tone:"muted",description:"Asleep. Opening it wakes its computer"},failed:{label:"Failed",tone:"danger",description:"Its computer didn't start"},legacy:{label:"Legacy",tone:"muted",description:"Imported. Open it to restore"}};function GI(e){return!!(e.metadata??{}).legacy_migration}function sQ(e,t=0){if(t>0)return"needs-you";switch(e.status){case"queued":case"branching":case"provisioning":return"starting";case"running":return e.working?.state==="idle"?"done":"running";case"completed":case"stopped":return GI(e)?"legacy":e.status==="completed"?"done":"stopped";case"failed":return"failed";default:return"stopped"}}function oQ(e){switch(e){case"waking":return{label:"Waking computer",tone:"progress"};case"connecting":return{label:"Connecting",tone:"progress"};case"unreachable":return{label:"Can't reach computer",tone:"danger"};default:return null}}var iQ={unreachable:"Lost contact with this session's computer. Messages you send are queued until it reconnects.",unreachableMidTurn:"Lost contact with this session's computer while a turn is still open. Messages you send stay queued until it answers.",stalled:"Waking this session's computer is taking longer than usual. Messages you send are queued.",starting:"Starting this session's computer. Your message sends automatically.",idle:"This session's computer is asleep. Your next message wakes it up and is delivered.",waking:"Waking this session's computer. Messages you send are queued and go out automatically."};function aQ(e){return e===null?"Waiting to retry":e>0?`Retrying in ${e}s`:"Retrying now"}function Sa(e){return e.runtime_sessions??e.opencode_sessions??[]}function WI(e){let t=Sa(e),n=e.runtime_session_id??e.opencode_session_id;return n?t.find(r=>r.id===n)??null:t.find(r=>!r.parent_id)??null}function lQ(e){let t=WI(e);return t?Sa(e).filter(n=>(n.parent_id===t.id||!n.parent_id&&n.fork_source_id)&&!n.archived_at).sort((n,r)=>(r.updated_at??0)-(n.updated_at??0)||n.id.localeCompare(r.id)):[]}function uQ(e,t){if(!t)return null;let n=e.find(r=>r.session_id===t||(r.runtime_session_id??r.opencode_session_id)===t);return n||(e.find(r=>Sa(r).some(s=>s.id===t))??null)}var HI=new Set;function VI(e){for(let t of[...HI])try{t(e)}catch{}}var QS={schema:ue,v:1,session_id:"",title:null,created_at:"",restore_grade:"native",harness:{current:"",history:[]},selection:{agent:null,model:null},todos:[],pending:{questions:[],permissions:[]}};var XS=e=>Object.values(e.ext??{}).find(t=>t.version===Te),ZS=e=>!!e&&XS(e)!==void 0,ex=e=>{let t=XS(e);return t?t.native_id??null:e.thread_id};function tx(e){let t=e&&Object.values(e.threads).find(r=>r.parent_thread_id===null);if(!e||!t)return null;let n=(e.messages[t.thread_id]?.length??0)>0;return{runtimeSessionId:ex(t),hasMessages:n,empty:!n&&e.older[t.thread_id]===!1}}var VS=new WeakMap;function nx(e,t){let n=ex(e),r=VS.get(t);if(r&&r.native===n)return r.rows;let{rows:s}=is({...QS,threads:[{...e,messages:[t]}]}),o=s.map(i=>({info:i.info,parts:i.parts}));return VS.set(t,{native:n,rows:o}),o}var xa=e=>e.info.time?.created;var zI=(e,t)=>(xa(e)??-1/0)-(xa(t)??-1/0)||(e.info.id<t.info.id?-1:e.info.id>t.info.id?1:0);var zS=new WeakMap,YS=new WeakMap,rx=e=>typeof e=="object"&&e!==null,YI=e=>e!==void 0&&Number.isFinite(e)&&Math.abs(e)<=864e13?new Date(e).toISOString():null,JI=e=>e.info.role==="user"&&e.parts.some(t=>rx(t)&&t.type==="compaction"),QI=(e,t)=>{let n=e.info;return n.role==="assistant"&&n.summary===!0&&n.parentID===t.info.id},JS=new WeakMap;function XI(e,t,n){let r=t.info,s=`${e}|${String(r.id)}|${String(r.time?.created)}`,o=!1,i=n.blocks.map((a,l)=>{let p=t.parts[l];if(!rx(p)||a.type==="compaction")return a;let d=`${s}|${l}|${a.id}`,g=JS.get(p);return g&&g.key===d?(o=!0,g.block):(JS.set(p,{key:d,block:a}),a)});return o?{...n,blocks:i}:n}function ZI(e){let t=new Map,n=new Set;for(let r of e){if(!JI(r))continue;let s=e.find(o=>!n.has(o)&&QI(o,r));s&&(t.set(r,s),n.add(s))}return{paired:t,used:n}}function eE(e,t,n,r,s){let o=zS.get(n);if(o&&o.sessionId===e&&o.native===t&&o.sum===r&&o.seq===s)return o;let a=as({session_id:e,root_id:t,rows:(r?[n,r]:[n]).map(d=>({runtime_session_id:t,info:d.info,parts:d.parts}))},{live:!0}),l=XI(t,n,a.threads[0].messages[0]),p={sessionId:e,native:t,sum:r,seq:s,message:{...l,seq:s},lost:a.grade_counts};return zS.set(n,p),p}function tE(e,t,n){let r=YS.get(n);if(r&&r.sessionId===e&&r.native===t)return r.log;let s=[...n].sort(zI),{paired:o,used:i}=ZI(s),a={tool_input:0,cut_point:0,attachment:0},l=[];for(let m of s){if(i.has(m))continue;let f=eE(e,t,m,o.get(m),l.length+1);for(let h of["tool_input","cut_point","attachment"])a[h]+=f.lost[h];l.push(f.message)}let p=YI(s.map(xa).find(m=>typeof m=="number"&&Number.isFinite(m)))??"",d=l.filter(m=>m.role==="user"&&m.kind==="turn"),g={...QS,session_id:e,created_at:p,restore_grade:a.tool_input+a.cut_point+a.attachment>0?"partial":"converted",grade_counts:a,harness:{current:"opencode",history:[]},selection:{agent:d.at(-1)?.agent??null,model:d.at(-1)?.model??null},threads:[{schema:ue,v:1,thread_id:t,parent_thread_id:null,spawned_by:null,agent:d[0]?.agent??null,title:null,created_at:l[0]?.created_at||p,messages:l,ext:{opencode:{version:Te,native_id:t}}}]};return YS.set(n,{sessionId:e,native:t,log:g}),g}var Pa=new WeakMap,Qt=new WeakMap,sx=new WeakMap;function Hs(e){let t,n=Qt.get(e);return n&&(t=nE(n).get(e.id)),t?(Pa.set(t,e),t):(e.type!=="harness"?t=Zo(e):typeof e.data?.type=="string"?t=e.data:e.model_visible&&e.fallback_text!==void 0&&(t=sx.get(e)??{id:e.id,type:"text",text:e.fallback_text,synthetic:!0},sx.set(e,t)),t&&Pa.set(t,e),t)}var tr=e=>Pa.get(e),Pt=e=>e.flatMap(t=>Hs(t)??[]),ox=new WeakMap;function nE(e){let t=ox.get(e);return t||ox.set(e,t=new Map(at(e)[0]?.parts.map(n=>[n.id,n]))),t}var ix=new Map;function at(e){let t=ix.get(e.thread_id);return t||(t={schema:ue,v:1,thread_id:e.thread_id,parent_thread_id:null,spawned_by:null,agent:null,title:null,created_at:""},ix.set(e.thread_id,t)),nx(t,e)}var rE="kortix-v1-import",wa={schema:ue,v:1};function Vs(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]}var ka=e=>e.type==="tool_call",sE=e=>e.status==="pending"||e.status==="running",va=e=>e.status==="error"&&(e.result?.synthetic===!0||e.result?.error?.code==="interrupted");function oE(e,t){let n=va(e);return!sE(e)&&!n?e.status:t?e.status==="running"||n&&e.started_at?"running":"pending":"interrupted"}var ax=new WeakMap;function iE(e,t){let n=ax.get(e);if(n)return n;let r=typeof e.client_sent_at_ms=="number"?e.client_sent_at_ms:Date.parse(e.created_at),s={...wa,message_id:e.message_id||`queued-${e.prompt_id}`,thread_id:t,seq:Number.MAX_SAFE_INTEGER,role:"user",kind:"turn",status:"complete",in_context:!0,origin:"prompt",model:null,usage:null,finish:null,error:null,created_at:Number.isFinite(r)?new Date(r).toISOString():"",completed_at:null,producer:{harness:"kortix-inbox",harness_version:"",adapter_version:"1"},blocks:[{type:"text",id:`syn-${e.prompt_id}`,text:e.full_text??e.text}]};return ax.set(e,s),s}var cx=new WeakMap;function aE(e){let t=cx.get(e);return t||(t={...wa,message_id:e.reply_to,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},cx.set(e,t)),t}var lx=new WeakMap;function cE(e){let t=lx.get(e);return t||(t={...wa,message_id:`${e.message_id}:continued`,thread_id:e.thread_id,seq:e.seq,role:"user",kind:"turn",status:"complete",in_context:!0,model:null,usage:null,finish:null,error:null,created_at:e.created_at,completed_at:null,producer:e.producer,blocks:[]},lx.set(e,t)),t}var lE=e=>!e.error&&e.blocks.length===0&&!(e.usage&&(e.usage.input||e.usage.output||e.usage.reasoning));function uE(e,t){let n=[],r=new Map;for(let g of e){if(g.role!=="user"||g.kind==="context"||r.has(g.message_id))continue;let m={user:g,assistant:[],partial:!1};r.set(g.message_id,m),n.push(m)}let s=[],o=[],i=new Map,a=new Map,l=null,p=null;for(let g of e){if(g.role==="user"){let S=r.get(g.message_id);S&&!t.has(g.message_id)&&(l=S,i.has(S)||i.set(S,i.size),S.user.kind==="compaction"&&(p=S));continue}if(g.role!=="assistant"||lE(g))continue;let f=(g.reply_to?r.get(g.reply_to):void 0)??l;if(p&&f&&(f===p||(i.get(f)??1/0)<i.get(p))){let S=a.get(p);S||(S={user:cE(p.user),assistant:[],partial:!0,continues:{marker:p.user.message_id,prompt:f===p?null:f.user.message_id}},a.set(p,S)),f=S}if(f){f.assistant.push(g);continue}if(!g.reply_to){o.push(g);continue}let h=s[s.length-1];h&&h.user.message_id===g.reply_to?h.assistant.push(g):s.push({user:aE(g),assistant:[g],partial:!0})}if(o.length){let g=n[0]??s[0];g?g.assistant.unshift(...o):n.push({user:o[0],assistant:o.slice(1),partial:!1})}let d=n.filter(g=>!t.has(g.user.message_id)).flatMap(g=>{let m=a.get(g);return m?[g,m]:[g]});return[...s,...d,...[...t].flatMap(g=>r.get(g)??[])]}function pE(e,t){let n=[],r=new Map,s=t;for(let o of e){let i=n[n.length-1],a=o.continues?r.get(o.continues.marker):o.user.kind==="compaction"&&i?.user.kind!=="compaction"?i:void 0;if(!a){n.push({...o,assistant:[...o.assistant]});continue}r.set(o.user.message_id,a),o.user.kind==="compaction"&&a.assistant.push(o.user),a.assistant.push(...o.assistant),t===o.user.message_id&&(s=a.user.message_id)}return{list:n,hint:s}}function dE(e,t){if(!t)return t;let n=t;for(let r of e){let s=r.continues;s&&(n===s.marker||n===s.prompt||t===s.prompt)&&(n=r.user.message_id)}return n}function dx(e){let n=(e.user.kind==="compaction"?[e.user,...e.assistant]:e.assistant).find(i=>i.error);if(!n?.error)return null;let r=at(n)[0]?.info?.error??n.error.message,s=Pe(r),o=Rs(r);return{code:n.error.code,message:s?.message||_e(r),...s&&{details:s},...o!==void 0&&{raw:o}}}function gE(e,t,n){return e.length&&e.every(t)?ca(e.flatMap(r=>at(r).flatMap(s=>s.parts.map(o=>({part:o,message:s})))),n)??null:Aa(e,n)}function Aa(e,t){let n=e.flatMap(r=>{let s=r.usage;if(!s)return[];let o={type:"step-finish",cost:s.cost??0,tokens:{input:s.input,output:s.output,reasoning:s.reasoning??0,cache:{read:s.cache_read,write:s.cache_write}}};return[{part:o,message:{info:{id:r.message_id,role:"assistant",providerID:r.model?.provider,modelID:r.model?.model},parts:[o]}}]});return ca(n,t)??null}function mE(e){if(e.kind!=="compaction")return null;let t=e.blocks.find(n=>n.type==="compaction")??null;return{block:t,hasContent:!!t?.summary?.trim(),inFlight:e.status==="streaming"}}function fE(e){let t=e.user.blocks;if(!t.length||!t.every(r=>r.type==="text"&&r.synthetic))return null;let n=e.assistant.length===1&&e.assistant[0].blocks.length===1?e.assistant[0].blocks[0]:null;return n&&ka(n)&&n.name==="bash"?n:null}function yE(e,t,n,r){if(!n.length)return[];let s=new Set(e.assistant.map(i=>i.message_id)),o=new Set;for(let i of n)i.spawned_by&&s.has(i.spawned_by.message_id)&&o.add(i.thread_id);for(let i of t){let a=i.type==="subtask"?i.thread_id:ka(i)?Es(i):void 0;a&&r.has(a)&&o.add(a)}return[...o]}var hE=e=>e.assistant.some(t=>t.blocks.some(n=>ka(n)&&ce(n.name)==="todowrite"&&Kn(n))),_E=e=>e.blocks.length>0&&e.blocks.every(t=>t.type==="text"&&t.synthetic===!0);function bE(e,t){let n=e.map(s=>dx(s)!==null),r=e.map((s,o)=>n[o]===!0&&t[o+1]===!0);return e.map((s,o)=>{if(r[o])return{continued:!0,retries:0};if(!n[o])return;let i=0;for(let a=o-1;a>=0&&r[a];a--)i+=1;return i>0?{continued:!1,retries:i}:void 0})}var ux=new WeakMap,SE=[];function gx(e){let t=Vs(e.messages,n=>n.role==="assistant");return!!t&&Kb(at(t))}var px=new WeakMap;function xE(e){let t=px.get(e);if(!t){let n=e.messages.filter(r=>r.in_context||r.status==="streaming");t=n.length===e.messages.length?e:{...e,messages:n},px.set(e,t)}return t}function Ra(e,t={}){let n=t.hideOutOfContext?xE(e):e,r=new Set(t.held??SE),s=uE(n.messages,r),o=dE(s,t.liveMessageId),{list:i,hint:a}=t.foldCompactions?pE(s,o):{list:s,hint:o},l=Vs(n.messages,_=>_.role==="assistant"),p=gx(n),d=gS({turns:i.map(_=>({userMessage:{info:{id:_.user.message_id}},assistantMessages:_.assistant.map(b=>({info:{time:b.status==="streaming"?{}:{completed:1},error:b.error??void 0}}))})),hintMessageId:a,unrunTurnIds:r}),g=Vs(i,hE)??i[i.length-1],m=i.map(_=>!_.partial&&_E(_.user)),f=bE(i,m),h=ZS(n),S=_=>h||_.producer.harness===rE,v=t.threads??[],T=new Set(v.map(_=>_.thread_id));return i.map((_,b)=>{let O=t.busy===!0&&d.workingTurnId===_.user.message_id,y=d.pendingTurnIds.includes(_.user.message_id),w=p&&_.assistant.includes(l),x=f[b],k=`${_.partial}|${O}|${y}|${_===g}|${w}|${x?(x.continued?"c":"")+x.retries:"-"}`,C=ux.get(_.user);if(C&&C.key===k&&C.pricing===t.pricing&&C.heads===t.threads&&C.assistant.length===_.assistant.length&&C.assistant.every((D,q)=>D===_.assistant[q]))return C.turn;let j=_.assistant.flatMap(D=>D.blocks);for(let D of _.assistant)for(let q of D.blocks)Qt.set(q,D);let R=yE(_,j,v,T),L=_.assistant[_.assistant.length-1],le={internal:m[b],autoRetry:x,id:_.user.message_id,user:_.user,assistant:_.assistant,partial:_.partial,continues:_.continues??null,blocks:j,status:w?"streaming":L?L.status:_.user.kind==="compaction"?_.user.status:"pending",error:dx(_),cost:gE([_.user,..._.assistant],S,t.pricing),compaction:mE(_.user),threads:R,plan:_===g,shell:fE(_),response:Vs(j,D=>D.type==="text"&&!!D.text.trim())??null,attachments:_.user.blocks.filter(D=>D.type==="attachment"&&(D.mime.startsWith("image/")||D.mime==="application/pdf")),live:O,queued:y,retrying:w};return ux.set(_.user,{assistant:_.assistant,key:k,pricing:t.pricing,heads:t.threads,turn:le}),le})}var Ca=e=>tr(e);function PE(e,t={}){return lS(aS(Pt(e),t),t).map(n=>n.kind==="burst"?{kind:n.kind,blocks:n.parts.map(tr)}:n.kind==="show-group"?{kind:n.kind,blocks:n.parts.map(Ca)}:n.kind==="text"?{kind:n.kind,block:tr(n.part)}:{kind:n.kind,block:Ca(n.part)})}var wE=e=>e.kind==="burst"||e.kind==="show-group"?{kind:e.kind,parts:Pt(e.blocks)}:{kind:e.kind,part:Hs(e.block)};function kE(e,t){let n=new Map(e.map(o=>[wE(o),o])),r=wS([...n.keys()],t);if(!r)return null;let s=o=>o.map(i=>n.get(i));return{work:s(r.work),hoisted:s(r.hoisted),final:s(r.final)}}function vE(e){if(!te(e)||!Ly(e.tool))return!1;let t=e.state.input?.questions;if(!Array.isArray(t)||!t.length)return!1;let n=jb(e);return(n.answers??AS(n.outputText??"",t.length)??[]).length>0}function AE(e){return tS(Pt(e),n=>zn(n).tier).flatMap(n=>n.kind==="group"&&n.step.parts.some(vE)?n.step.parts.map(r=>({kind:"part",key:r.id,part:r})):[n]).map(n=>{if(n.kind==="part")return{kind:"block",key:n.key,block:tr(n.part)};if(n.kind==="group")return{kind:"group",key:n.key,blocks:n.step.parts.map(Ca),family:n.step.family,label:n.step.label,status:n.step.status,durationMs:n.step.durationMs};let r=e.find(o=>o.id===n.key.slice(8)),s=r&&Qt.get(r);return{kind:"thought",key:n.key,texts:n.texts,running:n.running&&(!s||s.status==="streaming"),durationMs:n.durationMs}})}function RE(e,t){return fS(Pt(e.blocks).map(n=>({part:n})),t?.flatMap(at))}function CE(e){return oa(Pt(e))}function TE(e){return Xb(Pt(e))}function IE(e,t){return t.working?t.trailing?!0:e.some(n=>{if(n.type==="tool_call")return n.status==="pending"||n.status==="running";if(n.type!=="reasoning")return!1;let r=Hs(n),s=Qt.get(n);return!!r&&we(r)&&ia(r)&&(!s||s.status==="streaming")}):!1}var mx=new WeakMap;function EE(e){if(!va(e))return e;let t=mx.get(e);if(!t){let{result:n,...r}=e;t={...r,status:e.started_at?"running":"pending"},mx.set(e,t)}return t}function ME(e){let{callID:t,error:n,...r}=e;return e.status==="error"?{...r,type:"error",content:n||"This output failed to load."}:r}function OE(e){let t=e.map(se),n=t[0],r=t.some(o=>o.state.status==="running"||o.state.status==="pending"),s=uS(t).map(ME);return cs({...n,state:{...n.state,status:r?"running":"completed",input:{items:s}}})}function DE(e,t,n){let r=se(e),s=r.state;return cs({...r,state:{...s,status:"completed",...n!==void 0&&{input:n},metadata:{...s.metadata??{},answers:t}}})}function jE(e){let t=at(e).map(r=>Ji(r)),n=t.find(r=>r.error)?.error;return{parts:t.flatMap(r=>r.parts),error:n,isEmpty:t.every(r=>r.isEmpty)&&!n}}var fx=Object.freeze([]),yx=new WeakMap;function LE(e){if(!e)return fx;let t=yx.get(e);if(!t){let n=e.messages.flatMap(r=>r.role==="assistant"?r.blocks.filter(s=>s.type==="tool_call"&&Kn(s)):[]);t=n.length?n:fx,yx.set(e,t)}return t}function $E(e,t={}){let n={cost:0,messages:{all:0,user:0,assistant:0},tokens:{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0},context:null};for(let r of Ra(e)){let s=Aa([r.user,...r.assistant],t.pricing);if(s){n.cost+=s.cost;for(let o of Object.keys(n.tokens))n.tokens[o]+=s.tokens[o]}}for(let r of e.messages){r.role==="user"?n.messages.user++:r.role==="assistant"&&n.messages.assistant++,r.kind==="compaction"&&r.status!=="streaming"&&n.messages.assistant++;let s=r.usage;(r.role==="assistant"||r.kind==="compaction")&&s&&s.input+s.output+(s.reasoning??0)+s.cache_read+s.cache_write>0&&(n.context=r)}return n.messages.all=n.messages.user+n.messages.assistant,n}var UE="prt_kortix_restore_g";function FE(e){return e.role==="user"&&e.blocks.some(t=>t.type==="text"&&t.id.startsWith(UE))}function NE(e,t){let n=new Map,r=[...e??[]].sort((s,o)=>s.from_seq-o.from_seq);for(let s=1;s<r.length;s++){let o=r[s],i=r[s-1].harness;if(o.harness===i)continue;let a=t.findIndex(l=>l.user.seq>=o.from_seq);a<0||a===0&&t[0].user.seq!==o.from_seq||n.set(t[a].id,{harness:o.harness,previous:i,version:o.version,at:o.at})}return n}var Ta=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qe=e=>typeof e=="number"&&Number.isFinite(e)&&e>0?e:0,BE=new Set(["message","attachment","tool_input","cut_point","layout","text","tool_result"]);function KE(e){if(e?.restore_grade!=="partial")return null;let t=e.ext?.kortix?.data,n=Ta(t)?t.restore:void 0;if(!Ta(n))return null;let r=Ta(n.dropped)?n.dropped:{},s=e.grade_counts,o=[{kind:"message",count:Qe(r.message)},{kind:"attachment",count:Qe(s?.attachment)},{kind:"text",count:Qe(r.text)+Qe(n.truncated)},{kind:"tool_input",count:Qe(s?.tool_input)},{kind:"tool_result",count:Qe(r.tool_result)},{kind:"cut_point",count:Qe(s?.cut_point)},{kind:"other",count:Object.entries(r).reduce((i,[a,l])=>BE.has(a)?i:i+Qe(l),0)}];return{generation:Qe(n.generation),missing:o.filter(i=>i.count>0)}}var _x=e=>e.type==="text"?[e]:e.type==="tool_call"?(e.result?.content??[]).filter(t=>t.type==="text"):[];function qE(e){let t=new Map;for(let n of e)for(let r of n.blocks)for(let s of _x(r))s.ref&&s.bytes!==void 0&&!t.has(s.ref)&&t.set(s.ref,s.bytes);return[...t].map(([n,r])=>({ref:n,bytes:r}))}var bx=(e,t)=>{let n=e.ref===void 0?void 0:t.get(e.ref);if(n===void 0)return e;let{ref:r,bytes:s,...o}=e;return{...o,text:n}},GE=(e,t)=>e.map(n=>n.type==="text"?bx(n,t):n),hx=new WeakMap;function WE(e,t){let n=hx.get(e);if(n?.texts===t)return n.out;let r=e.blocks.some(s=>_x(s).some(o=>o.ref!==void 0&&t.has(o.ref)))?{...e,blocks:e.blocks.map(s=>s.type==="text"?bx(s,t):s.type==="tool_call"&&s.result?{...s,result:{...s.result,content:GE(s.result.content,t)}}:s)}:e;return hx.set(e,{texts:t,out:r}),r}var Ia=1024*1024;function HE(e){return e.reduce((t,n)=>t+n.bytes,0)>Ia?"download":"inline"}function VE(e){let t=new Set,n=0;for(let r of[...e].sort((s,o)=>s.bytes-o.bytes)){if(n+r.bytes>Ia)break;n+=r.bytes,t.add(r)}return{inline:e.filter(r=>t.has(r)),download:e.filter(r=>!t.has(r))}}function zE(e,t){if(t.size===0)return e;let n=e.messages.map(r=>WE(r,t));return n.every((r,s)=>r===e.messages[s])?e:{...e,messages:n}}function YE(e){return e==="TIMEOUT"||e==="request_deadline"}function JE(e){let t=xx(e)?e.code:void 0;return typeof t=="string"?t:void 0}var xx=e=>typeof e=="object"&&e!==null;function Sx(e){let t=e?.metadata;return!!xx(t)&&t.warm===!0}var QE=5,XE=2e3,ZE=e=>new Promise(t=>setTimeout(t,e));async function eM(e,{attempts:t=QE,delayMs:n=XE,sleep:r=ZE}={}){for(let s=0;s<t;s++){s>0&&await r(n);try{if(await e())return!0}catch{}}return!1}function xX(e,t){let n=new Map,r=new Set,s=new Set,o=new Set,i=0,a=(l,p,d)=>{if(r.has(l)||n.has(l))return Promise.resolve();r.add(l);let g=i,m=(async()=>{let f=null;try{let h=await e.ensure(l,p);if(g!==i)return;s.has(h.sessionId)?f=h.sessionId:n.set(l,h)}catch{}finally{g===i&&r.delete(l)}f&&d>0&&await a(l,f,d-1)})();return o.add(m),m.finally(()=>o.delete(m)),m};return{ensure:(l,p)=>a(l,p?.excludeSessionId,1),take:(l,p,{replenish:d})=>{let g=n.get(l);return g?(n.delete(l),s.add(g.sessionId),d&&a(l,g.sessionId,1),t.fits(g,p)?g:null):null},prime:async(l,p,d)=>{try{return await e.claim(l,d),!0}catch(g){return YE(JE(g))?eM(async()=>!Sx(await e.read(l,p.sessionId)),t.sleep?{sleep:t.sleep}:{}):!1}},dropBySessionId:l=>{for(let[p,d]of n)if(d.sessionId===l)return n.delete(p),s.add(l),p;return null},revalidate:async l=>{let p=n.get(l);if(!p)return!1;try{if(Sx(await e.read(l,p.sessionId)))return!1}catch{return!1}return n.get(l)?.sessionId!==p.sessionId?!1:(n.delete(l),s.add(p.sessionId),!0)},held:l=>n.get(l)??null,reset:()=>{i+=1,n.clear(),r.clear(),s.clear()},settled:async()=>{for(;o.size>0;)await Promise.all([...o])}}}var tM=12e4,zs=class extends Error{constructor(t){super(`Session history read did not settle within ${t}ms`),this.name="SessionSyncReadTimeoutError"}},nM=1e3,rM=15e3,Px=100,sM=50,oM=10;function wx(e){let t=e.fetch??globalThis.fetch,n=e.baseUrl.replace(/\/$/,"");return async({limit:r,before:s},o)=>{let i=new URLSearchParams({limit:String(r)});s&&i.set("before",s);let a=await e.getToken?.(),l=await t(`${n}/session/${encodeURIComponent(e.sessionId)}/message?${i}`,{headers:a?{Authorization:`Bearer ${a}`}:void 0,...o?{signal:o}:{}});if(!l.ok)throw l.status===503?new qs(`session ${l.status}`):new P(`Session synchronization failed: ${l.status}`,{status:l.status});return{messages:await l.json(),nextCursor:l.headers.get("x-next-cursor")||void 0}}}function iM(e){return cM(wx(e))}function aM(e){return new Ea({...e,loadPage:wx(e)})}async function cM(e){let t=[],n=new Set,r;do{let i=await e({limit:Px,...r?{before:r}:{}});if(t.push(i.messages),r=i.nextCursor,r&&n.has(r))throw new Error(`Session history cursor repeated: ${r}`);r&&n.add(r)}while(r);let s=[],o=new Set;for(let i=t.length-1;i>=0;i--)for(let a of t[i])o.has(a.info.id)||(o.add(a.info.id),s.push(a));return s}var lM={now:Date.now,setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},Ea=class{options;scheduler;livenessIntervalMs;verifyIntervalMs;readTimeoutMs;lastTailReadAt;retryAttempt=0;tailUnavailable=!1;tailRetryTimer;snapshot={freshness:"idle",hasOlder:!1,isLoadingOlder:!1};nextCursor;knownUserMessageIds=new Set;olderHistoryStarted=!1;tailRequest;turnEndPending=!1;olderRequest;livenessTimer;livenessBusy=!1;streamReliable=!1;lastActivityAt;listeners=new Set;destroyed=!1;abortController=new AbortController;constructor(t){this.options=t,this.scheduler=t.scheduler??lM,this.livenessIntervalMs=t.livenessIntervalMs??1e4,this.verifyIntervalMs=t.verifyIntervalMs??3e4,this.readTimeoutMs=t.readTimeoutMs??tM,this.lastActivityAt=this.scheduler.now(),this.lastTailReadAt=this.scheduler.now()}getSnapshot=()=>this.snapshot;subscribe=t=>(this.listeners.add(t),()=>this.listeners.delete(t));start(){return this.snapshot.freshness==="fresh"?Promise.resolve():this.reconcile("initial")}reconcile(t="manual"){return this.destroyed||t==="visible"&&this.streamReliable&&this.snapshot.freshness==="fresh"?Promise.resolve():this.tailRequest?this.tailRequest:(this.update({freshness:this.snapshot.freshness==="idle"||this.snapshot.freshness==="loading"?"loading":this.snapshot.freshness}),this.tailRequest=this.loadTail(t).finally(()=>{this.tailRequest=void 0}),this.tailRequest)}loadOlder=()=>{if(this.destroyed||!this.nextCursor)return Promise.resolve();if(this.olderRequest)return this.olderRequest;let t=this.nextCursor;return this.update({isLoadingOlder:!0}),this.olderRequest=this.loadCompleteOlderTurn(t).then(n=>{this.destroyed||(this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted=!0,this.setCursor(n.nextCursor))}).finally(()=>{this.olderRequest=void 0,this.update({isLoadingOlder:!1})}),this.olderRequest};noteActivity(){this.lastActivityAt=this.scheduler.now(),this.snapshot.freshness!=="fresh"&&this.update({freshness:"fresh"})}setStreamReliable(t){this.streamReliable=t}setBusy(t,n=!1){let r=this.livenessBusy&&!t;if(this.livenessBusy=t,!t&&!n){this.stopLivenessTimer(),r&&!this.destroyed&&this.reconcileTurnEnd();return}r&&!this.destroyed&&this.reconcileTurnEnd(),this.livenessTimer===void 0&&(this.lastActivityAt=this.scheduler.now(),this.livenessTimer=this.scheduler.setInterval(()=>{this.checkLiveness()},this.livenessIntervalMs))}destroy(){this.destroyed=!0,this.stopLivenessTimer(),this.tailRetryTimer!==void 0&&(this.cancelTimer(this.tailRetryTimer),this.tailRetryTimer=void 0),this.abortController.abort(),this.listeners.clear()}reconcileTurnEnd(){if(!this.tailRequest){this.reconcile("turn-end");return}this.turnEndPending||(this.turnEndPending=!0,this.tailRequest.finally(()=>{this.turnEndPending=!1,this.destroyed||this.reconcile("turn-end")}))}async loadTail(t){this.lastTailReadAt=this.scheduler.now();try{let n=await this.loadPage("tail",t);if(this.destroyed)return;this.rememberUserMessages(n.messages),this.options.hydrate(n.messages),this.olderHistoryStarted||this.setCursor(n.nextCursor),this.update({freshness:"fresh"}),this.options.markLoaded(),this.retryAttempt=0,this.tailUnavailable=!1}catch(n){if(this.destroyed||this.abortController.signal.aborted)return;let r=n instanceof zs;if(!r&&Bs(n))return;if(r||this.update({freshness:Zn(n)?"loading":"error"}),n instanceof P&&(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(nM*2**this.retryAttempt,rM);this.retryAttempt+=1,this.tailRetryTimer=this.startTimer(()=>{this.tailRetryTimer=void 0,!this.destroyed&&this.reconcile(t)},n)}async loadPage(t,n,r){let s=this.scheduler.now();try{let o=await this.boundedRead(i=>this.options.loadPage({limit:t==="tail"?sM:Px,...r?{before:r}:{}},i));return this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:o.messages.length,succeeded:!0}),o}catch(o){throw this.options.onTelemetry?.({operation:t,reason:n,durationMs:this.scheduler.now()-s,messageCount:0,succeeded:!1}),o}}boundedRead(t){let n=this.abortController.signal,r=new AbortController,s=()=>r.abort(n.reason);n.aborted?r.abort(n.reason):n.addEventListener("abort",s,{once:!0});let o,i=new Promise((l,p)=>{o=this.startTimer(()=>{let d=new zs(this.readTimeoutMs);p(d),r.abort(d)},this.readTimeoutMs)}),a;try{a=t(r.signal)}catch(l){a=Promise.reject(l)}return Promise.race([a,i]).finally(()=>{this.cancelTimer(o),n.removeEventListener("abort",s)})}async loadCompleteOlderTurn(t){let n=await this.loadPage("older","manual",t);return this.loadCompleteTurn(n,"older","manual",t,r=>{this.rememberUserMessages(r.messages),this.options.hydrate(r.messages),this.setCursor(r.nextCursor)})}async loadCompleteTurn(t,n,r,s,o){let i=[...t.messages],a=new Set(this.knownUserMessageIds),l=new Set(s?[s]:[]),p=t.nextCursor,d=0;for(let g of t.messages)g.info.role==="user"&&a.add(g.info.id);for(;p&&d<oM&&i.some(g=>g.info.role==="assistant"&&!!g.info.parentID&&!a.has(g.info.parentID));){if(l.has(p))throw new Error(`Session history cursor repeated: ${p}`);l.add(p);let g;try{g=await this.loadPage(n,r,p)}catch(m){throw o?.({messages:[...i],nextCursor:p}),m}if(this.destroyed)return{messages:i,nextCursor:p};d+=1,i.unshift(...g.messages);for(let m of g.messages)m.info.role==="user"&&a.add(m.info.id);p=g.nextCursor,o?.({messages:[...i],nextCursor:p})}return{messages:i,nextCursor:p}}rememberUserMessages(t){for(let n of t)n.info.role==="user"&&this.knownUserMessageIds.add(n.info.id)}async checkLiveness(){if(this.destroyed||this.tailUnavailable||this.streamReliable)return;let t=this.scheduler.now(),n=t-this.lastActivityAt>this.livenessIntervalMs,r=t-this.lastTailReadAt>=this.verifyIntervalMs;!(this.livenessBusy&&n)&&!r||(await this.raceDeadline(this.reconcile("poll"),this.livenessIntervalMs),this.lastActivityAt=this.scheduler.now())}raceDeadline(t,n){return new Promise(r=>{let s,o=!1,i=()=>{o||(o=!0,this.cancelTimer(s),r())};s=this.startTimer(i,n),t.then(i,i)})}setCursor(t){this.nextCursor=t,this.update({hasOlder:!!t})}stopLivenessTimer(){this.livenessTimer!==void 0&&(this.scheduler.clearInterval(this.livenessTimer),this.livenessTimer=void 0)}startTimer(t,n){return this.scheduler.setTimeout?this.scheduler.setTimeout(t,n):setTimeout(t,n)}cancelTimer(t){t!==void 0&&(this.scheduler.clearTimeout?this.scheduler.clearTimeout(t):clearTimeout(t))}update(t){let n={...this.snapshot,...t};if(!(n.freshness===this.snapshot.freshness&&n.hasOlder===this.snapshot.hasOlder&&n.isLoadingOlder===this.snapshot.isLoadingOlder)){this.snapshot=n;for(let r of this.listeners)r()}}};var uM=5e3,vx=40,RX=5*6e4,pM=16,nr=new Map;function Ax(e,t,n,r=Date.now()){let s=Rx(e,t);for(nr.delete(s),nr.set(s,{envelope:n,atMs:r});nr.size>pM;){let o=nr.keys().next().value;if(o===void 0)break;nr.delete(o)}}var kx=new Map;function Rx(e,t){return`${e}/${t}`}function dM(e,t){return e.settledAtMs===null?!0:t-e.settledAtMs<=uM}function Cx(e,t,n=Date.now()){if(!e||!t)return null;let r=Rx(e,t),s=kx.get(r);return s?dM(s,n)?s.promise:(kx.delete(r),null):null}function Tx(e){let t=e.transcript;if(!t||t.known!==!0||t.requested!==!0)return null;let{known:n,requested:r,...s}=t;if(!s.available)return s;let o=e.session?.runtime_session_id??e.session?.opencode_session_id,i=s.runtime_session_id??s.opencode_session_id;return o&&i===o?s:null}var gM=/(?:\n\n)?Command exited with code (-?\d+)\s*$/;function mM(e){if(e.status!=="error"||e.name!=="bash"||!e.result)return e;let n=e.result.content.filter(i=>i.type==="text").map(i=>i.text).join(""),r=gM.exec(n);if(!r)return e;let{error:s,...o}=e.result;return{...e,status:"complete",result:{...o,content:[{type:"text",text:n.slice(0,r.index)},...e.result.content.filter(i=>i.type!=="text")],is_error:!1,exit_code:Number(r[1])}}}function Ix(e){let t=!1,n=e.blocks.map(r=>{if(r.type!=="tool_call")return r;let s=mM(r);return s!==r&&(t=!0),s});return t?{...e,blocks:n}:e}var Ex=Object.freeze({generation:0,session:{},threads:{},messages:{},revs:{},older:{}});function fM(e,t){let n=Ix(t),r=(e[n.thread_id]??[]).filter(o=>o.message_id!==n.message_id),s=r.length;for(;s>0&&r[s-1].seq>n.seq;)s--;return r.splice(s,0,n),{...e,[n.thread_id]:r}}function Mx(e,t,n){let r=e.messages,s=e.older,o=t.thread_id,i=o===null?void 0:r[o];if(o!==null){let p=t.messages[0]?.seq;(n!==void 0||!i?.length||!t.has_more||p!==void 0&&p<=i[0].seq)&&e.older[o]!==t.has_more&&(s={...s,[o]:t.has_more})}if(o!==null&&i){let p=t.has_more?t.messages[0]?.seq??1/0:-1/0,d=n??1/0,g=new Set(t.messages.map(f=>f.message_id)),m=i.filter(f=>f.seq<p||f.seq>=d||g.has(f.message_id)||e.revs[f.message_id]!==void 0);m.length!==i.length&&(r={...r,[o]:m})}for(let p of t.messages)!Ro(p)||e.revs[p.message_id]!==void 0||(r=fM(r,p));let a={...e.threads};for(let p of t.threads)Co(p)&&(a[p.thread_id]=p);let l=t.generation>e.generation;return{...e,generation:Math.max(t.generation,e.generation),session:l?{...e.session,...t.session}:{...t.session,...e.session},threads:a,messages:r,older:s}}var yM=2e3;async function hM(e,t,n){let r=Cx(e,t),s,o=r?await Promise.race([r,new Promise(i=>{s=setTimeout(i,n.snapshotWaitMs??yM,null)})]).finally(()=>clearTimeout(s)):null;return(o&&Tx(o))??jr(e,t,{limit:vx,history:!0,signal:n.signal})}async function _M(e){let{projectId:t,sessionId:n,runtimeSessionId:r}=e;if(!t||!n||!r)return{envelope:null,empty:!1};let s=pn?await Tp(pn,t,n):null;if(s){let i=tx(Mx(Ex,s));return{envelope:null,empty:!!i?.empty&&i.runtimeSessionId===r&&await Ox(t,n,r),log:s}}let o;try{o=await hM(t,n,{})}catch{return{envelope:null,empty:!1}}return Ax(t,n,o),Dx(o)!==r?{envelope:o,empty:!1}:{envelope:o,empty:await Ox(t,n,r)}}async function Ox(e,t,n){try{let r=await Lr(e,t);return jx({savedEmptyRoot:n,rootSessionId:n,turnRead:!0,hasEndedTurn:r.last_ended!=null,hasOpenOrQueuedTurn:r.turns.length>0})}catch{return!1}}function Dx(e){return e?.available&&e.source==="mirror"&&e.complete&&e.total===0&&e.messages.length===0?e.runtime_session_id??e.opencode_session_id??null:null}function jx(e){return e.savedEmptyRoot!==null&&e.savedEmptyRoot===e.rootSessionId&&e.turnRead&&!e.hasEndedTurn&&!e.hasOpenOrQueuedTurn}function BX(e){throw N("buildTunnelEventStreamUrl")}function KX(e){let{url:t,token:n,method:r="GET",body:s,onEvent:o,onOpen:i,onError:a,onClose:l,signal:p}=e,d=new Map,g=null,m=!1,f="";function h(b,O){o?.(b,O);let y=d.get(b);if(y)for(let w of y)try{w(O)}catch{}}async function S(){if(m)return;let b=new AbortController;g=b,p&&(p.aborted?b.abort():p.addEventListener("abort",()=>b.abort(),{once:!0}));let O=b.signal;try{let y={Accept:"text/event-stream",Authorization:`Bearer ${n}`};r!=="GET"&&s!==void 0&&(y["Content-Type"]="application/json"),f&&(y["Last-Event-ID"]=f);let w=await fetch(t,{method:r,headers:y,body:r!=="GET"&&s!==void 0?JSON.stringify(s):void 0,signal:O,credentials:"include"});if(!w.ok)throw new Error(`SSE connection failed: ${w.status} ${w.statusText}`);if(!w.body)throw new Error("SSE response has no body");i?.();let x=w.body.getReader(),k=new TextDecoder,C="",j="message",R=[],L=D=>{if(D===""){R.length>0&&h(j,R.join(`
|
|
98
|
+
`)),j="message",R=[];return}if(D.startsWith(":"))return;let q=D.indexOf(":"),W=q===-1?D:D.slice(0,q),K=q===-1?"":D.slice(q+1);K.startsWith(" ")&&(K=K.slice(1)),W==="event"?j=K.trim()||"message":W==="data"?R.push(K):W==="id"&&!K.includes("\0")&&(f=K)},le=D=>{let q="";!D&&C.endsWith("\r")&&(q="\r",C=C.slice(0,-1));let W=C.split(/\r\n|\n|\r/);C=(W.pop()??"")+q;for(let K of W)L(K)};for(;!m;){let{done:D,value:q}=await x.read();if(D)break;C+=k.decode(q,{stream:!0}),le(!1)}m||(C+=k.decode(),le(!0),l?.())}catch(y){if(m||y instanceof DOMException&&y.name==="AbortError")return;a?.(y instanceof Error?y:new Error(String(y)))}}function v(){m=!0,g?.abort(),g=null,d.clear()}function T(b,O){let y=d.get(b)??new Set;y.add(O),d.set(b,y)}function _(b,O){d.get(b)?.delete(O)}return{connect:S,close:v,addEventListener:T,removeEventListener:_}}function qX(e,t){throw N("createTunnelEventStream")}var Lx="/_kortix/viewer",Ys=6e4,Xt=new Map;function bM(){Xt.clear(),rr.clear()}async function SM(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 $x(e={}){let t=e.path??Lx,n=e.fetch??((o,i)=>fetch(o,i)),r=Xt.get(t);if(r&&!r.inflight&&r.expiresAt>Date.now())return r.session;if(r?.inflight)return r.inflight;let s=SM(t,n).then(o=>{let i=o?.expires_at?Date.parse(o.expires_at):Number.NaN,a=Number.isFinite(i)?i-Ys:Date.now()+Ys;return Xt.set(t,{session:o,expiresAt:a}),o});return Xt.set(t,{session:r?.session??null,expiresAt:0,inflight:s}),s}function xM(e={}){let t=e.path??Lx;return Object.assign(async()=>(await $x(e))?.access_token??null,{invalidate:n=>{let r=Xt.get(t);r&&!r.inflight&&r.session?.access_token===n&&Xt.delete(t)}})}var rr=new Map;async function PM(e,t){try{let n=await t(e,{credentials:"same-origin",headers:{accept:"application/json"}});if(!n.ok){if(n.status===403){let o=await n.json().catch(()=>null);o?.error==="app_not_linked"&&console.warn(`[kortix] ${String(o.error_description)}`)}return null}let r=await n.json().catch(()=>null);if(!r||typeof r.token!="string")return null;let s=typeof r.expires_at=="string"?Date.parse(r.expires_at):Number.NaN;return rr.set(e,{token:r.token,refreshAt:Number.isFinite(s)?s-Ys:Date.now()+Ys}),r.token}catch{return null}}function Ux(e={}){let t=e.path??"/_kortix/token",n=e.audience===void 0?t:`${t}?audience=${encodeURIComponent(e.audience)}`,r=e.fetch??((s,o)=>fetch(s,o));return async(s={})=>{let o=rr.get(n);if(o instanceof Promise)return o;if(o&&!s.forceRefreshToken&&o.refreshAt>Date.now())return o.token;let i=PM(n,r).then(a=>(a===null&&rr.delete(n),a));return rr.set(n,i),i}}function wM(e,t={}){let n=t.origin??globalThis.location?.origin;if(!n)throw new Error("kortixBinding needs the App origin: pass { origin } outside a browser.");return{url:`${pe(n)}/_kortix/apps/${encodeURIComponent(e)}`,token:Ux({audience:e,fetch:t.fetch})}}var wt=class extends Error{code;constructor(t,n){super(n),this.name="KortixMemberError",this.code=t}},be=e=>typeof e=="string"&&e.length>0?e:null;function Fx(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return[]}return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Oa(e){if(!e||typeof e!="object")return null;let t=e,n=be(t.sub)??be(t.subject)??be(t.user_id)??be(t.userId);return n?{userId:n,email:be(t.email),name:be(t.name),picture:be(t.picture)??be(t.pictureUrl),groups:Fx(t.groups),groupIds:Fx(t.group_ids??t.groupIds),role:be(t.role),accountId:be(t.account_id)??be(t.accountId),projectId:be(t.project_id)??be(t.projectId)}:null}function kM(e,t={}){let n=Oa(e);if(!n)throw new wt("unauthenticated","Sign in with Kortix to continue.");let{groups:r,roles:s}=t;if(r&&!r.some(o=>n.groups.includes(o)||n.groupIds.includes(o)))throw new wt("forbidden",`Only members of ${r.join(" or ")||"no group"} may do this.`);if(s&&!s.some(o=>n.role===o))throw new wt("forbidden",`Only ${s.join(" or ")||"no role"} members may do this.`);return n}var vM=60,Ma=new Map;function Bx(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,r=>r.charCodeAt(0))}function Nx(e){return JSON.parse(new TextDecoder().decode(Bx(e)))}async function AM(e,t){if(typeof e!="string")return e;if(e.startsWith("data:")){let n=e.indexOf(","),r=e.slice(5,n),s=e.slice(n+1),o=r.endsWith(";base64")?new TextDecoder().decode(Uint8Array.from(atob(s),i=>i.charCodeAt(0))):decodeURIComponent(s);return JSON.parse(o)}if(/^https?:\/\//.test(e)){let n=Ma.get(e);return n||(n=t(e,{headers:{accept:"application/json"}}).then(async r=>{if(!r.ok)throw new Error(`key set ${r.status}`);return await r.json()}),n.catch(()=>Ma.delete(e)),Ma.set(e,n)),n}return JSON.parse(e)}async function RM(e,t={}){let n=b=>{throw new wt("unauthenticated",`Kortix sign-in token refused: ${b}.`)},r=t.jwks??et("KORTIX_AUTH_JWKS"),s=t.issuer??et("KORTIX_AUTH_ISSUER"),o=t.audience??et("KORTIX_AUTH_AUDIENCE");if(!r)return n("no key set configured (KORTIX_AUTH_JWKS)");if(o!==!1&&!o)return n("no audience configured (KORTIX_AUTH_AUDIENCE, or `audience: false` to accept any App)");let i=typeof e=="string"?e.split("."):[];if(i.length!==3)return n("malformed");let[a,l,p]=i,d,g;try{d=Nx(a),g=Nx(l)}catch{return n("malformed")}if(d.alg!=="ES256")return n("unsupported algorithm");let m;try{m=await AM(r,t.fetch??((b,O)=>fetch(b,O)))}catch{return n("key set unavailable")}let f=(m.keys??[]).filter(b=>b.kty==="EC"&&(d.kid===void 0||b.kid===d.kid));if(f.length===0)return n("unknown key");let h=new TextEncoder().encode(`${a}.${l}`),S;try{S=Bx(p)}catch{return n("malformed")}let v=!1;for(let b of f)try{let{kid:O,alg:y,use:w,key_ops:x,...k}=b,C=await crypto.subtle.importKey("jwk",k,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},C,S,h)){v=!0;break}}catch{}if(!v)return n("bad signature");let T=Math.floor(Date.now()/1e3);if(typeof g.exp!="number"||g.exp+vM<T)return n("expired");if(s&&g.iss!==s)return n("wrong issuer");if(o){let b=g.aud;if(!(b===o||Array.isArray(b)&&b.includes(o)))return n("wrong audience")}let _=Oa(g);return _||n("no subject")}function Kx(e){let t=e.agents.map(CM),n=e.default_agent??e.open_code_default_agent;return n?t.sort((r,s)=>r.name===n?-1:s.name===n?1:0):t}function CM(e){return{name:e.name,description:e.description??void 0,mode:e.mode??void 0,source:e.source,hidden:e.hidden===!0||e.enabled===!1}}function qx(e,t){if(!Array.isArray(e))return[];let n=t?.includeSubagents===!0;return e.filter(r=>oi(n?{...r,mode:null}:r))}function TM(e){let t=e.boundAgent?.trim()||null;if(!Array.isArray(e.agents)){let o=e.selectedAgent?.trim();return o?{selected:o,disabled:!1,reason:"loading"}:{selected:t,disabled:!1,reason:"loading"}}let n=qx(e.agents);if(n.length===0)return t?{selected:t,disabled:!1,reason:"bound"}:{selected:null,disabled:!0,reason:"no_access"};let r=e.selectedAgent?.trim();if(r&&n.some(o=>o.name===r))return{selected:r,disabled:!1,reason:"selected"};if(t)return{selected:t,disabled:!1,reason:"bound"};let s=e.defaultAgent?.trim();return s&&n.some(o=>o.name===s)?{selected:s,disabled:!1,reason:"default"}:{selected:n[0].name,disabled:!1,reason:"first_accessible"}}var IM=Kx;function Gx(e){return e.providerID==="kortix"||e.providerID==="opencode"?e.modelID:`${e.providerID}/${e.modelID}`}function Da(e){return{providerID:"kortix",modelID:e}}function sr(e,t){return Da(e.startsWith("kortix/")?e.slice(7):e)}var Wx=[{id:"bee",env:["BEE_API_KEY"]},{id:"aki-io",env:["AKI_IO_API_KEY"]},{id:"gitlab",env:["GITLAB_TOKEN"]},{id:"routing-run",env:["ROUTING_RUN_API_KEY"]},{id:"kimi-code-plan-cn",env:["KIMI_API_KEY"]},{id:"ovhcloud",env:["OVHCLOUD_API_KEY"]},{id:"xiaomi-token-plan-cn",env:["XIAOMI_API_KEY"]},{id:"fireworks-ai",env:["FIREWORKS_API_KEY"]},{id:"zeldoc",env:["ZELDOC_API_KEY"]},{id:"perplexity-agent",env:["PERPLEXITY_API_KEY"]},{id:"crusoe",env:["CRUSOE_API_KEY"]},{id:"coralbricks",env:["CORAL_API_KEY"]},{id:"groq",env:["GROQ_API_KEY"]},{id:"llmtech",env:["LLMTECH_API_KEY"]},{id:"impossibl",env:["IMPOSSIBL_API_KEY"]},{id:"hpc-ai",env:["HPC_AI_API_KEY"]},{id:"claudinio",env:["CLAUDINIO_API_KEY"]},{id:"nan",env:["NAN_API_KEY"]},{id:"moonshotai-cn",env:["MOONSHOT_API_KEY"]},{id:"aixy",env:["AIXY_API_KEY"]},{id:"standardcompute",env:["STANDARDCOMPUTE_API_KEY"]},{id:"liquid",env:["LIQUID_API_KEY"]},{id:"zhipuai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"auriko",env:["AURIKO_API_KEY"]},{id:"requesty",env:["REQUESTY_API_KEY"]},{id:"drun",env:["DRUN_API_KEY"]},{id:"jalapeno",env:["JALAPENO_API_KEY"]},{id:"dinference",env:["DINFERENCE_API_KEY"]},{id:"chutes",env:["CHUTES_API_KEY"]},{id:"minimax-coding-plan",env:["MINIMAX_API_KEY"]},{id:"openreason",env:["OPENREASON_API_KEY"]},{id:"ainetcafe",env:["AINETCAFE_API_KEY"]},{id:"mixlayer",env:["MIXLAYER_API_KEY"]},{id:"azure",env:["AZURE_RESOURCE_NAME","AZURE_API_KEY"]},{id:"stepfun-ai-step-plan",env:["STEPFUN_API_KEY"]},{id:"tencent-tokenhub",env:["TENCENT_TOKENHUB_API_KEY"]},{id:"poe",env:["POE_API_KEY"]},{id:"fastrouter",env:["FASTROUTER_API_KEY"]},{id:"aiand",env:["AIAND_API_KEY"]},{id:"databricks",env:["DATABRICKS_HOST","DATABRICKS_TOKEN"]},{id:"runinfra",env:["RUNINFRA_GATEWAY_KEY"]},{id:"deepseek",env:["DEEPSEEK_API_KEY"]},{id:"atomic-chat",env:["ATOMIC_CHAT_API_KEY"]},{id:"cloudferro-sherlock",env:["CLOUDFERRO_SHERLOCK_API_KEY"]},{id:"crossmodel",env:["CROSSMODEL_API_KEY"]},{id:"azure-cognitive-services",env:["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME","AZURE_COGNITIVE_SERVICES_API_KEY"]},{id:"agentrouter",env:["AGENTROUTER_API_KEY"]},{id:"zai-coding-plan",env:["ZHIPU_API_KEY"]},{id:"clarifai",env:["CLARIFAI_PAT"]},{id:"xiaomi-token-plan-ams",env:["XIAOMI_API_KEY"]},{id:"ambient",env:["AMBIENT_API_KEY"]},{id:"vispark",env:["VISPARK_LAB_API_KEY"]},{id:"alibaba-token-plan-cn",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"kilo",env:["KILO_API_KEY"]},{id:"anthropic",env:["ANTHROPIC_API_KEY"]},{id:"cloudflare-workers-ai",env:["CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_API_KEY"]},{id:"boundless",env:["BOUNDLESS_API_KEY"]},{id:"submodel",env:["SUBMODEL_INSTAGEN_ACCESS_KEY"]},{id:"salad-cloud",env:["SALAD_CLOUD_API_KEY"]},{id:"regolo-ai",env:["REGOLO_API_KEY"]},{id:"merge-gateway",env:["MERGE_GATEWAY_API_KEY"]},{id:"zenifra",env:["ZENIFRA_AI_KEY"]},{id:"klokintegration",env:["KLOKINTEGRATION_API_KEY"]},{id:"bailing",env:["BAILING_API_TOKEN"]},{id:"siliconflow",env:["SILICONFLOW_API_KEY"]},{id:"morph",env:["MORPH_API_KEY"]},{id:"opper",env:["OPPER_API_KEY"]},{id:"scx-ai",env:["SCX_API_KEY"]},{id:"alibaba",env:["DASHSCOPE_API_KEY"]},{id:"the-grid-ai",env:["THEGRID_API_KEY"]},{id:"vercel",env:["AI_GATEWAY_API_KEY"]},{id:"sensenova",env:["SENSENOVA_API_KEY"]},{id:"tokenrouter",env:["TOKENROUTER_API_KEY"]},{id:"meta",env:["META_MODEL_API_KEY"]},{id:"volcengine",env:["ARK_API_KEY"]},{id:"berget",env:["BERGET_API_KEY"]},{id:"synthetic",env:["SYNTHETIC_API_KEY"]},{id:"xpersona",env:["XPERSONA_API_KEY"]},{id:"kosmik",env:["KOSMIK_API_KEY"]},{id:"frogbot",env:["FROGBOT_API_KEY"]},{id:"deepinfra",env:["DEEPINFRA_API_KEY"]},{id:"alibaba-coding-plan-cn",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"jiekou",env:["JIEKOU_API_KEY"]},{id:"model-oracle-ai",env:["MODEL_ORACLE_API_KEY"]},{id:"opencode",env:["OPENCODE_API_KEY"]},{id:"neon",env:["NEON_AI_GATEWAY_BASE_URL","NEON_AI_GATEWAY_TOKEN"]},{id:"llmgateway-providers",env:["LLMGATEWAY_API_KEY"]},{id:"iflowcn",env:["IFLOW_API_KEY"]},{id:"scaleway",env:["SCALEWAY_API_KEY"]},{id:"zenmux",env:["ZENMUX_API_KEY"]},{id:"qvac",env:["QVAC_API_KEY"]},{id:"orcarouter",env:["ORCAROUTER_API_KEY"]},{id:"stepfun-step-plan",env:["STEPFUN_API_KEY"]},{id:"agnes",env:["AGNES_API_KEY"]},{id:"llama",env:["LLAMA_API_KEY"]},{id:"lilac",env:["LILAC_API_KEY"]},{id:"volcengine-coding-plan",env:["ARK_CODING_PLAN_API_KEY"]},{id:"kimi-code-plan-global",env:["KIMI_API_KEY"]},{id:"alibaba-cn",env:["DASHSCOPE_API_KEY"]},{id:"nova",env:["NOVA_API_KEY"]},{id:"ebcloud",env:["EBCLOUD_API_KEY"]},{id:"melious",env:["MELIOUS_API_KEY"]},{id:"friendli",env:["FRIENDLI_TOKEN"]},{id:"upstage",env:["UPSTAGE_API_KEY"]},{id:"cortecs",env:["CORTECS_API_KEY"]},{id:"inco",env:["INCO_API_KEY"]},{id:"anyapi",env:["ANYAPI_API_KEY"]},{id:"greenpt",env:["GREENPT_API_KEY"]},{id:"togetherai",env:["TOGETHER_API_KEY"]},{id:"infomaniak",env:["INFOMANIAK_API_KEY","INFOMANIAK_PRODUCT_ID"]},{id:"qiniu-ai",env:["QINIU_API_KEY"]},{id:"siliconflow-cn",env:["SILICONFLOW_CN_API_KEY"]},{id:"infer",env:["INFER_API_KEY"]},{id:"minimax-cn-coding-plan",env:["MINIMAX_API_KEY"]},{id:"daoxe",env:["DAOXE_API_KEY"]},{id:"llmgateway",env:["LLMGATEWAY_API_KEY"]},{id:"helicone",env:["HELICONE_API_KEY"]},{id:"nvidia",env:["NVIDIA_API_KEY"]},{id:"stepfun",env:["STEPFUN_API_KEY"]},{id:"cohere",env:["COHERE_API_KEY"]},{id:"neuralwatt",env:["NEURALWATT_API_KEY"]},{id:"gmicloud",env:["GMICLOUD_API_KEY"]},{id:"bothub",env:["BOTHUB_API_KEY"]},{id:"modelis",env:["MODELIS_API_KEY"]},{id:"github-copilot",env:["GITHUB_TOKEN"]},{id:"scnet-token-plan",env:["SCNET_API_KEY"]},{id:"above",env:["ABOVE_API_KEY"]},{id:"xiaomi",env:["XIAOMI_API_KEY"]},{id:"echo",env:["ECHO_API_KEY"]},{id:"xiaomi-token-plan-sgp",env:["XIAOMI_API_KEY"]},{id:"abliteration-ai",env:["ABLIT_KEY"]},{id:"huggingface",env:["HF_TOKEN"]},{id:"trustedrouter",env:["TRUSTEDROUTER_API_KEY"]},{id:"oci",env:["OCI_GENAI_API_KEY"]},{id:"nearai",env:["NEARAI_API_KEY"]},{id:"watsonx",env:["WATSONX_AI_APIKEY","WATSONX_AI_PROJECT_ID"]},{id:"meganova",env:["MEGANOVA_API_KEY"]},{id:"lmstudio",env:["LMSTUDIO_API_KEY"]},{id:"vancine",env:["VANCINE_API_KEY"]},{id:"blueclaw",env:["BLUECLAW_API_KEY"]},{id:"tencent-token-plan",env:["TENCENT_TOKEN_PLAN_API_KEY"]},{id:"unorouter",env:["UNOROUTER_API_KEY"]},{id:"subconscious",env:["SUBCONSCIOUS_API_KEY"]},{id:"novita-ai",env:["NOVITA_API_KEY"]},{id:"inference",env:["INFERENCE_API_KEY"]},{id:"sakana",env:["SAKANA_API_KEY"]},{id:"freemodel",env:["FREEMODEL_API_KEY"]},{id:"hyper",env:["HYPER_API_KEY"]},{id:"alibaba-token-plan",env:["ALIBABA_TOKEN_PLAN_API_KEY"]},{id:"minimax",env:["MINIMAX_API_KEY"]},{id:"reflection",env:["REFLECTION_API_KEY"]},{id:"lynkr",env:["LYNKR_API_KEY"]},{id:"sarvam",env:["SARVAM_API_KEY"]},{id:"google",env:["GOOGLE_API_KEY","GOOGLE_GENERATIVE_AI_API_KEY","GEMINI_API_KEY"]},{id:"nano-gpt",env:["NANO_GPT_API_KEY"]},{id:"stackit",env:["STACKIT_API_KEY"]},{id:"engy",env:["ENGY_API_KEY"]},{id:"zhipuai",env:["ZHIPU_API_KEY"]},{id:"digitalocean",env:["DIGITALOCEAN_ACCESS_TOKEN"]},{id:"venice",env:["VENICE_API_KEY"]},{id:"ollama-cloud",env:["OLLAMA_API_KEY"]},{id:"openai",env:["OPENAI_API_KEY"]},{id:"google-vertex-anthropic",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"longcat",env:["LONGCAT_API_KEY"]},{id:"aihubmix",env:["AIHUBMIX_API_KEY"]},{id:"xai",env:["XAI_API_KEY"]},{id:"pioneer",env:["PIONEER_API_KEY"]},{id:"iteracompute",env:["ITERACOMPUTE_API_KEY"]},{id:"umans-ai",env:["UMANS_AI_API_KEY"]},{id:"neosmith",env:["NEOSMITH_API_KEY"]},{id:"hetzner",env:["HETZNER_API_KEY"]},{id:"modelscope",env:["MODELSCOPE_API_KEY"]},{id:"stepfun-ai",env:["STEPFUN_API_KEY"]},{id:"tempr",env:["TEMPR_API_KEY"]},{id:"prime",env:["PRIME_API_KEY"]},{id:"evroc",env:["EVROC_API_KEY"]},{id:"alibaba-coding-plan",env:["ALIBABA_CODING_PLAN_API_KEY"]},{id:"302ai",env:["302AI_API_KEY"]},{id:"wallaby",env:["WALLABY_API_KEY"]},{id:"amd",env:["AMD_API_KEY"]},{id:"opencode-go",env:["OPENCODE_API_KEY"]},{id:"perplexity",env:["PERPLEXITY_API_KEY"]},{id:"umans-ai-coding-plan",env:["UMANS_AI_CODING_PLAN_API_KEY"]},{id:"vivgrid",env:["VIVGRID_API_KEY"]},{id:"wandb",env:["WANDB_API_KEY"]},{id:"nebius",env:["NEBIUS_API_KEY"]},{id:"kenari",env:["KENARI_API_KEY"]},{id:"google-vertex",env:["GOOGLE_VERTEX_PROJECT","GOOGLE_VERTEX_LOCATION","GOOGLE_APPLICATION_CREDENTIALS"]},{id:"arcee",env:["ARCEE_API_KEY"]},{id:"baseten",env:["BASETEN_API_KEY"]},{id:"ofox",env:["OFOX_API_KEY"]},{id:"openrouter",env:["OPENROUTER_API_KEY"]},{id:"io-net",env:["IOINTELLIGENCE_API_KEY"]},{id:"pareto",env:["PARETO_API_KEY"]},{id:"llmtr",env:["LLMTR_API_KEY"]},{id:"qihang-ai",env:["QIHANG_API_KEY"]},{id:"zai",env:["ZHIPU_API_KEY"]},{id:"cerebras",env:["CEREBRAS_API_KEY"]},{id:"abacus",env:["ABACUS_API_KEY"]},{id:"moark",env:["MOARK_API_KEY"]},{id:"tokengo",env:["TOKENGO_API_KEY"]},{id:"sap-ai-core",env:["AICORE_SERVICE_KEY"]},{id:"thinkingmachines",env:["TINKER_API_KEY"]},{id:"lucidquery",env:["LUCIDQUERY_API_KEY"]},{id:"tensorx",env:["TENSORX_API_KEY"]},{id:"modal",env:["MODAL_PROXY_TOKEN"]},{id:"ai-router",env:["AI_ROUTER_API_KEY"]},{id:"mistral",env:["MISTRAL_API_KEY"]},{id:"empiriolabs",env:["EMPIRIOLABS_API_KEY"]},{id:"moonshotai",env:["MOONSHOT_API_KEY"]},{id:"ai21",env:["AI21_API_KEY"]},{id:"kuae-cloud-coding-plan",env:["KUAE_API_KEY"]},{id:"inceptron",env:["INCEPTRON_API_KEY"]},{id:"wafer.ai",env:["WAFER_API_KEY"]},{id:"cloudflare-ai-gateway",env:["CLOUDFLARE_API_TOKEN","CLOUDFLARE_ACCOUNT_ID","CLOUDFLARE_GATEWAY_ID"]},{id:"minimax-cn",env:["MINIMAX_API_KEY"]},{id:"tencent-coding-plan",env:["TENCENT_CODING_PLAN_API_KEY"]},{id:"snowflake-cortex",env:["SNOWFLAKE_ACCOUNT","SNOWFLAKE_CORTEX_PAT"]},{id:"sambanova",env:["SAMBANOVA_API_KEY"]},{id:"privatemode-ai",env:["PRIVATEMODE_API_KEY"]},{id:"inception",env:["INCEPTION_API_KEY"]},{id:"commandcode",env:["CMD_API_KEY"]},{id:"poolside",env:["POOLSIDE_API_KEY"]},{id:"amazon-bedrock",env:["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION","AWS_BEARER_TOKEN_BEDROCK"]},{id:"cline-pass",env:["CLINE_API_KEY"]},{id:"edenai",env:["EDENAI_API_KEY"]},{id:"aimlapi",env:["AIMLAPI_API_KEY"]},{id:"vultr",env:["VULTR_API_KEY"]},{id:"lowrouter",env:["LOWROUTER_API_KEY"]},{id:"tinfoil",env:["TINFOIL_API_KEY"]},{id:"pendra",env:["PENDRA_API_KEY"]},{id:"inferx",env:["INFERX_API_KEY"]}];function ja(e){if(!e.released)return null;let t=new Date(e.released).getTime();return Number.isNaN(t)?null:t}function MM(e){if(e.provider)return e.provider;let t=e.id.indexOf("/");return t===-1?"kortix":e.id.slice(0,t)}function Hx(e,t){let n=new Map;for(let r of e){let s=t(r),o=n.get(s);o?o.push(r):n.set(s,[r])}return n}function or(e){let t=e.includes("/")?e.slice(e.indexOf("/")+1):e;return t.startsWith("global.")?2:/^(us|eu|jp|apac|au|ca|sa|us-gov)\./.test(t)?1:0}function Vx(e){return e.reduce((t,n)=>{let r=ja(n)??0,s=ja(t)??0;return r!==s?r>s?n:t:or(n.id)>or(t.id)?n:t})}function La(e,t){let n=(t?.now??new Date).getTime(),r=(t?.windowMonths??6)*2630016e3,s=new Set;for(let[,o]of Hx(e,MM)){let a=[...Hx(o,p=>p.family||p.id).values()].map(Vx),l=a.filter(p=>{let d=ja(p);return d!==null&&Math.abs(n-d)<r});for(let p of l.length>0?l:[Vx(a)])s.add(p.id)}return s}function $a(e){let t=e.filter(r=>r.status!=="deprecated"&&r.status!=="beta"&&r.tool_call!==!1),n=t.length>0?t:e;return n.some(r=>or(r.id)>0)?n.filter(r=>or(r.id)>0):n}var zx={id:"platinum",name:"Platinum",env:["PLATINUM_API_KEY"],doc:"https://platinum.dev",api:"https://api.platinum.dev/v1/inference",npm:"@ai-sdk/openai-compatible",models:[]},Yx=[...Wx,{id:zx.id,env:zx.env}],OM={"amazon-bedrock":{methods:[{label:"Bearer token",envVars:["AWS_BEARER_TOKEN_BEDROCK","AWS_REGION"]}]},google:{methods:[{envVars:["GOOGLE_GENERATIVE_AI_API_KEY"]},{envVars:["GOOGLE_API_KEY"]},{envVars:["GEMINI_API_KEY"]}]}};function Jx(e){return`${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}_API_KEY`}var DM=(()=>{let e=new Map;for(let{id:n,env:r}of Yx)r.length===1&&e.set(r[0],[...e.get(r[0])??[],n]);let t=new Map;for(let[n,r]of e){if(r.length<2)continue;let s=[...r].sort((o,i)=>o.length-i.length||o.localeCompare(i));t.set(n,r.find(o=>Jx(o)===n)??s[0])}return t})();function Qx(e){let t=OM[e.id];if(t)return t;let n=e.env??[],r=n.length===1?DM.get(n[0]):void 0;return r&&r!==e.id?{methods:[{envVars:[Jx(e.id)]}]}:{methods:n.length>0?[{envVars:n}]:[]}}var jM=["low","medium","high"];function Xx(e){if(!e)return{temperature:!1,topP:!1};let t=e.reasoning_options?.find(a=>a.type==="effort"),n=e.reasoning_options?.find(a=>a.type==="budget_tokens"),r=t?.values?.length?{values:t.values}:n?{values:[...jM]}:void 0,s=e.temperature===!0,o=e.limit?.output,i=typeof o=="number"&&o>0?{ceiling:o}:void 0;return{reasoningEffort:r,temperature:s,topP:s,maxOutputTokens:i}}var Zx=Yx;var a4=Zx.map(e=>({id:e.id,authRequirement:Qx(e)})),eP=new Set(["kortix"]);function LM(e){let t=Object.fromEntries(Object.entries(e.models??{}).filter(([r])=>r!=="auto"&&r!=="kortix/auto").map(([r,s])=>{if(s.variants&&Object.keys(s.variants).length>0)return[r,s];let o=Xx({id:r,name:s.name,reasoning:s.reasoning,reasoning_options:s.reasoning_options}).reasoningEffort?.values;return o?.length?[r,{...s,variants:Object.fromEntries(o.map(i=>[i,{}]))}]:[r,s]})),n=Object.keys(t)[0];return{default:n?{kortix:n}:{},connected:["kortix"],all:[{id:"kortix",name:"Kortix",source:"gateway",models:t}]}}function $M(e){return e.modelPicker?LM(e.modelPicker):void 0}function UM(e){return"capabilities"in e&&e.capabilities!=null}function Ua(e,t){let n=e.find(r=>r.providerID===t.providerID&&r.modelID===t.modelID);return!!n&&n.enabled!==!1&&n.available!==!1}function FM(e,t){if(!e)return[];let n=Array.isArray(e.all)?e.all:[],r=Array.isArray(e.connected)?e.connected:[],s=[];for(let o of n)if(r.includes(o.id)&&eP.has(o.id))for(let[i,a]of Object.entries(o.models)){if(i==="auto"||i==="kortix/auto")continue;let l;if(UM(a)){let p=a.capabilities;l={reasoning:p.reasoning??!1,vision:p.input?p.input.image??!1:void 0,toolcall:p.toolcall??!1}}else{let p=a.modalities?.input;l={reasoning:a.reasoning??!1,vision:p?p.includes("image"):a.attachment,toolcall:a.tool_call??!1}}s.push({id:Gx({providerID:o.id,modelID:i}),providerID:o.id,providerName:a.provider_name??o.name,modelID:i,modelName:(a.name||i).replace("(latest)","").trim(),variants:a.variants,capabilities:l,contextWindow:a.limit?.context,releaseDate:a.release_date,family:a.family,cost:a.cost?{input:a.cost.input??0,output:a.cost.output??0}:void 0,providerSource:o.source,provider:a.provider,reasoningOptions:a.reasoning_options,description:a.description,openWeights:a.open_weights,lastUpdated:a.last_updated,enabled:a.enabled,free:a.free===!0,available:a.available,availability:a.availability})}return s}function tP(e){return new Map(e.map(t=>[`${t.providerID}:${t.modelID}`,t]))}var rP="kortix",nP="codex";function sP(e){return e.providerID===rP&&!e.modelID.includes("/")}function NM(e,t){if(t)return t;let n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function Zt(e){return sP(e)}function BM(e){return La(e.map(t=>({id:`${t.providerID}:${t.modelID}`,released:t.releaseDate,family:t.family,provider:t.provider??t.providerID})))}function KM(e){let{connectedProviderIds:t}=e,n=e.freeTier??!1,r=BM(e.catalogModels),s=tP(e.catalogModels),o=new Map;for(let i of e.pins??[])o.set(`${i.providerID}:${i.modelID}`,i.visibility);return i=>{let a=`${i.providerID}:${i.modelID}`,l=o.get(a);if(l==="hide")return!1;if(i.providerID===rP){let d=NM(i.modelID,i.provider),g=d===nP?t?.has(nP)??!1:t?.has(d)??!1;if(sP(i))return!n;if(!g)return!1;if(l==="show"||r.has(a))return!0;let m=s.get(a);if(!m?.releaseDate)return Zt(i);try{let f=new Date(m.releaseDate);if(Number.isNaN(f.getTime()))return Zt(i)}catch{return Zt(i)}return!1}if(l==="show"||r.has(a))return!0;let p=s.get(a);if(!p?.releaseDate)return Zt(i);try{let d=new Date(p.releaseDate);if(Number.isNaN(d.getTime()))return Zt(i)}catch{return Zt(i)}return!1}}function qM(e,t){return t.search.trim().length>0||e.providerID==="kortix"||t.selected&&t.selected.providerID===e.providerID&&t.selected.modelID===e.modelID?!0:t.isStoreVisible({providerID:e.providerID,modelID:e.modelID})}function GM(e,t){let r=(t?e?.agentDefaults?.[t]:void 0)??(e?.resolvedForCaller!==void 0?e.resolvedForCaller:e?.projectDefault??e?.accountDefault??(e?.freeTier?void 0:e?.platformDefault));return r?Da(r):void 0}function WM(e){for(let t=(e?.length??0)-1;t>=0;t--){let n=e[t],{provider:r,model:s}=n.model??{};if(n.role==="user"&&r&&s)return{providerID:r,modelID:s}}}var HM=new Set(["explicit","repointed","fallback"]);function VM(e){let t=e?.metadata;if(t?.opencode_model_source!=="fallback")return;let{opencode_model:n,opencode_model_fallback_from:r,opencode_model_fallback_at:s}=t;if(typeof n!="string"||typeof r!="string"||typeof s!="number")return;let o=t.opencode_model_fallback_reason;return{model:sr(n),from:sr(r),reason:typeof o=="string"?o:"other",atMs:s}}function zM(e,t){return!t||(e??-1)>=t.atMs}function YM(e){let t=e.session?Nr(e.session):null,n=t?sr(t):void 0,r=e.session?.metadata;return(HM.has(String(r?.opencode_model_source))||r?.opencode_model_restored===!0?[n,e.lastPromptModel]:[e.lastPromptModel,n]).filter(i=>!!i)}function JM(e){let{models:t,providers:n}=e,r=l=>Ua(t,l),s=l=>l.find(p=>!!p&&r(p)),o=(()=>{if(e.configModel){let l=e.configModel.split("/");if(l.length>=2){let[p,...d]=l,g=d.join("/");if(r({providerID:p,modelID:g}))return{providerID:p,modelID:g}}}for(let l of e.recent??[])if(r(l))return l;if(n){let l=n.default||{},p=Array.isArray(n.all)?n.all:[],d=Array.isArray(n.connected)?n.connected:[],g=p.filter(m=>d.includes(m.id));for(let m of g){let f=l[m.id];if(f){let h={providerID:m.id,modelID:f};if(r(h))return h}for(let h of $a(Object.keys(m.models).map(S=>({id:S})))){let S={providerID:m.id,modelID:h.id};if(r(S))return S}}}})(),i=s(e.picks??[]);return{model:i??s([e.serverDefault,e.globalDefault,e.agentModel,o]),explicit:i,fallback:o}}export{eI as ABORT_REASONS,Dz as ABORT_REASONS_NOT_YET_EMITTED,Za as ACCOUNTS_LIST_UNAVAILABLE_CODE,Ks as ACTIVE_INSTANCE_COOKIE,Xa as ANALYTICS_UNAVAILABLE_CODE,xI as ATTACHMENT_PART_REF_PREFIX,P as ApiError,ie as AuthError,ut as BillingError,O1 as CAPTURE_DEVICE_DEFAULTS,T1 as CAPTURE_EXCLUSION_GROUPS,E1 as CAPTURE_FRAME_INTERVALS_MS,C1 as CAPTURE_LAYERS,M1 as CAPTURE_MAX_HEIGHTS,I1 as CAPTURE_RETENTION_LIMITS,OI as CONNECTION_FAULT_GRACE_MS,hI as CONNECTOR_POLL_FIRST_DELAY_MS,_I as CONNECTOR_POLL_INTERVAL_MS,bI as CONNECTOR_POLL_WINDOW_MS,ER as CONTEXT_TOOLS,hS as COST_MARKUP,xo as ConnectorApprovalPendingError,vr as ConnectorCallError,Po as ConnectorPageLimitError,MR as DEFAULT_CONTEXT_TOOL_TRIGGER_LABELS,IN as DEFAULT_NOTIFICATION_PREFERENCES,cb as DEFAULT_TRANSCRIPT_OPTIONS,gI as DESTRUCTIVE_PHASES,en as FEATURE_DISABLED_CODE,NO as FEATURE_FLAG_KEYS,za as FEATURE_NOT_SUPPORTED_CODE,xt as FILE_VERBS,In as FileExistsError,hn as HeadlessAuthError,Gs as HostBoundaryError,xP as IMPERSONATION_HEADER,TN as INBOX_NOTIFICATION_KINDS,ha as INBOX_OBSERVATION_MAX_MS,xJ as INITIAL_SETTLED_CONNECTION,tI as INSTANCE_SCOPED_ROUTES,_w as KNOWN_TOOL_KINDS,Te as KORTIX_TRANSCRIPT_SCHEMA,wt as KortixMemberError,sw as MAX_PROMPT_ATTACHMENTS_BYTES,ko as MAX_PROMPT_ATTACHMENT_BYTES,Gu as MAX_PROMPT_ATTACHMENT_FILES,dz as MEMORY_VERBS,Ya as MODEL_NOT_SERVABLE_CODE,Gk as NO_GROUP_ACTIVITY_TOOLS,_a as OPTIMISTIC_ABORT_MAX_MS,GJ as OPTIMISTIC_COMPACTION_MAX_MS,fa as OPTIMISTIC_RECEIPT_MAX_MS,B2 as PERSISTED_QUERY_CACHE_VERSION,XC as PLUMBING_TOOLS,lJ as PREVIEW_PROBE_TIMEOUT_MS,Z as PROJECT_ACTIONS,rL as PROJECT_SESSION_NAME_LOOKUP_LIMIT,nL as PROJECT_SESSION_PAGE_DEFAULT_LIMIT,Uw as PROJECT_SESSION_PAGE_MAX_LIMIT,Ja as PROVISION_IN_FLIGHT_CODE,KP as PROVISION_STREAM_UNTERMINATED_CODE,Lo as PublicSessionShareError,lr as REPOSITORY_DISCONNECTED_CODE,K$ as REVIEW_CONTROL_ACTIONS,Vz as RUNTIME_NOT_READY_MARKERS,KN as RUNTIME_PERMISSION_CAPABILITIES,BN as RUNTIME_PERMISSION_REPLIES,kt as RequestTooLargeError,vn as RuntimeNotReadyError,Di as SANDBOX_FS_ROOTS,tt as SANDBOX_PORTS,Qa as SANDBOX_STATE_CHANGE_IN_PROGRESS_CODE,NI as SERVER_COMPACTION_REVALIDATE_MS,ya as SERVER_OBSERVATION_MAX_MS,rQ as SESSION_LIST_STATUS,Ia as SESSION_LOG_FULL_TEXT_INLINE_MAX_BYTES,Se as SESSION_LOG_MINOR,ue as SESSION_LOG_SCHEMA,iQ as SESSION_NOTICE,Wk as STANDALONE_TOOLS,er as STREAM_OBSERVATION_MAX_MS,qs as SandboxNotReadyError,Bt as SessionNotReadyError,Io as SessionStartError,N$ as TRIGGER_CONTROL_ACTIONS,OJ as TURN_END_LEDGER_LAG_MS,yk as TURN_ERROR_CODES,QJ as WAKE_ESCALATION_COOLDOWN_MS,JJ as WAKE_MAX_RESTARTS,YJ as WAKE_NO_PROGRESS_MS,wi as WIRE_ID_BACKDATE_MS,yt as WIRE_ID_CLOCK_TOLERANCE,st as WIRE_ID_TIME_MASK,Pn as WIRE_ID_TIME_SCALE,dv as WIRE_MESSAGE_ID,XM as __getConfigResolver,QM as __setConfigResolver,jz as abortErrorReason,co as acceptAccountInvite,wc as acceptAccountInviteAndLand,ag as acceptEnterpriseOffer,vY as acceptInvite,BP as accountInviteLanding,Im as actReviewItem,Jl as activateConnection,Zl as addComputerToProject,nm as addGroupMembers,Af as addMarketplaceSource,Zm as addRoomPerson,Qm as addRoomSession,ZJ as advanceWakeEscalation,gC as allDescendantIds,J2 as appendPreviewToken,Q_ as approveCaptureDeviceGrant,$_ as approveCaptureEnrollment,rl as approveProjectAccessRequest,NK as approveTask,Pr as archiveProject,zK as assignTicket,gl as attachGroupToProject,hi as authMfa,mi as authUser,U as authenticatedFetch,Rr as authenticatedRequest,aJ as authorizePreviewUrl,c as backendApi,d$ as bindSlackIdentity,g$ as bindTeamsIdentity,vl as brokerProjectSecretRequest,G2 as browserKeyValueStorage,rI as buildInstancePath,mJ as buildPresentationTemplateImageUrl,gJ as buildPresentationTemplatePdfUrl,BS as buildPreviewAuthEndpoint,A2 as buildPublicTemplateUrl,MI as buildRuntimePresentationConversionUrl,Lu as buildSandboxTemplate,kC as buildScrapeFailureResults,EG as buildStaticFileHealthPreviewUrl,IG as buildStaticFileLocalUrl,TG as buildStaticFilePreviewUrl,MA as buildStaticFileServicePath,BX as buildTunnelEventStreamUrl,LG as buildWebProxyUrl,Em as bulkActReviewItems,d0 as bulkDeletePolicies,g0 as bulkImportPolicies,oa as burstSummary,nT as burstSummaryLabel,Xb as burstWorkLabel,It as callConnector,Hw as canManageBilling,zL as canOfferTopup,LU as cancelAccountDeletion,bc as cancelAccountInvite,gY as cancelSandbox,GY as cancelSandboxUpdate,eg as cancelScheduledChange,Qd as cancelSubscription,F1 as captureHealthBucket,ok as changeRequestControlsFrom,c2 as checkAccessEmail,VD as checkMcpServerSignIn,uH as childMapByParent,QY as claimComputer,YA as claimNext,ZL as claimPerSeatBilling,qp as claimWarmProjectSession,Lb as classifyPart,II as classifyPreviewProbeStatus,bv as classifyPtyClose,jE as classifySessionLogMessage,Ji as classifyTurn,vH as cleanErrorMessage,EH as cleanResultSnippet,rz as cleanWorkerOutput,tc as clearImpersonationSession,bM as clearKortixAppViewerCache,Od as clearModelDefault,Ej as clearSessionFresh,cp as closeChangeRequest,Pq as closeMilestone,yH as collectTurnParts,JK as commentTicket,pp as commitSessionChanges,HJ as compactionExpiryAtMs,oV as compactionTurnInfo,Zi as compareForDisplayAt,lH as compareMessagesForDisplay,W1 as compareSemver,JA as completeInFlight,_g as completeSlackInstall,bg as completeTeamsInstall,qx as composerSelectableAgents,mS as computeStatusFromPart,sg as configureAutoTopup,Xs as configureKortix,Yd as confirmCheckoutSession,Ag as connectEmail,fg as connectSlack,h$ as connectTelegram,SJ as connectionFromHealth,bJ as connectionIsFaulted,OD as connectionSharedWithEveryone,XP as connectorConnect,ZP as connectorFinalize,M2 as connectorHeadline,cg as contactEnterpriseSales,HH as contextLabelForTool,kW as contextToolSummary,vW as contextToolTrigger,XU as convertPresentationToGoogleSlides,fJ as convertRuntimePresentation,bs as copyFile,ug as costExportUrl,jJ as countLiveInboxPrompts,j$ as countReviewItemsBySegment,cc as createAccount,ff as createAccountAuditWebhook,Ol as createAccountSecretResource,rf as createAccountToken,Tf as createApp,$f as createAppAccessSession,Ff as createAppDeployment,Mf as createAppToken,ty as createAppVolume,oy as createAppVolumeSnapshot,VH as createArtifactKind,Pm as createAssignment,pU as createAuditWebhook,TY as createBackup,D_ as createCaptureEnrollmentToken,zd as createCheckoutSession,gu as createConnector,T2 as createConnectorLinkInfoCache,_s as createFile,Gg as createGatewayKey,Xg as createGroup,aM as createHttpSessionSyncController,zY as createInstance,WA as createKortix,xh as createKortixPty,bi as createKortixSession,MF as createMarketplaceInstallSession,Sq as createMilestone,KM as createModelVisibility,hm as createOAuthClient,XL as createPerSeatCheckout,q2 as createPersistedQueryCache,l0 as createPolicy,Jd as createPortalSession,Dc as createProject,iq as createProjectAgent,lf as createProjectCliToken,jc as createProjectRepo,hl as createProjectResourceGrant,jt as createProjectSession,Bc as createProjectSkill,dd as createProjectTrigger,S_ as createPromptAttachmentController,lm as createRole,Wm as createRoom,KX as createSSEStream,iY as createSandbox,Om as createSandboxShare,Ou as createSandboxTemplate,Bj as createSavedCopyStore,w0 as createScimToken,rU as createServiceAccountApi,$r as createSessionPrompt,Np as createSessionPublicShare,VA as createSessionQueue,Um as createSessionReminder,K0 as createSsoGroupMapping,$K as createTask,WK as createTicket,qX as createTunnelEventStream,xX as createWarmSessionPool,Ap as currentSavedCopyStore,kc as declineAccountInvite,AY as declineInvite,$U as deleteAccountImmediately,Ll as deleteAccountSecretResource,Ef as deleteApp,Wf as deleteAppDeployment,gU as deleteAuditWebhook,EY as deleteBackup,hu as deleteConnector,wu as deleteConnectorCredential,Tq as deleteCredential,Zr as deleteCustomLlmProvider,uN as deleteDriveFile,bh as deleteEnv,Wt as deleteFile,Kg as deleteGatewayBudget,Zc as deleteGitHubInstallation,em as deleteGroup,YY as deleteInstance,fq as deleteKortixProject,kq as deleteMilestone,Sm as deleteOAuthClient,Il as deletePersonalProjectSecret,p0 as deletePolicy,cq as deleteProjectAgent,Rl as deleteProjectProviderOAuth,_l as deleteProjectResourceGrant,wr as deleteProjectSecret,ed as deleteProjectSession,md as deleteProjectTrigger,ln as deletePromptAttachment,dm as deleteRole,ju as deleteSandboxTemplate,oU as deleteServiceAccountApi,zp as deleteSessionPrompt,Uo as deleteSessionReminder,Km as deleteSessionReminders,q0 as deleteSsoGroupMapping,N0 as deleteSsoProvider,BK as deleteTask,QK as deleteTicket,X_ as denyCaptureDeviceGrant,U_ as denyCaptureEnrollment,Pc as describeAccountInvite,yo as describeConnectorTool,Qf as destroyAppMachine,ry as destroyAppVolume,fl as detachGroupFromProject,CA as detectLocalhostUrls,lQ as directSubsessions,sU as disableServiceAccountApi,Rg as disconnectEmail,F2 as disconnectGitHubApp,xg as disconnectSlack,b$ as disconnectTelegram,$D as discoverConnectionOAuth2,UD as discoverConnectionOAuth2Resource,mu as discoverConnectorAuth,uY as discoverLocalSandbox,rN as dismissDriveConflict,k2 as downloadAccountAudit,oN as downloadDriveFile,qq as dropClientForUrl,Hq as dropPublicClientForUrl,eR as editQueued,Yp as editSessionPrompt,zA as enqueue,sq as ensurePmSession,TI as ensurePreviewSessionCookie,DD as ensureProjectConnectorConnection,dI as ensureSandbox,Kp as ensureWarmProjectSession,hv as env,pi as exchangeCode,Zf as execInApp,gf as exportAccountAudit,Pe as extractGatewayErrorDetails,Qn as extractInstanceRoute,AT as extractSkillBaseDir,Az as extractSkillContent,wT as extractSkillFiles,oz as extractWorkerPreview,QA as failInFlight,CV as fallbackBusyRowAfterTurnId,Vn as familyForTool,Ka as featureDisabledKey,qy as featureFlags,YL as fetchAccountStateWithToken,jO as fetchAccountsWithToken,z2 as fetchAttachmentPart,c$ as fetchCostExportCsv,$x as fetchKortixAppViewer,Ku as fetchProjectArchive,hj as fetchProjectFileRaw,YO as fetchProjectsForAccountWithToken,By as fetchSessionAttachment,eA as fileDownloadRequest,lz as filePhase,cz as fileVerb,gA as files,qo as finalizeAppArtifact,f2 as finalizeConnectorSetupLink,oL as findActiveTranscriptShare,ys as findFiles,hH as findLastTextPart,lB as findSessionAttachments,hs as findText,hd as fireProjectTrigger,Mu as fixSandboxWithAgent,FM as flattenModels,gV as flattenThought,ay as forkAppVolume,Ga as formatBillingErrorForUI,qV as formatCost,yS as formatDuration,AH as formatJsonFailureOutput,yV as formatMessageDay,hV as formatMessageExact,Yz as formatOpenCodeRuntimeError,IH as formatRawOutput,pI as formatRuntimeError,GV as formatTokens,aR as formatTranscript,MV as freshSendHint,HA as generateSessionId,lc as getAccount,dL as getAccountAutomations,pc as getAccountBranding,DU as getAccountDeletionStatus,Bd as getAccountState,Kd as getAccountStateMinimal,oI as getActiveInstanceIdFromCookie,WU as getAdminProviderAnalytics,KU as getAdminProviderDistribution,VU as getAdminProviderFallback,UU as getAdminRole,NR as getAgentCardLabel,NL as getAgentConfig,lq as getAgentPersona,BY as getAllVersions,bH as getAnsweredQuestionParts,Bo as getApp,Df as getAppAccess,Of as getAppAuthEnv,Bf as getAppDeployment,Kf as getAppDeploymentLogs,CF as getApprovalLink,sn as getAuthToken,AD as getAuthTokenWithRetry,rg as getAutoTopupSettings,QL as getAutoTopupSetupStatus,Wd as getBillingCreditBreakdown,Vd as getBillingTierConfigurations,Gd as getBillingTransactionsSummary,Hd as getBillingUsageHistory,Y_ as getCaptureAssetUrl,z_ as getCaptureChunkMedia,W_ as getCaptureDays,J_ as getCaptureDeviceGrant,V_ as getCaptureFrame,F_ as getCapturePolicy,B_ as getCaptureStorage,q_ as getCaptureTimeline,G_ as getCaptureTimelineItems,Z_ as getCaptureWorkspace,rp as getChangeRequest,sp as getChangeRequestDiff,op as getChangeRequestMergePreview,BW as getChildSessionError,Es as getChildSessionId,KW as getChildSessionToolParts,ht as getClient,He as getClientForUrl,xu as getConnectStatus,LD as getConnectionOAuth2Application,qD as getConnectionOAuth2Status,GD as getConnectionPolicies,on as getConnectorCatalog,uu as getConnectorConfig,cu as getConnectorPolicies,g2 as getConnectorSetupLink,a$ as getCostSummary,sI as getCurrentInstanceIdFromPathname,Fz as getCurrentInstanceIdFromWindow,Jh as getCurrentProject,Ud as getDefaultAccountState,WW as getDiagnostics,FR as getDirectory,So as getDiscoverConnector,QD as getDiscoverIntegration,cy as getDriveFileUrl,kg as getEmailInstallation,vg as getEmailMode,xU as getEnterpriseDemo,fs as getFileStatus,Cb as getFileWithDir,UR as getFilename,XF as getFolderAccess,mI as getFullChangelog,$g as getGatewayBreakdown,Ng as getGatewayBudgets,Fg as getGatewayErrors,qg as getGatewayKeys,Dg as getGatewayLog,jg as getGatewayOverview,Tg as getGatewayRoutingPolicy,Lg as getGatewaySeries,Ug as getGatewaySessions,j2 as getGitHubAppStatus,Wc as getGitHubInstallation,QU as getGoogleAuthUrl,Qg as getGroup,FW as getHiddenToolParts,kP as getImpersonationSession,kY as getInvite,VY as getJustavpsServerTypes,dq as getKortixProject,gq as getKortixProjectBySession,kh as getKortixPtyWebSocketUrl,NY as getLatestSandboxVersion,S2 as getMaintenanceConfig,el as getManagedGitBackend,WO as getManagedGitStatus,wf as getMarketplaceCatalogItem,kf as getMarketplaceCatalogItemFile,C0 as getMfaRequired,_q as getMilestone,ob as getMobileClientPolicy,Ed as getModelDefaults,rb as getMyCaptureFrame,nb as getMyCaptureTimeline,my as getNotificationPreferences,ym as getOAuthClient,p2 as getOAuthConsentRequest,Wz as getOpenCodeConfigInvalidError,LW as getPartText,Q0 as getPatPolicy,HW as getPermissionForTool,Ct as getProject,uq as getProjectActivity,Xu as getProjectCommit,Zu as getProjectCommitDiff,_r as getProjectDetail,QF as getProjectDrive,ep as getProjectFileHistory,rD as getProjectGitConnectionState,Oc as getProjectGitToken,br as getProjectLlmCatalog,KO as getProjectLlmCatalogProviders,Yr as getProjectModelAccess,Sr as getProjectModelPicker,GO as getProjectQuota,Ar as getProjectSandboxHealth,HO as getProjectSandboxProviderTransition,Dr as getProjectSession,rd as getProjectSessionConfigState,id as getProjectSessionScope,tg as getProrationPreview,sY as getProviders,MG as getProxyBaseUrl,Wq as getPublicClientForUrl,i2 as getPublicMarketplaceItem,a2 as getPublicMarketplaceItemFile,aF as getPublicSessionShare,cF as getPublicSessionShareMessages,_2 as getPublicShareByToken,R2 as getPublicTemplate,VW as getQuestionForTool,C$ as getReferralCode,E$ as getReferralStats,WV as getRetryInfo,HV as getRetryMessage,Cm as getReviewItem,Rm as getReviewSummary,am as getRolePermissions,cm as getRoleUsage,Hm as getRoom,pa as getRuntimeConfigInvalidError,DY as getSSHConnection,oY as getSandbox,aY as getSandboxById,Zz as getSandboxPortUrl,XY as getSandboxProvisionStatus,ZY as getSandboxProvisionStreamUrl,FY as getSandboxUpdateStatus,OS as getSandboxUrl,Fe as getSandboxUrlForExternalId,y2 as getSecretSetupLink,ji as getServerHealth,Mq as getServiceLogs,Gp as getSessionAudit,KV as getSessionCost,Hr as getSessionCostRecord,gk as getSessionDrives,r_ as getSessionHealth,Hp as getSessionLogPage,ld as getSessionMessageAuthors,ud as getSessionModelUsage,iL as getSessionOpenBundle,E0 as getSessionOversight,Op as getSessionParticipants,V0 as getSessionPolicy,Up as getSessionPreviewCandidates,Nl as getSessionProviderSecretPool,Wp as getSessionTranscript,jr as getSessionTranscriptSync,Lr as getSessionTurn,Dp as getSessionWatch,ez as getShellModePart,Pg as getSlackChannelFile,mg as getSlackInstallation,Sg as getSlackManifest,yg as getSlackMode,L0 as getSsoProvider,OA as getStaticFileHealthPath,go as getSupabaseAccessToken,VP as getSupabaseAccessTokenWithRetry,DK as getTask,LK as getTaskStatus,y$ as getTelegramInstallation,jF as getTemplate,qK as getTicket,qW as getToolInfo,Vi as getToolPrimaryArg,cR as getTranscriptFilename,ca as getTurnCost,FV as getTurnError,BV as getTurnErrorDetails,NV as getTurnErrorRawText,fS as getTurnStatus,lg as getUsageRollup,P2 as getUserRolesWithToken,tp as getVersionDiff,yy as getWebPushPublicKey,$V as getWorkingState,$l as grantAccountSecretResource,SY as grantSandboxProjectAccess,KL as grantSecretToAgent,fH as groupMessagesIntoTurns,lS as groupShowSegments,eS as groupSteps,VV as hasDiffs,CG as hasLocalhostUrls,EA as hasPreviewTarget,Kb as hasRetryingAssistantTurn,Kv as heartbeatGapEvent,Xp as holdSessionPrompts,Yg as humanizeReviewActionPath,Cs as humanizeSearchQuery,Ob as humanizeToolName,nc as impersonationHeaders,U0 as importSsoProviderFromMetadata,DJ as inboxObservationSupersedes,HS as initialWakeEscalationState,Ie as inputPath,LF as installTemplate,Jp as interruptSessionPrompt,mo as invalidateTokenCache,hc as inviteAccountMember,cl as inviteProjectMember,Ec as inviteRepoCollaborator,Bs as isAbortError,CP as isAdminBypassEnabled,EW as isAgentPart,vA as isAppRouteUrl,$W as isAttachment,PI as isAttachmentPartRef,tn as isAuthFailure,qa as isBillingError,MW as isCompactionPart,Zs as isConfigured,wW as isContextTool,UY as isDestructivePhase,jx as isEmptyConversation,ei as isEmptyShowPart,kH as isErrorOutput,FG as isExternalUrl,Ba as isFeatureDisabledError,Tb as isFilePart,PP as isImpersonationSessionLive,$z as isInstanceDetailPath,nI as isInstanceScopedAppPath,jG as isInternalLocalhostUrl,Uy as isInvisibleActivityPart,pD as isInviteSent,LV as isLastUserMessage,GI as isLegacyMigratedSession,BO as isManagedGithubProject,$y as isNoGroupActivityTool,Ua as isOfferedModel,Hz as isOpenCodeConfigInvalidError,Aw as isPaintableSavedCopy,DW as isPatchPart,K2 as isPersistableQueryKey,DG as isPreviewUrl,DA as isProxiableLocalhostUrl,Ly as isQuestionTool,we as isReasoningPart,pP as isRepositoryDisconnectedError,yC as isRetryableTurnError,iI as isRuntimeConfigInvalidError,lI as isRuntimeNotReadyResponse,n_ as isRuntimeReady,zz as isRuntimeStartingError,Zn as isSandboxNotReadyError,oi as isSelectableAgent,Qh as isServerReachable,cB as isSessionAttachmentRef,gp as isSessionFresh,FE as isSessionLogRestoreNote,PL as isSessionStartError,ZN as isShellActivityTool,xT as isShellMode,sz as isShortOutput,FN as isShowContentUnavailable,es as isShowPayloadEmpty,OW as isSnapshotPart,Fy as isStandaloneActivityTool,jW as isStepPart,Ws as isSubdomainPreviewUrl,Je as isTextPart,te as isToolPart,NW as isToolPartHidden,xy as isTurnErrorCode,Nh as isUnderSandboxRoot,UG as isWebProxyUrl,mv as isWireIdAheadOf,xM as kortixAppViewerToken,wM as kortixBinding,wv as kortixPty,Ux as kortixToken,WM as latestPromptModel,Rc as leaveAccount,M_ as linkCaptureDevice,Qc as linkGitHubInstallation,qc as linkRepository,pf as listAccountAudit,mf as listAccountAuditWebhooks,_c as listAccountInvites,yc as listAccountMembers,r0 as listAccountResourceGrants,Ml as listAccountSecretResources,Y0 as listAccountSessions,nf as listAccountTokens,ac as listAccounts,h0 as listActions,qU as listAdminSandboxes,om as listAgentIdentities,Wl as listAllConnections,jf as listAppAgents,Nf as listAppDeployments,Vf as listAppMachines,sy as listAppVolumeSnapshots,ey as listAppVolumes,Cf as listApps,xm as listAssignments,mU as listAuditEvents,uU as listAuditWebhooks,CY as listBackups,qd as listBillingTransactions,I_ as listCaptureDevices,O_ as listCaptureEnrollmentTokens,L_ as listCaptureEnrollments,np as listChangeRequests,S$ as listChannelBindings,XK as listColumns,YD as listConnectSections,zD as listConnectToolkits,Gl as listConnections,ho as listConnectorAccounts,fu as listConnectorMoves,fo as listConnectorTools,ru as listConnectors,i$ as listCostByProject,Aq as listCredentialEvents,vq as listCredentials,Qr as listCustomLlmProviders,bo as listDiscoverConnectors,JD as listDiscoverIntegrations,Su as listDiscoverSections,nN as listDriveConflicts,sN as listDriveFiles,uk as listDriveFolder,pN as listDriveVersions,hh as listEnv,Pf as listFeaturedMarketplaces,eq as listFields,On as listFiles,tN as listFolderPrincipals,Og as listGatewayLogs,Hc as listGitHubInstallations,zc as listGitHubRepositories,Yc as listGitHubRepositoryBranches,tm as listGroupMembers,J$ as listGroupProjectGrants,Jg as listGroups,mq as listKortixProjectSessions,pq as listKortixProjects,Sh as listKortixPty,Vc as listLinkableGitHubInstallations,tl as listManagedGitRepositories,Sf as listMarketplaceCatalogItems,vf as listMarketplaceSources,xf as listMarketplaces,Q$ as listMemberGroups,X$ as listMemberProjectAccess,bq as listMilestoneEvents,hq as listMilestones,xc as listMyAccountInvites,dy as listNotifications,fm as listOAuthClients,of as listOAuthGrants,bl as listPendingApprovals,ll as listPendingProjectInvites,km as listPermissions,_u as listPipedreamApps,bu as listPipedreamSections,c0 as listPolicies,ol as listProjectAccess,nl as listProjectAccessRequests,im as listProjectAgentIdentities,oq as listProjectAgents,df as listProjectAudit,Ju as listProjectBranches,cf as listProjectCliTokens,Qu as listProjectCommits,Fu as listProjectDirectory,Uu as listProjectFiles,dl as listProjectGroupGrants,Ru as listProjectPolicies,Al as listProjectProviderOAuth,qm as listProjectReminders,yl as listProjectResourceGrants,Tu as listProjectSandboxTemplates,$u as listProjectSandboxes,Pl as listProjectSecrets,Dt as listProjectSessions,Ep as listProjectSessionsPage,Iu as listProjectSnapshots,Pd as listProjectTriggerEventApps,xd as listProjectTriggerEventTypes,bd as listProjectTriggerRuns,pd as listProjectTriggers,Rt as listProjects,Ic as listProjectsForAccount,s2 as listPublicMarketplaceItems,o2 as listPublicMarketplaces,M$ as listReferrals,Am as listReviewItems,sm as listRoles,zm as listRoomMessages,tf as listRoomPeople,Gm as listRooms,bY as listSandboxProjectMembers,Mm as listSandboxShares,lY as listSandboxes,P0 as listScimTokens,nU as listServiceAccountsApi,Eq as listServiceTemplates,Iq as listServices,HD as listSessionConnectRequests,pg as listSessionCosts,gN as listSessionDrives,Vp as listSessionPrompts,Bl as listSessionProviderSecretPools,Fp as listSessionPublicShares,$m as listSessionReminders,Sl as listSessionsNeedingInput,_F as listSignedInDevices,B0 as listSsoGroupMappings,jK as listTaskEvents,OK as listTasks,nq as listTemplates,GK as listTicketEvents,KK as listTickets,_d as listTriggerRuns,iM as loadHttpSessionHistory,ft as loadPreviewUrlTemplate,Gb as looksLikeError,UH as looksLikeHtml,TH as looksLikeJsonPayload,cN as makeDriveFolder,$$ as mapApiReviewItem,JY as markInstanceError,gy as markNotificationsRead,Jm as markRoomRead,Mr as markSessionFresh,dh as maxWireIdClock,gz as memoryRelPath,tS as mergeBurstSteps,ap as mergeChangeRequest,fV as messageCreatedAt,aT as messageTime,HU as migrateAdminSandboxProvider,ki as mintWireMessageId,mh as mintWireMessageIdAbove,$n as mkdir,qM as modelInDefaultView,sr as modelRefToKey,yu as moveConnector,lN as moveDriveFile,Qb as narrateFailedStep,Us as narrateStep,$s as narrationToolName,qv as narrowChatEvent,fv as newestWireIdClock,E2 as nextConnectorPollDelay,he as normalizeActivityToolName,Kz as normalizeAppPathname,j1 as normalizeCaptureAppId,D1 as normalizeCaptureDomain,NG as normalizeExternalInput,ee as normalizeName,Mb as normalizeToolName,VI as notifyHostSignal,ip as openChangeRequest,Ti as openEventStream,v2 as openStressTestStream,Au as paginateConnector,ur as parseBillingError,MH as parseEmbeddedFailure,gB as parseFlagOverride,Wb as parseJsonFailure,ws as parseLocalhostUrl,mz as parseMemoryView,Gz as parseOpenCodeErrorPayload,bz as parsePresentationOutput,t_ as parseProxyHop,AS as parseQuestionAnswersFromOutput,wz as parseReadOutput,MS as parseRuntimeErrorPayload,wC as parseScrapeInputUrls,vC as parseScrapeOutput,d_ as parseSubdomainUrl,iz as parseTaskRows,$G as parseWebProxyUrl,Vb as parseWebSearchOutput,ea as partOutcome,yq as patchKortixProject,hz as patchVerb,$M as pickerProviderList,du as pipedreamConnect,tu as pipedreamConnectConnection,ku as pipedreamFinalize,nu as pipedreamFinalizeConnection,I as platformConfig,KD as pollConnectionOAuth2DeviceAuthorization,uo as pollProjectProviderOAuth,Ym as postRoomMessage,og as previewBillingPlan,Mg as previewGatewayRoute,T0 as previewMfaRequired,m$ as previewSlackIdentity,f$ as previewTeamsIdentity,gm as probeEffectivePermission,mm as probeEffectivePermissions,uJ as probePreviewPort,qu as projectArchiveRequest,WJ as projectCompacting,IM as projectConfigAgentsToOpenCodeAgents,Kx as projectConfigAgentsToRuntimeAgents,_J as projectSessionConnection,uQ as projectSessionForRuntimeId,Rd as projectSessionStartSeed,$J as projectWorking,Lc as provisionProject,qO as provisionProjectStream,JO as provisionProjectWithToken,u_ as proxyLocalhostUrl,OG as proxyUrlToInternal,ng as purchaseCredits,jD as putConnectionOAuth2Application,Xr as putCustomLlmProvider,Rs as rawErrorText,mY as reactivateSandbox,Xd as reactivateSubscription,jn as readBlob,iN as readDriveFile,Dn as readFile,Oa as readKortixMember,Bu as readProjectFile,_M as readSavedSessionCopy,ia as reasoningIsRunning,Eu as rebuildProjectSnapshot,Hl as reconcileConnection,Vl as reconcileMemberConnection,Dq as reconcileServices,u2 as recordPlatformLogout,ta as recoverLinkResults,td as recoverProjectSession,T$ as refreshReferralCode,_n as refreshSession,Ko as registerAppArtifact,FD as registerConnectionOAuth2Client,ly as registerDeviceToken,jq as registerService,hy as registerWebPushSubscription,sl as rejectProjectAccessRequest,GW as relativizePath,py as releaseDeviceToken,sd as reloadProjectSessionConfig,od as reloadProjectSessionConfigStream,hf as removeAccountAuditWebhook,mc as removeAccountBrandingAsset,vc as removeAccountMember,rm as removeGroupMember,wh as removeKortixPty,Rf as removeMarketplaceSource,Kc as removeProjectSkill,ZA as removeQueued,ef as removeRoomPerson,Xm as removeRoomSession,Xl as renameConnection,xs as renameFile,cY as renameSandbox,lp as reopenChangeRequest,wq as reopenMilestone,tR as reorderQueued,ZK as replaceColumns,tq as replaceFields,Gc as replaceProjectRepository,rq as replaceTemplates,Sd as replayTriggerRun,dP as repositoryDisconnectedReason,jU as requestAccountDeletion,up as requestChangesOnChangeRequest,uD as requestProjectAccess,bf as requestProjectConnector,_f as requestProjectSecret,JL as requestTopUp,kM as requireKortixMember,Sc as resendAccountInvite,pl as resendPendingProjectInvite,fc as resetAccountBranding,Gq as resetClient,Eg as resetGatewayRoutingPolicy,di as resetPassword,Vq as resetPublicClient,qY as resetSandboxUpdateStatus,xl as resolveApproval,TM as resolveComposerAgent,JM as resolveComposerModel,I2 as resolveConnectorStart,GM as resolveModelDefault,sL as resolvePublicShareUrl,FH as resolveScrapeResults,gS as resolveWorkingTurn,VL as resolvedPlan,Jf as restartAppMachine,Ur as restartProjectSession,pY as restartSandbox,iy as restoreAppVolume,IY as restoreBackup,dN as restoreDriveVersion,nd as restoreProjectSession,jl as retryAccountSecretResource,XA as retryFailed,Qp as retrySessionPrompt,Cq as revealCredential,zg as reviewItemTarget,Yw as reviewSegmentForStatus,q$ as reviewVerdictAllowed,L$ as reviewVerdictForStatus,Ul as revokeAccountSecretResourceGrant,J0 as revokeAccountSession,sf as revokeAccountToken,wm as revokeAssignment,E_ as revokeCaptureDevice,j_ as revokeCaptureEnrollmentToken,Yl as revokeConnection,Wg as revokeGatewayKey,af as revokeOAuthGrant,ul as revokePendingProjectInvite,al as revokeProjectAccess,uf as revokeProjectCliToken,xY as revokeSandboxProjectAccess,Dm as revokeSandboxShare,k0 as revokeScimToken,Bp as revokeSessionPublicShare,bt as rewriteLocalhostUrl,Hf as rollbackApp,WI as rootRuntimeSession,Dl as rotateAccountSecretResource,bm as rotateOAuthClientSecret,wo as runConnector,Hg as runGatewayPlayground,fD as runProjectProviderOAuthFlow,Fm as runSessionReminder,Sa as runtimeSessionsOf,fA as runtimeSupports,Pv as sanitizePtyChunk,Jc as saveGitHubInstallation,Dx as savedCopyEmptyRoot,Xf as scaleApp,Zd as scheduleDowngrade,H_ as searchCapture,ql as searchConnectorTools,tb as searchMyCapture,Nu as searchProjectFiles,aS as segmentTurn,yB as selectableProjectAgents,ci as sendMagicLink,O$ as sendReferralEmails,VJ as serverCompactionRevalidateAtMs,Oq as serviceAction,oQ as sessionConnectionLabel,sQ as sessionListStatus,RE as sessionLogActivityText,DE as sessionLogAnsweredQuestionCall,IE as sessionLogBurstRunning,AE as sessionLogBurstSteps,CE as sessionLogBurstSummary,TE as sessionLogBurstWorkLabel,oE as sessionLogCallStatus,HE as sessionLogFullTextAction,VE as sessionLogFullTextPlan,NE as sessionLogHarnessSwitches,tE as sessionLogOfV1Rows,EE as sessionLogOpenCall,iE as sessionLogPromptMessage,qE as sessionLogReferencedTexts,KE as sessionLogRestoreNotice,gx as sessionLogRetrying,OE as sessionLogShowGroupCall,$E as sessionLogThreadMetrics,PE as sessionLogTurnSegments,Ra as sessionLogTurns,zE as sessionLogWithFullTexts,YM as sessionModelCandidates,VM as sessionModelFallback,Nr as sessionModelPin,tL as sessionParentId,zM as sessionPickStands,cL as sessionPromptActions,wL as sessionStartKey,gL as setAccountAutomationsPaused,Fl as setAccountSecretResourceAccess,Nz as setActiveInstanceCookie,RP as setAdminBypass,GU as setAdminProviderDistribution,zU as setAdminProviderFallback,jd as setAgentScope,ig as setBillingPlan,vD as setBootstrapAuthToken,kD as setCachedAuthToken,eb as setCaptureEnabled,N_ as setCapturePolicy,K_ as setCaptureStorage,WD as setConnectionPolicies,iu as setConnectorAuthorizationStrategy,Pu as setConnectorCredential,ou as setConnectorCredentialMode,pu as setConnectorName,lu as setConnectorPolicies,XD as setConnectorSecretBinding,au as setConnectorSensitive,Ql as setDefaultConnection,PU as setEnterpriseDemo,_h as setEnv,Bg as setGatewayBudget,Ig as setGatewayRoutingPolicy,$2 as setGitHubAppFromExisting,U2 as setGitHubAppPat,cO as setImpersonationSession,x2 as setMaintenanceConfig,_0 as setMemberSuperAdmin,I0 as setMfaRequired,Md as setModelDefault,Tl as setPersonalProjectSecret,Jr as setProjectModelAccess,IL as setProjectModelEnablement,Nc as setProjectOnboardingComplete,zO as setProjectOnboardingProfile,Cu as setProjectPolicies,kl as setProjectSecretStrategy,cd as setProjectSessionModel,ad as setProjectSessionScope,Mp as setProjectSessionSharing,fd as setProjectTriggersActivation,Kj as setSavedCopyStore,$p as setSessionArchived,M0 as setSessionOversight,Lp as setSessionPinned,Kl as setSessionProviderSecretPool,jp as setSessionWatch,_$ as setTelegramAllowedUsers,PJ as settleSessionConnection,OY as setupSSH,eu as shareConnection,ZF as shareFolder,eB as shellActivityGroupLabel,TS as shellExitCode,AP as shouldAttachImpersonation,UV as shouldHideResponsePart,Kn as shouldShowToolPart,RV as shouldSuppressWorkingTurnBusy,uS as showGroupItems,pS as showTurnBusyIndicator,ai as signInWithPassword,ui as signInWithProvider,yi as signInWithSso,_i as signOut,bF as signOutDevice,ii as signUp,Cz as skillDocumentPath,Rz as skillInputDir,pH as sortSessions,kE as splitSessionLogTurnWork,wS as splitTurnWork,UW as splitUserParts,qf as startApp,zf as startAppMachine,ND as startConnectionOAuth2Authorization,BD as startConnectionOAuth2DeviceAuthorization,m2 as startConnectorSetupLink,L2 as startGitHubAppManifest,lo as startProjectProviderOAuth,mt as startProjectSession,Td as startProjectSessionOrThrow,b2 as startSessionWithToken,FK as startTask,zn as stepLabel,Gf as stopApp,Yf as stopAppMachine,Fr as stopProjectSession,dY as stopSandbox,Xc as storeGitHubUserToken,Ib as stripAnsi,Uz as stripInstancePrefix,pe as stripTrailingSlashes,LE as subAgentCalls,l2 as submitAccessRequest,w2 as submitDemoRequest,d2 as submitOAuthConsent,Tm as submitReviewItem,h2 as submitSecretSetupLink,lO as subscribeToImpersonation,CO as supabaseClient,su as syncConnectors,e$ as syncSubscription,zq as systemReload,_t as toDaemonPath,Bz as toInstanceAwarePath,jA as toInternalUrl,Mn as toSandboxAbsolutePath,jb as toToolView,Bh as toWorkspaceRelative,cs as toolCallBlock,qk as toolCallError,Nk as toolCallMetadata,Kk as toolCallRawOutput,Bk as toolCallStatus,zi as toolInfo,ce as toolKind,YT as toolViewModel,B$ as triggerControlsFrom,KY as triggerSandboxUpdate,_v as triggersRequest,UI as turnEndCause,KJ as turnEndNotice,_H as turnHasSteps,TV as turnIsConfirmedActive,IV as turnRendersQueued,aQ as turnRetryLabel,YK as unassignTicket,uy as unregisterDeviceToken,_y as unregisterWebPushSubscription,eN as unshareFolder,Bb as untimedAnchorOf,_e as unwrapError,yf as updateAccountAuditWebhook,dc as updateAccountBranding,Ac as updateAccountMemberRole,uc as updateAccountName,BL as updateAgentConfig,If as updateApp,Lf as updateAppAccess,ny as updateAppVolume,dU as updateAuditWebhook,dp as updateChangeRequest,x$ as updateChannelBinding,zl as updateConnectionCredential,Cg as updateEmailPolicy,Uc as updateExperimentalFeature,$c as updateFeatureFlag,Zg as updateGroup,Ph as updateKortixPty,xq as updateMilestone,fy as updateNotificationPreferences,_m as updateOAuthClient,gi as updatePassword,X0 as updatePatPolicy,u0 as updatePolicy,xr as updateProject,il as updateProjectAccess,aq as updateProjectAgent,Ld as updateProjectDefaultAgent,ml as updateProjectGroupGrant,Fc as updateProjectSandboxProvider,Zp as updateProjectSession,gd as updateProjectTrigger,um as updateRole,pm as updateRolePermissions,Vm as updateRoom,Du as updateSandboxTemplate,z0 as updateSessionPolicy,$o as updateSessionReminder,Bm as updateSessionReminders,UK as updateTask,VO as updateTemplateWarmPool,HK as updateTicket,VK as updateTicketStatus,fi as updateUserMetadata,gc as uploadAccountBrandingAsset,Uf as uploadAppArtifactArchive,_o as uploadConnectorAttachment,aN as uploadDriveFile,Ln as uploadFile,cA as uploadNativeFile,Er as uploadPromptAttachment,Ny as uploadSessionAttachment,wg as uploadSlackChannelFile,Cn as uploadTimeoutMsForBytes,Rq as upsertCredential,Cl as upsertProjectGitCredential,wl as upsertProjectSecret,$0 as upsertSsoProvider,Mc as validateProjectManifest,I$ as validateReferralCode,Cc as validateToken,v$ as verifyGatewayProvider,RM as verifyKortixToken,li as verifyOtp,F0 as verifySsoDomain,tQ as wakeEscalationAttemptSummary,eQ as wakeEscalationNote,XJ as wakeProgressFingerprint,Kt as wireIdClock,wn as wireIdClockAt,qt as wireIdClockDelta,QV as workedForLabel,UJ as workingExpiryAtMs,EV as workingTurnDrawsBusyRow,tB as writeActivityGroupLabel,Ss as writeFile,na as wsDomain,$H as wsFavicon,LH as wsRootDomain};
|